2020-04-27 16:46:23 +00:00
|
|
|
package mount
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/ajnavarro/distribyted/config"
|
|
|
|
"github.com/ajnavarro/distribyted/node"
|
2020-05-02 12:06:18 +00:00
|
|
|
"github.com/ajnavarro/distribyted/stats"
|
2020-04-27 16:46:23 +00:00
|
|
|
"github.com/anacrolix/torrent"
|
|
|
|
"github.com/hanwen/go-fuse/v2/fs"
|
|
|
|
"github.com/hanwen/go-fuse/v2/fuse"
|
|
|
|
"github.com/panjf2000/ants/v2"
|
|
|
|
)
|
|
|
|
|
2020-05-02 12:06:18 +00:00
|
|
|
type Torrent struct {
|
2020-04-27 16:46:23 +00:00
|
|
|
c *torrent.Client
|
2020-05-02 12:06:18 +00:00
|
|
|
s *stats.Torrent
|
2020-04-27 16:46:23 +00:00
|
|
|
opts *fs.Options
|
|
|
|
|
|
|
|
pool *ants.Pool
|
|
|
|
servers map[string]*fuse.Server
|
|
|
|
}
|
|
|
|
|
2020-05-02 12:06:18 +00:00
|
|
|
func NewTorrent(c *torrent.Client, pool *ants.Pool, s *stats.Torrent) *Torrent {
|
|
|
|
return &Torrent{
|
2020-04-27 16:46:23 +00:00
|
|
|
c: c,
|
2020-05-02 12:06:18 +00:00
|
|
|
s: s,
|
2020-04-27 16:46:23 +00:00
|
|
|
opts: &fs.Options{},
|
|
|
|
pool: pool,
|
|
|
|
servers: make(map[string]*fuse.Server),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-02 12:06:18 +00:00
|
|
|
func (s *Torrent) Mount(mpc *config.MountPoint) error {
|
2020-04-27 16:46:23 +00:00
|
|
|
var torrents []*torrent.Torrent
|
|
|
|
for _, magnet := range mpc.Magnets {
|
|
|
|
t, err := s.c.AddMagnet(magnet.URI)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
log.Println("getting torrent info", t.Name())
|
|
|
|
<-t.GotInfo()
|
2020-05-02 12:06:18 +00:00
|
|
|
|
|
|
|
s.s.Add(t)
|
|
|
|
|
2020-04-27 16:46:23 +00:00
|
|
|
log.Println("torrent info obtained", t.Name())
|
|
|
|
torrents = append(torrents, t)
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO change permissions
|
2020-05-02 12:06:18 +00:00
|
|
|
if err := os.MkdirAll(mpc.Path, 0770); err != nil && !os.IsExist(err) {
|
|
|
|
log.Println("UFFF", err)
|
2020-04-27 16:46:23 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
node := node.NewRoot(torrents, s.pool)
|
|
|
|
server, err := fs.Mount(mpc.Path, node, s.opts)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
s.servers[mpc.Path] = server
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-05-02 12:06:18 +00:00
|
|
|
func (s *Torrent) Close() {
|
2020-04-27 16:46:23 +00:00
|
|
|
for path, server := range s.servers {
|
|
|
|
log.Println("unmounting", path)
|
|
|
|
err := server.Unmount()
|
|
|
|
if err != nil {
|
|
|
|
log.Println("unmount failed", path, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|