2021-03-01 18:04:59 +00:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/anacrolix/torrent"
|
|
|
|
"github.com/distribyted/distribyted/config"
|
|
|
|
"github.com/distribyted/distribyted/fs"
|
|
|
|
"github.com/distribyted/distribyted/stats"
|
2021-03-10 09:54:56 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
2021-03-01 18:04:59 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Handler struct {
|
|
|
|
c *torrent.Client
|
|
|
|
s *stats.Torrent
|
|
|
|
|
|
|
|
fssMu sync.Mutex
|
2021-03-06 22:08:15 +00:00
|
|
|
fss map[string]fs.Filesystem
|
2021-03-01 18:04:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewHandler(c *torrent.Client, s *stats.Torrent) *Handler {
|
|
|
|
return &Handler{
|
|
|
|
c: c,
|
|
|
|
s: s,
|
2021-03-06 22:08:15 +00:00
|
|
|
fss: make(map[string]fs.Filesystem),
|
2021-03-01 18:04:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-04 17:24:58 +00:00
|
|
|
func (s *Handler) Load(route string, ts []*config.Torrent) error {
|
2021-03-06 22:08:15 +00:00
|
|
|
var torrents []*torrent.Torrent
|
2021-03-01 18:04:59 +00:00
|
|
|
for _, mpcTorrent := range ts {
|
|
|
|
var t *torrent.Torrent
|
|
|
|
var err error
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case mpcTorrent.MagnetURI != "":
|
|
|
|
t, err = s.c.AddMagnet(mpcTorrent.MagnetURI)
|
|
|
|
case mpcTorrent.TorrentPath != "":
|
|
|
|
t, err = s.c.AddTorrentFromFile(mpcTorrent.TorrentPath)
|
|
|
|
default:
|
|
|
|
err = fmt.Errorf("no magnet URI or torrent path provided")
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// only get info if name is not available
|
|
|
|
if t.Name() == "" {
|
2021-03-10 09:54:56 +00:00
|
|
|
log.Info().Str("hash", t.InfoHash().String()).Msg("getting torrent info")
|
2021-03-01 18:04:59 +00:00
|
|
|
<-t.GotInfo()
|
|
|
|
}
|
|
|
|
|
2021-04-04 17:24:58 +00:00
|
|
|
s.s.Add(route, t)
|
2021-03-06 22:08:15 +00:00
|
|
|
torrents = append(torrents, t)
|
2021-03-01 18:04:59 +00:00
|
|
|
|
2021-04-04 17:24:58 +00:00
|
|
|
log.Info().Str("name", t.Name()).Str("route", route).Msg("torrent added to mountpoint")
|
2021-03-01 18:04:59 +00:00
|
|
|
}
|
|
|
|
|
2021-04-04 17:24:58 +00:00
|
|
|
folder := "/" + route
|
2021-03-01 18:04:59 +00:00
|
|
|
|
|
|
|
s.fssMu.Lock()
|
|
|
|
defer s.fssMu.Unlock()
|
2021-03-06 22:08:15 +00:00
|
|
|
s.fss[folder] = fs.NewTorrent(torrents)
|
2021-03-01 18:04:59 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-03-06 22:08:15 +00:00
|
|
|
func (s *Handler) Fileststems() map[string]fs.Filesystem {
|
2021-03-01 18:04:59 +00:00
|
|
|
return s.fss
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Handler) RemoveAll() error {
|
|
|
|
s.fssMu.Lock()
|
|
|
|
defer s.fssMu.Unlock()
|
|
|
|
|
2021-03-06 22:08:15 +00:00
|
|
|
s.fss = make(map[string]fs.Filesystem)
|
2021-03-01 18:04:59 +00:00
|
|
|
s.s.RemoveAll()
|
|
|
|
return nil
|
|
|
|
}
|