-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtask.go
261 lines (235 loc) · 5.86 KB
/
task.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
package trss
import (
"context"
"io/ioutil"
"net/http"
"os"
"path"
"sync"
"time"
"github.com/capric98/t-rss/bencode"
"github.com/capric98/t-rss/feed"
"github.com/capric98/t-rss/filter"
"github.com/capric98/t-rss/receiver"
"github.com/capric98/t-rss/setting"
"github.com/capric98/t-rss/ticker"
"github.com/capric98/t-rss/unit"
"github.com/sirupsen/logrus"
)
type worker struct {
client *http.Client
header map[string][]string
tick *ticker.Ticker
filters []filter.Filter
recvers []receiver.Receiver
quota setting.Quota
delay time.Duration
wpath string
edit *setting.Edit
logger func() *logrus.Entry
ctx context.Context
wg *sync.WaitGroup
}
func (w *worker) prepare(t *setting.Task, num int) {
// check if log directory exists.
if _, e := os.Stat(w.wpath); os.IsNotExist(e) {
e = os.MkdirAll(w.wpath, 0740)
if e != nil {
w.logger().Fatal("create log dir: ", e)
}
}
// make ticker
if t.Rss != nil {
req, err := http.NewRequest(t.Rss.Method, t.Rss.URL, nil)
if err != nil {
w.logger().Fatal(err)
}
req.Header = w.header
w.tick = ticker.NewRssTicker(num, req, w.client, w.logger(), t.Rss.Interval.T)
}
// make filter
w.filters = append(w.filters, filter.NewRegexpFilter(t.Filter.Regexp.Accept, t.Filter.Regexp.Reject))
w.filters = append(w.filters, filter.NewContentSizeFilter(t.Filter.ContentSize.Min.I, t.Filter.ContentSize.Max.I))
// make receiver only if learn==false (num==-1)
if num == -1 {
if t.Receiver.Save != nil {
w.recvers = append(w.recvers, receiver.NewDownload(*t.Receiver.Save))
}
for k, v := range t.Receiver.Client {
w.recvers = append(w.recvers, receiver.NewClient(v["type"], v, k))
}
}
}
func (w *worker) loop() {
defer w.wg.Done()
defer w.tick.Stop()
for {
select {
case <-w.ctx.Done():
return
case items, ok := <-w.tick.C():
if !ok {
w.logger().Debug("ticker closed, return")
return
} // under "learn" mode or ticker crashed
var passed []feed.Item
var accept, reject int
for k := range items {
log := w.logger().WithFields(logrus.Fields{
"author": items[k].Author,
"category": items[k].Category,
"GUID": items[k].GUID,
"size": unit.FormatSize(items[k].Len),
})
// Check if have seen.
historyPath := path.Join(w.wpath, items[k].GUID)
if _, err := os.Stat(historyPath); !os.IsNotExist(err) {
log.Trace("(reject) have seen ", items[k].Title, " before.")
reject++
continue
}
if w.recvers == nil {
// learn -> create history file immediately
hf, err := os.Create(historyPath)
if err != nil {
log.Warn("create history file: ", err)
} else {
hf.Close()
}
} // else create history file at push phase
flag := true
for _, f := range w.filters {
if e := f.Check(&items[k]); e != nil {
flag = false
log.Info("(reject) ", e)
break
}
}
if flag {
accept++
log.Info("(accept) ", items[k].Title)
passed = append(passed, items[k])
} else {
reject++
hf, err := os.Create(historyPath)
if err != nil {
log.Warn("create history file: ", err)
} else {
hf.Close()
}
}
}
w.logger().Info("accepted ", accept, " item(s), rejected ", reject, " item(s).")
go w.push(passed)
}
}
}
func (w *worker) push(items []feed.Item) {
quota := w.quota
mu := sync.Mutex{}
for k := range items {
go func(item feed.Item) {
time.Sleep(w.delay)
// preperation
start := time.Now()
log := w.logger().WithFields(logrus.Fields{
"title": item.Title,
})
// request torrent's body
req, e := http.NewRequest("GET", item.URL, nil)
if e != nil {
log.Warn("new request: ", e)
return
}
req.Header = w.header
resp, e := w.client.Do(req)
for retry := 0; e != nil && retry < 3; retry++ {
resp, e = w.client.Do(req)
}
if e != nil {
log.Warn("client.Do(): ", e)
return
}
body, e := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if e != nil {
log.Warn("read response body: ", e)
return
}
if tLen(body) == -1 {
log.Info("got non-bencoded file, skip")
log.Debug("content: ", string(body))
return
}
// write history
historyPath := path.Join(w.wpath, item.GUID)
if _, err := os.Stat(historyPath); os.IsNotExist(err) {
hf, err := os.Create(historyPath)
if err != nil {
log.Warn("create history file: ", err)
} else {
hf.Close()
}
}
// double check in case of Len=0
if item.Len == 0 {
item.Len = tLen(body)
for _, f := range w.filters {
if e := f.Check(&item); e != nil {
log.Info("(reject in double check) ", e)
return
}
}
}
// check quota
mu.Lock()
if quota.Num > 0 && quota.Size.I >= item.Len {
quota.Num--
quota.Size.I -= item.Len
} else {
log.Info("(drop) quota exceeded (left Num=", quota.Num, " Size=", unit.FormatSize(quota.Size.I), ")")
mu.Unlock()
return
}
mu.Unlock()
if w.edit != nil {
log.Debug("edit torrent...")
body, e = w.edit.EditTorrent(body)
if e != nil {
w.logger().WithFields(logrus.Fields{
"@func": "editTorrent",
}).Warn(e)
return
}
}
// push to every receiver
recvwg := sync.WaitGroup{}
for i := range w.recvers {
recvwg.Add(1)
go func(recv receiver.Receiver) {
err := recv.Push(&item, body)
if err != nil {
log.Warn("push to ", recv.Name(), " : ", err)
} else {
log.WithField("@cost", time.Since(start)).Info("push to ", recv.Name())
}
recvwg.Done()
}(w.recvers[i])
}
// preserve (start)
recvwg.Wait()
}(items[k])
}
}
func tLen(data []byte) (l int64) {
defer func() { _ = recover() }()
result, err := bencode.Decode(data)
if err != nil {
return -1
}
info := result[0].Dict("info")
pl := (info.Dict("piece length")).Value()
ps := int64(len((info.Dict("pieces")).BStr())) / 20
l = pl * ps
return
}