-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtorrent.go
76 lines (61 loc) · 1.75 KB
/
torrent.go
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
package objects
import (
"crypto/md5"
"fmt"
"sync"
bencode "github.com/rakshasa/bencode-go"
"github.com/rakshasa/rbedit/types"
)
func NewTorrentInfo(rootObject interface{}) (types.TorrentInfo, error) {
if _, ok := AsMap(rootObject); !ok {
return types.TorrentInfo{}, fmt.Errorf("root is not a map")
}
infoMap, ok := AsMap(LookupKey(rootObject, "info"))
if !ok {
return types.TorrentInfo{}, fmt.Errorf("missing valid info entry")
}
isStrictlyCompliant := true
if _, ok := AsString(LookupKey(rootObject, "announce")); !ok {
isStrictlyCompliant = false
}
if _, ok := AsInteger(LookupKey(infoMap, "piece length")); !ok {
isStrictlyCompliant = false
}
if _, ok := AsString(LookupKey(infoMap, "pieces")); !ok {
isStrictlyCompliant = false
}
name, ok := AsString(LookupKey(infoMap, "name"))
if !ok {
return types.TorrentInfo{}, fmt.Errorf("missing valid info::name entry")
}
if _, ok := AsInteger(LookupKey(infoMap, "length")); ok {
// Do nothing.
} else if _, ok := AsList(LookupKey(infoMap, "files")); ok {
// Do nothing.
} else {
isStrictlyCompliant = false
}
var cachedLock sync.Mutex
var cachedMD5Hash *types.MD5Hash
hashFn := func() (types.MD5Hash, error) {
cachedLock.Lock()
defer cachedLock.Unlock()
if cachedMD5Hash == nil {
hasher := md5.New()
if err := bencode.Marshal(hasher, infoMap); err != nil {
return types.MD5Hash{}, fmt.Errorf("failed to calculate info hash: %v", err)
}
md5Hash, err := types.NewMD5HashFromHasher(hasher)
if err != nil {
return types.MD5Hash{}, err
}
cachedMD5Hash = &md5Hash
}
return *cachedMD5Hash, nil
}
torrentInfo, err := types.NewTorrentInfo(name, hashFn, isStrictlyCompliant)
if err != nil {
return types.TorrentInfo{}, nil
}
return *torrentInfo, nil
}