-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleaner.go
221 lines (188 loc) · 5 KB
/
cleaner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Package cleaner provides functions to clean old .ts files.
package cleaner
import (
"context"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Darkness4/fc2-live-dl-go/video/probe"
"github.com/rs/zerolog/log"
)
// cleanerMutex is used to avoid multiple clean in parallel.
//
// Less stress for CPU, and avoid risks of race condition.
var cleanerMutex sync.Mutex
// Option is the option for the cleaner.
type Option func(*Options)
// Options are the options for the cleaner.
type Options struct {
dryRun bool
probe bool
eligibleAge time.Duration
}
// WithDryRun sets the dryRun option.
func WithDryRun() Option {
return func(o *Options) {
o.dryRun = true
}
}
// WithoutProbe disables the probe.
func WithoutProbe() Option {
return func(o *Options) {
o.probe = false
}
}
// WithEligibleAge sets the minimum time since the modtime of the file to be deleted.
func WithEligibleAge(d time.Duration) Option {
return func(o *Options) {
if d < time.Hour {
log.Warn().
Dur("eligibleAge", d).
Msg("You've set an 'eligible to cleaning' age < 1 hour. You should set an age greater than the duration of the streams.")
}
if d != 0 {
o.eligibleAge = d
}
}
}
func applyOptions(opts []Option) *Options {
o := &Options{
probe: true,
eligibleAge: 48 * time.Hour,
}
for _, opt := range opts {
opt(o)
}
return o
}
// Scan scans the scanDirectory for old .ts files.
func Scan(
scanDirectory string,
opts ...Option,
) (queueForDeletion []string, queueForRenaming []string, err error) {
o := applyOptions(opts)
set := make(map[string]bool)
queueForRenaming = make([]string, 0)
if err := filepath.WalkDir(scanDirectory, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
name := strings.TrimSuffix(d.Name(), filepath.Ext(d.Name()))
if strings.HasSuffix(name, ".combined") {
prefix := strings.TrimSuffix(name, ".combined")
dir := filepath.Dir(path)
finfo, err := d.Info()
if err != nil {
return err
}
// Check if file is eligible for cleaning.
if time.Since(finfo.ModTime()) <= o.eligibleAge {
return nil
}
// Check if file is a video
if o.probe {
if isVideo, err := probe.ContainsVideoOrAudio(path); err != nil {
log.Err(err).Str("path", path).Msg("deletion skipped due to error")
return nil
} else if !isVideo {
return nil
}
}
// Look for .TS files with the same prefix.
entries, err := os.ReadDir(dir)
if err != nil {
return err
}
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), prefix+".") &&
strings.HasSuffix(entry.Name(), ".ts") &&
!strings.Contains(entry.Name(), ".combined.") &&
!entry.IsDir() {
fpath := filepath.Join(dir, entry.Name())
set[fpath] = true
}
}
queueForRenaming = append(queueForRenaming, path)
}
}
return nil
}); err != nil {
return []string{}, []string{}, nil
}
queue := make([]string, 0, len(set))
for k := range set {
queue = append(queue, k)
}
return queue, queueForRenaming, nil
}
// Clean removes old .ts files from the scanDirectory.
func Clean(scanDirectory string, opts ...Option) error {
cleanerMutex.Lock()
defer cleanerMutex.Unlock()
o := applyOptions(opts)
queueForDeletion, queueForRenaming, err := Scan(scanDirectory, opts...)
if err != nil {
return err
}
for _, path := range queueForDeletion {
log.Info().Str("path", path).Msg("deleting old .ts file")
if !o.dryRun {
if err := os.Remove(path); err != nil {
log.Err(err).Str("path", path).Msg("failed to delete old .ts file, skipping...")
}
}
}
for _, path := range queueForRenaming {
ext := filepath.Ext(path)
prefix := strings.TrimSuffix(path, ext)
renamedPath := strings.TrimSuffix(prefix, ".combined") + ext
// Check for conflict
if _, err := os.Stat(renamedPath); err == nil {
log.Info().Str("path", path).Str("to", renamedPath).Msg("cannot rename, file exists")
continue
}
log.Info().Str("path", path).Str("to", renamedPath).Msg("renaming combined file")
if !o.dryRun {
if err := os.Rename(path, renamedPath); err != nil {
log.Err(err).
Str("path", path).
Str("to", renamedPath).
Msg("failed old .ts file, skipping...")
}
}
}
return nil
}
// CleanPeriodically runs the Clean function periodically.
func CleanPeriodically(
ctx context.Context,
scanDirectory string,
interval time.Duration,
opts ...Option,
) {
log.Debug().Msg("scanning for old .ts to be deleted")
if err := Clean(scanDirectory, opts...); err != nil {
log.Err(err).Msg("failed to cleanup .ts files")
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
// Context cancelled, exit the goroutine
return
case <-ticker.C:
// Execute the cleanup routine
go func() {
log.Debug().Msg("scanning for old .ts to be deleted")
if err := Clean(scanDirectory, opts...); err != nil {
log.Err(err).Msg("failed to cleanup .ts files")
}
}()
}
}
}