-
Notifications
You must be signed in to change notification settings - Fork 18
/
brush.go
304 lines (287 loc) · 10.9 KB
/
brush.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package brush
import (
"fmt"
"math/rand"
"path/filepath"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/sagan/ptool/client"
"github.com/sagan/ptool/cmd"
"github.com/sagan/ptool/cmd/brush/strategy"
"github.com/sagan/ptool/config"
"github.com/sagan/ptool/site"
"github.com/sagan/ptool/stats"
"github.com/sagan/ptool/util"
"github.com/sagan/ptool/util/torrentutil"
)
var command = &cobra.Command{
Use: "brush {client} {site | group}...",
Annotations: map[string]string{"cobra-prompt-dynamic-suggestions": "brush"},
Short: "Brush sites using client.",
Long: `Brush sites using client.`,
Args: cobra.MatchAll(cobra.MinimumNArgs(2), cobra.OnlyValidArgs),
RunE: brush,
}
var (
dryRun = false
addPaused = false
ordered = false
force = false
maxSites = int64(0)
)
func init() {
command.Flags().BoolVarP(&dryRun, "dry-run", "d", false, "Dry run. Do not actually controlling client")
command.Flags().BoolVarP(&addPaused, "add-paused", "", false, "Add torrents to client in paused state")
command.Flags().BoolVarP(&ordered, "ordered", "", false, "Brush sites provided in order")
command.Flags().BoolVarP(&force, "force", "", false, "Force mode. Ignore _noadd flag in client")
command.Flags().Int64VarP(&maxSites, "max-sites", "", -1, "Allowed max succcess sites number, -1 == no limit")
cmd.RootCmd.AddCommand(command)
}
func brush(cmd *cobra.Command, args []string) error {
clientInstance, err := client.CreateClient(args[0])
if err != nil {
return err
}
if clientInstance.GetClientConfig().Type == "transmission" {
log.Warnf("Warning: brush function of transmission client has NOT been tested")
}
sitenames := config.ParseGroupAndOtherNamesWithoutDeduplicate(args[1:]...)
if !ordered {
rand.Shuffle(len(sitenames), func(i, j int) { sitenames[i], sitenames[j] = sitenames[j], sitenames[i] })
}
cntSuccessSite := int64(0)
cntSkipSite := int64(0)
cntAddTorrents := int64(0)
cntDeleteTorrents := int64(0)
doneSiteFlag := map[string]bool{}
var statDb *stats.StatDb
if config.Get().BrushEnableStats {
statDb, err = stats.NewDb(filepath.Join(config.ConfigDir, config.STATS_FILENAME))
if err != nil {
log.Warnf("Failed to create stats db: %v.", err)
}
}
for i, sitename := range sitenames {
if doneSiteFlag[sitename] {
continue
}
doneSiteFlag[sitename] = true
siteInstance, err := site.CreateSite(sitename)
if err != nil {
log.Errorf("Failed to get instance of site %s: %v", sitename, err)
continue
}
log.Printf("Brush client %s site %s", clientInstance.GetName(), sitename)
status, err := clientInstance.GetStatus()
if err != nil {
log.Printf("Failed to get client %s status: %v", clientInstance.GetName(), err)
continue
}
noadd := !force && status.NoAdd
var siteTorrents []site.Torrent
if status.UploadSpeedLimit > 0 && (status.UploadSpeedLimit < strategy.SLOW_UPLOAD_SPEED ||
(float64(status.UploadSpeed)/float64(status.UploadSpeedLimit)) >= strategy.BANDWIDTH_FULL_PERCENT) {
log.Printf(
"Client %s upload bandwidth is already full (Upload speed/limit: %s/s/%s/s). Do not fetch site new torrents\n",
clientInstance.GetName(),
util.BytesSize(float64(status.UploadSpeed)),
util.BytesSize(float64(status.UploadSpeedLimit)),
)
} else if !siteInstance.GetSiteConfig().BrushAllowHr && siteInstance.GetSiteConfig().GlobalHnR {
log.Printf("Site %s enforces global HnR. Do not fetch site new torrents", sitename)
} else if noadd {
log.Printf("Client %s in NoAdd status. Do not fetch site new torrents", clientInstance.GetName())
} else {
siteTorrents, err = siteInstance.GetLatestTorrents(true)
if err != nil {
log.Printf("failed to fetch site %s torrents: %v", sitename, err)
}
}
clientTorrents, err := clientInstance.GetTorrents("", config.BRUSH_CAT, true)
if err != nil {
log.Printf("Failed to get client %s torrents: %v ", clientInstance.GetName(), err)
continue
}
brushSiteOption := strategy.GetBrushSiteOptions(siteInstance, util.Now())
brushClientOption := strategy.GetBrushClientOptions(clientInstance)
log.Printf(
"Brush Options: minDiskSpace=%v, slowUploadSpeedTier=%v, torrentUploadSpeedLimit=%v/s,"+
" maxDownloadingTorrents=%d, maxTorrents=%d, minRatio=%f",
util.BytesSize(float64(brushClientOption.MinDiskSpace)),
util.BytesSize(float64(brushClientOption.SlowUploadSpeedTier)),
util.BytesSize(float64(brushSiteOption.TorrentUploadSpeedLimit)),
brushClientOption.MaxDownloadingTorrents,
brushClientOption.MaxTorrents,
brushClientOption.MinRatio,
)
result := strategy.Decide(status, clientTorrents, siteTorrents, brushSiteOption, brushClientOption)
log.Printf(
"Current client %s torrents: %d; Download speed / limit: %s/s / %s/s; Upload speed / limit: %s/s / %s/s;Free disk space: %s;",
clientInstance.GetName(),
len(clientTorrents),
util.BytesSize(float64(status.DownloadSpeed)),
util.BytesSize(float64(status.DownloadSpeedLimit)),
util.BytesSize(float64(status.UploadSpeed)),
util.BytesSize(float64(status.UploadSpeedLimit)),
util.BytesSize(float64(status.FreeSpaceOnDisk)),
)
log.Printf(
"Fetched site %s torrents: %d; Client add / modify / stall / delete torrents: %d / %d / %d / %d. Msg: %s",
siteInstance.GetName(),
len(siteTorrents),
len(result.AddTorrents),
len(result.ModifyTorrents),
len(result.StallTorrents),
len(result.DeleteTorrents),
result.Msg,
)
// delete
for _, torrent := range result.DeleteTorrents {
clientTorrent := util.FindInSlice(clientTorrents, func(t client.Torrent) bool {
return t.InfoHash == torrent.InfoHash
})
// double check
if clientTorrent == nil || clientTorrent.Category != config.BRUSH_CAT {
log.Warnf("Invalid torrent deletion target: %s", torrent.InfoHash)
continue
}
duration := brushSiteOption.Now - clientTorrent.Atime
log.Printf("Delete client %s torrent: %v / %v / %v.", clientInstance.GetName(), torrent.Name, torrent.InfoHash, torrent.Msg)
log.Printf("Torrent total downloads / uploads: %s / %s; Lifespan: %s; Average download / upload speed of lifespan: %s/s / %s/s",
util.BytesSize(float64(clientTorrent.Downloaded)),
util.BytesSize(float64(clientTorrent.Uploaded)),
util.GetDurationString(duration),
util.BytesSize(float64(clientTorrent.Downloaded)/float64(duration)),
util.BytesSize(float64(clientTorrent.Uploaded)/float64(duration)),
)
if dryRun {
continue
}
err := clientInstance.DeleteTorrents([]string{torrent.InfoHash}, true)
log.Printf("Delete torrent result: error=%v", err)
if err == nil {
cntDeleteTorrents++
if statDb != nil {
statDb.AddTorrentStat(brushSiteOption.Now, 1, &stats.TorrentStat{
Client: clientInstance.GetName(),
Site: clientTorrent.GetSiteFromTag(),
InfoHash: clientTorrent.InfoHash,
Category: clientTorrent.Category,
Name: clientTorrent.Name,
Atime: clientTorrent.Atime,
Size: clientTorrent.Size,
Uploaded: clientTorrent.Uploaded,
Downloaded: clientTorrent.Downloaded,
Msg: torrent.Msg,
})
}
}
}
// stall
for _, torrent := range result.StallTorrents {
log.Printf("Stall client %s torrent: %v / %v / %v", clientInstance.GetName(), torrent.Name, torrent.InfoHash, torrent.Msg)
if dryRun {
continue
}
err := clientInstance.ModifyTorrent(torrent.InfoHash, &client.TorrentOption{
DownloadSpeedLimit: strategy.STALL_DOWNLOAD_SPEED,
}, torrent.Meta)
log.Printf("Stall torrent result: error=%v", err)
}
// resume
if len(result.ResumeTorrents) > 0 {
for _, torrent := range result.ResumeTorrents {
log.Printf("Resume client %s torrent: %v / %v / %v", clientInstance.GetName(), torrent.Name, torrent.InfoHash, torrent.Msg)
}
if !dryRun {
err := clientInstance.ResumeTorrents(util.Map(result.ResumeTorrents, func(t strategy.AlgorithmOperationTorrent) string {
return t.InfoHash
}))
log.Printf("Resume torrents result: error=%v", err)
}
}
// modify
for _, torrent := range result.ModifyTorrents {
log.Printf("Modify client %s torrent: %v / %v / %v / %v ", clientInstance.GetName(), torrent.Name, torrent.InfoHash, torrent.Msg, torrent.Meta)
if dryRun {
continue
}
err := clientInstance.ModifyTorrent(torrent.InfoHash, nil, torrent.Meta)
log.Printf("Modify torrent result: error=%v", err)
}
// add
cndAddTorrents := 0
for _, torrent := range result.AddTorrents {
log.Printf("Add site %s torrent to client %s: %s / %s / %v", siteInstance.GetName(), clientInstance.GetName(), torrent.Name, torrent.Msg, torrent.Meta)
if dryRun {
continue
}
torrentdata, _, _, err := siteInstance.DownloadTorrent(torrent.DownloadUrl)
if err != nil {
log.Printf("Failed to download: %s. Skip \n", err)
continue
}
tinfo, err := torrentutil.ParseTorrent(torrentdata, 99)
if err != nil {
continue
}
pClientTorrent, _ := clientInstance.GetTorrent(tinfo.InfoHash)
if pClientTorrent != nil {
log.Printf("Already existing in client. skip\n")
continue
}
if clientInstance.TorrentRootPathExists(tinfo.RootDir) {
log.Printf("torrent rootpath %s existing in client. skip\n", tinfo.RootDir)
continue
}
log.Printf("torrent info: %s\n", tinfo.InfoHash)
cndAddTorrents++
torrentOption := &client.TorrentOption{
Name: torrent.Name,
Pause: addPaused,
Category: config.BRUSH_CAT,
Tags: []string{client.GenerateTorrentTagFromSite(siteInstance.GetName())},
UploadSpeedLimit: siteInstance.GetSiteConfig().TorrentUploadSpeedLimitValue,
}
// torrentname := fmt.Sprint(torrent.Name, "_", i, ".torrent")
// os.WriteFile(tmpdir+"/"+torrentname, torrentdata, 0666)
if !dryRun {
err = clientInstance.AddTorrent(torrentdata, torrentOption, torrent.Meta)
log.Printf("Add torrent result: error=%v", err)
if err == nil {
cntAddTorrents++
}
}
}
if len(result.AddTorrents) > 0 {
cntSuccessSite++
} else {
cntSkipSite++
}
if noadd {
log.Printf("Client in NoAdd status. Skip follow sites.")
cntSkipSite += int64(len(sitenames) - 1 - i)
break
}
if maxSites >= 0 && cntSuccessSite >= maxSites {
log.Printf("MaxSites reached. Stop brushing.")
cntSkipSite += int64(len(sitenames) - 1 - i)
break
}
if !result.CanAddMore {
log.Printf("Client capacity is full. Stop brushing.")
cntSkipSite += int64(len(sitenames) - 1 - i)
break
}
if i < len(sitenames)-1 && (len(result.AddTorrents) > 0 || len(result.ModifyTorrents) > 0 || len(result.DeleteTorrents) > 0 || len(result.StallTorrents) > 0) {
clientInstance.PurgeCache()
util.Sleep(3)
}
}
fmt.Printf("Finish brushing %d sites: successSites=%d, skipSites=%d; Added / Deleted torrents: %d / %d to client %s\n",
len(sitenames), cntSuccessSite, cntSkipSite, cntAddTorrents, cntDeleteTorrents, clientInstance.GetName())
if cntSuccessSite == 0 {
return fmt.Errorf("no sites successed")
}
return nil
}