@@ -3,6 +3,9 @@ package recorders
33import (
44 "context"
55 "fmt"
6+ "os"
7+ "path/filepath"
8+ "strings"
69
710 "github.com/gogf/gf/v2/frame/g"
811 "github.com/gogf/gf/v2/os/gctx"
@@ -31,6 +34,10 @@ func liveEndBiz(ctx context.Context, session *lives.LiveSession) {
3134 if enable == 1 {
3235 go message_push .LivePush (gctx .GetInitCtx (), session .State .Anchor , false )
3336 }
37+ autoClean := mr .GetSettingsManager ().GetSetting (consts .SKAutoCleanLittleFile )
38+ if autoClean > 0 {
39+ go cleanLittleFiles (session .Filename , autoClean )
40+ }
3441}
3542
3643func addHistory (ctx context.Context , liveId int , anchor string , startTime , endTime * gtime.Time ) {
@@ -57,3 +64,72 @@ func (*manager) updateName(ctx context.Context, session *lives.LiveSession) {
5764 }
5865 service .UpdateRoomInfo (ctx , session )
5966}
67+
68+ func cleanLittleFiles (filename string , fileSize int ) {
69+ if strings .TrimSpace (filename ) == "" || fileSize <= 0 {
70+ return
71+ }
72+
73+ ctx := gctx .GetInitCtx ()
74+ thresholdBytes := int64 (fileSize ) * 1024 * 1024
75+
76+ dir , name := filepath .Split (filename )
77+ ext := filepath .Ext (name )
78+ base := strings .TrimSuffix (name , ext )
79+
80+ origPath := filepath .Join (dir , name )
81+
82+ getFileSize := func (path string ) (int64 , bool ) {
83+ info , err := os .Stat (path )
84+ if err != nil {
85+ if os .IsNotExist (err ) {
86+ return 0 , false
87+ }
88+ return 0 , false
89+ }
90+ if ! info .Mode ().IsRegular () {
91+ return 0 , false
92+ }
93+ return info .Size (), true
94+ }
95+
96+ deleteIfSmall := func (path string , threshold int64 ) bool {
97+ sz , ok := getFileSize (path )
98+ if ! ok {
99+ return false
100+ }
101+ if sz < threshold {
102+ if err := os .Remove (path ); err != nil {
103+ g .Log ().Infof (ctx , "remove failed: %s, err: %v\n " , path , err )
104+ return false
105+ }
106+ g .Log ().Infof (ctx , "removed small file: %s (size=%d bytes, threshold=%d)\n " , path , sz , threshold )
107+ return true
108+ }
109+ return false
110+ }
111+
112+ if _ , exists := getFileSize (origPath ); exists {
113+ _ = deleteIfSmall (origPath , thresholdBytes )
114+ return
115+ }
116+
117+ const maxParts = 1000
118+ deletedAny := false
119+
120+ for i := range maxParts {
121+ partName := fmt .Sprintf ("%s_%03d%s" , base , i , ext )
122+ partPath := filepath .Join (dir , partName )
123+
124+ if _ , ok := getFileSize (partPath ); ! ok {
125+ break
126+ }
127+
128+ deleteIfSmall (partPath , thresholdBytes )
129+ }
130+
131+ if ! deletedAny {
132+ g .Log ().Info (ctx , "no little files found!" )
133+ return
134+ }
135+ }
0 commit comments