93 lines
1.8 KiB
Go
93 lines
1.8 KiB
Go
package events
|
|
|
|
import (
|
|
"reflect"
|
|
"time"
|
|
|
|
"git.quimbo.fr/odwrtw/canape/backend/users"
|
|
"github.com/odwrtw/papi"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// TorrentNotifier is a struct implementing the Notifier interface
|
|
type TorrentNotifier struct {
|
|
*Notifier
|
|
user *users.User
|
|
client *papi.Client
|
|
torrents []papi.Torrent
|
|
log *logrus.Entry
|
|
}
|
|
|
|
// Name implements the Notifier interface
|
|
func (t *TorrentNotifier) Name() string {
|
|
return "torrents"
|
|
}
|
|
|
|
// Launch implements the Notifier interface
|
|
func (t *TorrentNotifier) Launch() {
|
|
// Create the timer that will check for the torrents every X seconds
|
|
timeTicker := time.NewTicker(10 * time.Second)
|
|
defer timeTicker.Stop()
|
|
|
|
// Create a new papi client
|
|
client, err := t.user.NewPapiClient()
|
|
if err != nil {
|
|
return
|
|
}
|
|
t.client = client
|
|
|
|
err = t.torrentsUpdate()
|
|
if err != nil {
|
|
t.log.Warnf("got error getting torrent update: %s", err)
|
|
t.FatalError(err)
|
|
return
|
|
}
|
|
|
|
for {
|
|
select {
|
|
case <-timeTicker.C:
|
|
err := t.torrentsUpdate()
|
|
if err != nil {
|
|
t.log.Warnf("got error getting torrent update: %s", err)
|
|
t.FatalError(err)
|
|
return
|
|
}
|
|
case <-t.done:
|
|
t.log.Info("quit torrent notifier")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// FatalError is a wrapper around Notifier FatalError
|
|
func (t *TorrentNotifier) FatalError(err error) {
|
|
t.Notifier.FatalError(t.Name(), err)
|
|
}
|
|
|
|
// torrentsUpdate sends to the eventStream if torrents change
|
|
func (t *TorrentNotifier) torrentsUpdate() error {
|
|
// Get torrents
|
|
torrents, err := t.client.GetTorrents()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if reflect.DeepEqual(t.torrents, torrents) {
|
|
return nil
|
|
}
|
|
|
|
// If they're different, send the event
|
|
event := ServerEvent{
|
|
Event: Event{
|
|
Type: t.Name(),
|
|
Status: OK,
|
|
},
|
|
Data: torrents,
|
|
}
|
|
t.eventStream <- event
|
|
|
|
t.torrents = torrents
|
|
|
|
return nil
|
|
}
|