-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexer.go
567 lines (497 loc) · 12.4 KB
/
indexer.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package main
import "time"
import "log"
import "path/filepath"
import "encoding/json"
import "strings"
import "strconv"
import "regexp"
import "os"
import "path"
import "fmt"
import (
"github.com/boltdb/bolt"
"github.com/cytec/releaseparser"
)
type Indexer struct {
Conf *Config
db *bolt.DB
connPool *ConnectionPool
imdb *IMDB
pckgChs [] (chan PackageMsg)
timeToScan chan bool
announcementCh chan PrivMsg
}
type Package struct {
ID string
Server string
Channel string
Bot string
Package string
Filename string
Size string
Gets string
Time string
Release Release
}
type Release struct {
IMDBId string
AvgRating float64
NumVotes int
releaseparser.Release
}
type Downloaded struct {
Filename string
Location string
ReleaseID uint
}
func (i *Indexer) TriggerRescan() {
select {
case i.timeToScan<-true:
default:
}
}
func (i *Indexer) OfferAllToTasks() {
for {
log.Print("starting to offer all packages to tasks")
i.db.View(func(tx *bolt.Tx) error {
pBucket := tx.Bucket([]byte("packages"))
c := pBucket.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
i.offerPackageToTasks(tx, PackageFromJSON(v), true)
}
return nil
})
log.Print("done to offer all packages to tasks")
select {
case <-time.After(10*time.Minute):
case <-i.timeToScan:
log.Print("full db scan triggered")
}
}
}
func (i *Indexer) ExpirePackages() {
for {
i.db.Update(func(tx *bolt.Tx) error {
expirationTime := time.Now().Add(-4 * time.Hour)
pBucket := tx.Bucket([]byte("packages"))
c := pBucket.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
p := PackageFromJSON(v)
t,_ := time.Parse(time.RFC850, p.Time)
if t.Before(expirationTime) {
i.removePackage(tx, &p)
}
}
return nil
})
time.Sleep(10*time.Minute)
}
}
func (i *Indexer) addDownloaded(tx *bolt.Tx, r Release) {
dBucket := tx.Bucket([]byte("downloaded"))
dBucket.Put([]byte(r.key()), []byte(r.json()))
log.Print("putting " + r.key() + " = " + string(r.json()))
}
func (i *Indexer) AddDownloaded(r Release) {
err := i.db.Update(func(tx *bolt.Tx) error {
i.addDownloaded(tx, r)
return nil
})
if err != nil {
log.Print("bolt err")
log.Print(err)
}
}
func (i *Indexer) CheckDownloadedExact(p Package) bool {
panic("not implemented")
return false
}
func (i *Indexer) releaseDownloaded(tx *bolt.Tx, r *Release) (downloaded bool) {
dBucket := tx.Bucket([]byte("downloaded"))
if dBucket.Get([]byte(r.key())) != nil {
downloaded = true
} else {
downloaded = false
}
return downloaded
}
func (i *Indexer) ReleaseDownloaded(r *Release) (downloaded bool) {
err := i.db.Update(func(tx *bolt.Tx) error {
downloaded = i.releaseDownloaded(tx, r)
return nil
})
if err != nil {
log.Print("bolt err")
log.Print(err)
}
return downloaded
}
func (i *Indexer) ResetDownloaded() bool {
// tx := i.db.Begin()
i.db.Update(func(tx *bolt.Tx) error {
// tx.Exec("DELETE FROM downloadeds;")
for _,dir := range i.Conf.GetDirs() {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", dir, err)
return err
}
if !info.IsDir() {
p := Package{Filename: info.Name()}
r := p.Parse()
i.addDownloaded(tx, r)
}
fmt.Printf("visited file: %q\n", path)
return nil
})
if err != nil {
fmt.Printf("error walking the path %q: %v\n", dir, err)
}
}
return nil
})
//err := tx.Commit()
//return err != nil
return true
}
func (i *Indexer) CheckDownloaded(p Package) bool {
//i.db.LogMode(true)
r := i.getReleaseForPackage(p)//p.Parse()
if r.Type == "movie" {
return i.ReleaseDownloaded(&Release{Release: releaseparser.Release{Type: r.Type, Title: r.Title, Year: r.Year}})
} else if (r.Type == "tvshow") {
return i.ReleaseDownloaded(&Release{Release: releaseparser.Release{Type: r.Type, Title: r.Title, Season: r.Season, Episode: r.Episode}})
}
return false
}
func (i *Indexer) EnrichWithIMDB(r *Release) {
var id string
if r.Type == "movie" {
id = i.imdb.GetIdForMovie(r.Title, r.Year)
} else {
id = i.imdb.GetIdForShow(r.Title)
}
if id != "" {
rating, _ := i.imdb.GetRating(id)
r.IMDBId = id
r.AvgRating = rating
// r.NumVotes = num
}
}
func (i *Indexer) EnrichAll() {
/*
var rs []Release
tx := i.db.Begin()
i.db.Where(Release{IMDBId:""}).Find(&rs)
for _, r := range(rs) {
i.EnrichWithIMDB(&r)
tx.Save(r)
log.Print(r)
}
tx.Commit()
*/
}
func (p Package) Parse() Release {
return Release{Release: *releaseparser.Parse(p.Filename)}
}
func (p *Package) SizeMbytes() float64 {
size := strings.Trim(p.Size, " ")
if len(size) == 0 {
return -1
}
lastC := size[len(size)-1:]
s,err := strconv.ParseFloat(size[:len(size)-1], 64)
if err != nil {
return -1
}
if lastC == "M" {
return s
}
if lastC == "G" {
return s*1024
}
return -1
}
func (p *Package) TargetFolder() string {
// TODO: make sure one cant move outside of download directory...
pp := p.Parse()
if pp.Type == "tvshow" {
return fmt.Sprintf("%s/Season %d/",pp.Title, pp.Season)
} else {
return pp.Title
}
}
func PackageFromJSON(b []byte) Package {
var r Package
err := json.Unmarshal(b, &r)
if err != nil {
log.Print("json err")
log.Print(err)
}
return r
}
func ReleaseFromJSON(b []byte) Release {
var r Release
err := json.Unmarshal(b, &r)
if err != nil {
panic("couldnt parse json")
}
return r
}
func (i *Indexer) getReleaseForPackage(p Package) (release Release) {
if p.Release.Type == "" {
err := i.db.View(func(tx *bolt.Tx) error {
rBucket := tx.Bucket([]byte("releases"))
if r := rBucket.Get([]byte(p.Filename)); r != nil {
release = ReleaseFromJSON(r)
} else {
release = p.Parse()
}
return nil
})
if err != nil {
log.Print("bolt err")
log.Print(err)
}
} else {
release = p.Release
}
return release
}
func (i *Indexer) AddNewPackageSubscription(ch chan PackageMsg) {
i.pckgChs = append(i.pckgChs, ch)
}
func (i *Indexer) offerPackageToTasks(tx *bolt.Tx, p Package, block bool) {
pd := PackageMsg{Package: p, Downloaded:i.releaseDownloaded(tx, &p.Release)}
for _,ch := range i.pckgChs {
if !block {
select {
case ch<-pd:
default:
log.Print("offer channel full")
}
} else {
select {
case ch<-pd:
case <-time.After(1*time.Second):
log.Print("blocked 1 sec, timeout")
}
}
}
}
func (i *Indexer) AddPackage(p Package) {
panic("not implemented")
/*if !i.UpdateIfExists(p) {
// p.Release = i.getReleaseForPackage(p)
}
*/
}
func (p Release) key() string {
return strings.ToLower(fmt.Sprintf("%s:%d:%s:%d:%d", p.Type, p.Year,p.Title, p.Season, p.Episode))
}
func (p Package) key() string {
return p.Server + ":" + p.Channel + ":" + p.Bot + ":" + p.Package
}
func (p Package) isDifferentTo(p2 Package) bool {
if p.Filename != p2.Filename {
return true
} else {
return false
}
}
func (p Release) json() []byte {
b, err := json.Marshal(p)
if err == nil {
return b
} else {
return []byte("")
}
}
func (p Package) json() []byte {
b, err := json.Marshal(p)
if err == nil {
return b
} else {
return []byte("")
}
}
func (i *Indexer) addPackage(tx *bolt.Tx, p Package) {
pBucket := tx.Bucket([]byte("packages"))
rBucket := tx.Bucket([]byte("releases"))
pDb := pBucket.Get([]byte(p.key()))
if release := rBucket.Get([]byte(p.Filename)); release != nil {
p.Release = ReleaseFromJSON(release)
} else {
p.Release = p.Parse()
i.EnrichWithIMDB(&p.Release)
rBucket.Put([]byte(p.Filename), p.Release.json())
}
p.ID = p.key()
if pDb == nil || PackageFromJSON(pDb).isDifferentTo(p) {
i.offerPackageToTasks(tx, p, false)
}
pBucket.Put([]byte(p.key()), p.json())
}
/*func (i *Indexer) GetPackage(id int) (bool, Package) {
var pack Package
i.db.First(&pack, id)
return true, pack
}*/
func (i *Indexer) RemovePackage(p *Package) {
err := i.db.Update(func(tx *bolt.Tx) error {
i.removePackage(tx, p)
return nil
})
if err != nil {
log.Print("bolt err")
log.Print(err)
}
}
func (i *Indexer) removePackage(tx *bolt.Tx, p *Package) {
tx.Bucket([]byte("packages")).Delete([]byte(p.key()))
}
func (i *Indexer) Search(name string) []Package {
var res []Package
var count int64
i.db.View(func(tx *bolt.Tx) error {
pBucket := tx.Bucket([]byte("packages"))
words := strings.Split(strings.ToLower(name), " ")
c := pBucket.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
count++
containsAll := true
for _,w := range words {
if !strings.Contains(strings.ToLower(string(v)), w) {
containsAll = false
break
}
}
if containsAll {
res = append(res, PackageFromJSON(v))
}
}
return nil
})
log.Print("searched through ",count)
return res
}
func (i *Indexer) SetupDB() {
p := path.Join(i.Conf.DBPath, ".indexer.bdb")
db, err := bolt.Open(p, 0600, nil)
if err != nil {
log.Fatal(err)
}
db.Update(func(tx *bolt.Tx) error {
tx.CreateBucketIfNotExists([]byte("packages"))
tx.CreateBucketIfNotExists([]byte("releases"))
tx.CreateBucketIfNotExists([]byte("downloaded"))
return nil
})
i.db = db
}
func (i *Indexer) GetPackage(id string) (found bool, p Package) {
i.db.View(func(tx *bolt.Tx) error {
v := tx.Bucket([]byte("packages")).Get([]byte(id))
if v == nil {
found = false
} else {
found = true
p = PackageFromJSON(v)
}
return nil
})
return found, p
}
func (indx* Indexer) WaitForPackages(ch chan PrivMsg) {
listingRegexp := regexp.MustCompile(`(#[0-9]*)[^0-9]*([0-9]*x)[^\[]*\[([ 0-9.]+(?:M|G)?)\][^\x21-\x7E]*(.*)`)
colorRegexp := regexp.MustCompile(`\x03[0-9,]*([^\x03]*)\x03`)
var cache []Package
for {
select {
case msg := <-ch:
if listingRegexp.MatchString(msg.Content) {
matches := listingRegexp.FindStringSubmatch(colorRegexp.ReplaceAllString(msg.Content, "$1"))
nmb, gets, size, name := matches[1], matches[2], strings.Trim(matches[3]," \r\n\u000f"), strings.Trim(matches[4], " \r\n\u000f")
cache= append(cache, Package{Server: msg.Server, Channel: msg.To, Bot: msg.From, Package: nmb, Filename: name, Size: size, Gets: gets, Time: time.Now().Format(time.RFC850)})
if len(cache) > 99 {
err := indx.db.Update(func(tx *bolt.Tx) error {
for _,p := range cache {
indx.addPackage(tx, p)
}
return nil
})
if err != nil {
log.Print("bolt err")
log.Print(err)
}
log.Print("written to db")
cache = []Package{}
}
}
}
}
}
func (indx* Indexer) setupChannelListener(server string, channel string) bool {
connPool := indx.connPool
i := connPool.GetConnection(server)
suc := false
for a:= 0; a<1&&!suc; a++ {
suc = /*i.Connect() &&*/ i!=nil && i.JoinChannel(channel)
time.Sleep(time.Duration(0*a)*time.Second)
i = connPool.GetConnection(server)
}
if !suc {
log.Print("Coulndt connect to ", server, channel)
return false
}
i.SubscriptionCh<-PrivMsgSubscription{Once:false, Backchannel: indx.announcementCh, To:channel}
return true
}
func CreateIndexer(c *Config, connPool *ConnectionPool) *Indexer {
indx := Indexer{Conf: c, connPool: connPool, timeToScan: make(chan bool,1)}
indx.SetupDB()
indx.imdb = CreateIMDB(c)
indx.announcementCh = make(chan PrivMsg, 100)
for _,el := range c.Channels {
if !indx.setupChannelListener(el.Server, el.Channel) {
//return nil
}
}
for i :=0; i<2; i++ {
go indx.WaitForPackages(indx.announcementCh)
}
go indx.ExpirePackages()
go indx.OfferAllToTasks()
return &indx
}
func (indx *Indexer) InitWatchDog() {
go func() {
for {
indx.watchDog()
time.Sleep(60*time.Second)
}
}()
}
func (indx *Indexer) watchDog() bool {
log.Print("watch dog checking connections")
connectionReset := false
for _,el := range indx.Conf.Channels {
// if CheckChannels fails, we possibly lost connection to the server...
ircConn := indx.connPool.GetConnection(el.Server)
if ircConn == nil || !ircConn.StillConnected() {
log.Print("watch dog resetting " + el.Server)
indx.connPool.Quit(el.Server)
indx.setupChannelListener(el.Server, el.Channel)
connectionReset = true
} else if !ircConn.CheckChannel(el.Channel) {
log.Print("watch dog rejoining " + el.Channel)
if ircConn.JoinChannel(el.Channel) {
log.Print("rejoined " + el.Channel)
} else {
log.Print("failed to rejoin " + el.Channel)
}
}
}
return connectionReset
}