-
Notifications
You must be signed in to change notification settings - Fork 2
/
torrent.go
120 lines (97 loc) · 2.52 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package gotorrent
import (
log "code.google.com/p/tcgl/applog"
"github.com/moretti/gotorrent/bitarray"
"github.com/moretti/gotorrent/metainfo"
"os"
"strings"
"time"
)
type Torrent struct {
ClientId ClientId
Port int
DownloadPath string
Downloaded int
Uploaded int
Pieces []*Piece
PeerManager *PeerManager
Tracker *Tracker
ActivePieces *bitarray.BitArray
CompletedPieces *bitarray.BitArray
Announce string
InfoHash string
CreationDate int
Name string
Length int
PieceHashes string
PieceLength int
PieceCount int
}
func NewTorrent(clientId ClientId, port int, torrent string, downloadPath string) *Torrent {
t := new(Torrent)
t.ClientId = clientId
t.Port = port
t.DownloadPath = downloadPath
t.Downloaded = 0
t.Uploaded = 0
metaInfo := readTorrent(torrent)
t.Announce = metaInfo.Announce
t.InfoHash = metaInfo.InfoHash
t.CreationDate = metaInfo.CreationDate
t.Name = metaInfo.Info.Name
t.Length = metaInfo.Info.Length
t.PieceHashes = metaInfo.Info.Pieces
t.PieceLength = metaInfo.Info.PieceLength
t.PieceCount = t.Length / t.PieceLength
t.Pieces = make([]*Piece, t.PieceCount)
for i := 0; i < t.PieceCount; i++ {
hashIndex := i * 20
t.Pieces[i] = NewPiece(i, t.PieceLength, t.PieceHashes[hashIndex:hashIndex+20])
}
t.ActivePieces = bitarray.New(t.PieceCount)
t.CompletedPieces = bitarray.New(t.PieceCount)
t.Tracker = NewTracker(t.Announce)
t.PeerManager = NewPeerManager(t)
log.Debugf("File Length: %v", t.Length)
log.Debugf("Piece Length: %v", t.PieceLength)
log.Debugf("Piece Count: %v", t.PieceCount)
log.Debugf("Piece Hashes: %v", len(t.PieceHashes))
return t
}
func readTorrent(torrent string) *metainfo.MetaInfo {
if strings.HasPrefix(torrent, "http:") {
panic("Not implemented")
} else if strings.HasPrefix(torrent, "magnet:") {
panic("Not implemented")
} else {
log.Debugf("Opening: %v", torrent)
file, err := os.Open(torrent)
if err != nil {
panic(err)
}
defer func() {
if err := file.Close(); err != nil {
panic(err)
}
}()
metaInfo, err := metainfo.Read(file)
if err != nil {
panic(err)
}
return metaInfo
}
}
func (torrent *Torrent) Test() (err error) {
trackerResponse, err := torrent.Tracker.Peers(
torrent.InfoHash,
torrent.ClientId,
torrent.Port,
torrent.Uploaded,
torrent.Downloaded,
torrent.Length,
)
log.Debugf("Len of addr: %v", len(trackerResponse.PeerAddresses))
torrent.PeerManager.UpdatePeers(trackerResponse.PeerAddresses)
time.Sleep(240 * time.Second)
return
}