-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetainfo.go
More file actions
81 lines (73 loc) · 1.9 KB
/
metainfo.go
File metadata and controls
81 lines (73 loc) · 1.9 KB
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
package services
import (
"bytes"
"context"
"sync"
"time"
ts "github.com/bcashier/torrent-store/torrent-store"
"github.com/anacrolix/torrent/metainfo"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
type MetaInfo struct {
cl *TorrentStore
infoHash string
input string
mux sync.Mutex
mi *metainfo.MetaInfo
err error
inited bool
}
const (
META_INFO_INFO_HASH_FLAG = "info-hash"
META_INFO_INPUT_FLAG = "input"
)
func RegisterMetaInfoFlags(c *cli.App) {
c.Flags = append(c.Flags, cli.StringFlag{
Name: META_INFO_INFO_HASH_FLAG,
Usage: "torrent infohash",
EnvVar: "TORRENT_INFO_HASH, INFO_HASH",
})
c.Flags = append(c.Flags, cli.StringFlag{
Name: META_INFO_INPUT_FLAG,
Usage: "torrent file path",
})
}
func NewMetaInfo(c *cli.Context, cl *TorrentStore) *MetaInfo {
return &MetaInfo{cl: cl, infoHash: c.String(META_INFO_INFO_HASH_FLAG), input: c.String(META_INFO_INPUT_FLAG), inited: false}
}
func (s *MetaInfo) Get() (*metainfo.MetaInfo, error) {
s.mux.Lock()
defer s.mux.Unlock()
if s.inited {
return s.mi, s.err
}
s.mi, s.err = s.get()
s.inited = true
return s.mi, s.err
}
func (s *MetaInfo) get() (*metainfo.MetaInfo, error) {
log.Info("Initializing MetaInfo")
if s.input != "" {
log.Info("Loading from file")
return metainfo.LoadFromFile(s.input)
}
c, err := s.cl.Get()
if err != nil {
return nil, errors.Wrap(err, "Failed to get torrent store client")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
r, err := c.Pull(ctx, &ts.PullRequest{InfoHash: s.infoHash})
if err != nil {
return nil, errors.Wrap(err, "Failed to pull torrent from the torrent store")
}
reader := bytes.NewReader(r.Torrent)
mi, err := metainfo.Load(reader)
if err != nil {
return nil, errors.Wrap(err, "Failed to parse torrent")
}
log.Info("Torrent pulled successfully")
return mi, nil
}