2017-05-17 07:58:40 +02:00
package metainfoFetcher
2017-05-13 19:58:48 +02:00
import (
"errors"
2017-05-17 07:58:40 +02:00
"github.com/NyaaPantsu/nyaa/config"
"github.com/NyaaPantsu/nyaa/model"
"github.com/NyaaPantsu/nyaa/util"
"github.com/anacrolix/torrent/metainfo"
2017-05-13 19:58:48 +02:00
"strings"
2017-05-17 07:58:40 +02:00
"time"
2017-05-13 19:58:48 +02:00
)
type FetchOperation struct {
2017-05-17 07:58:40 +02:00
fetcher * MetainfoFetcher
torrent model . Torrent
done chan int
2017-05-13 19:58:48 +02:00
}
type Result struct {
operation * FetchOperation
err error
info * metainfo . Info
}
2017-05-14 13:20:34 +02:00
func NewFetchOperation ( fetcher * MetainfoFetcher , dbEntry model . Torrent ) ( op * FetchOperation ) {
2017-05-13 19:58:48 +02:00
op = & FetchOperation {
2017-05-17 07:58:40 +02:00
fetcher : fetcher ,
torrent : dbEntry ,
done : make ( chan int , 1 ) ,
2017-05-13 19:58:48 +02:00
}
return
}
// Should be started from a goroutine somewhere
func ( op * FetchOperation ) Start ( out chan Result ) {
2017-05-13 21:07:39 +02:00
defer op . fetcher . wg . Done ( )
2017-05-13 19:58:48 +02:00
magnet := util . InfoHashToMagnet ( strings . TrimSpace ( op . torrent . Hash ) , op . torrent . Name , config . Trackers ... )
downloadingTorrent , err := op . fetcher . torrentClient . AddMagnet ( magnet )
if err != nil {
out <- Result { op , err , nil }
return
}
2017-05-14 23:10:39 +02:00
defer downloadingTorrent . Drop ( )
2017-05-13 19:58:48 +02:00
2017-05-14 23:10:39 +02:00
timeoutTimer := time . NewTicker ( time . Second * time . Duration ( op . fetcher . timeout ) )
defer timeoutTimer . Stop ( )
2017-05-13 19:58:48 +02:00
select {
case <- downloadingTorrent . GotInfo ( ) :
out <- Result { op , nil , downloadingTorrent . Info ( ) }
2017-05-13 21:07:39 +02:00
break
2017-05-14 23:10:39 +02:00
case <- timeoutTimer . C :
2017-05-13 19:58:48 +02:00
out <- Result { op , errors . New ( "Timeout" ) , nil }
2017-05-13 21:07:39 +02:00
break
2017-05-13 19:58:48 +02:00
case <- op . done :
2017-05-13 21:07:39 +02:00
break
2017-05-13 19:58:48 +02:00
}
}