-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathtracker.go
More file actions
57 lines (48 loc) · 1.26 KB
/
Copy pathtracker.go
File metadata and controls
57 lines (48 loc) · 1.26 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
package torrentfile
import (
"net/http"
"net/url"
"strconv"
"time"
"github.com/veggiedefender/torrent-client/peers"
"github.com/jackpal/bencode-go"
)
type bencodeTrackerResp struct {
Interval int `bencode:"interval"`
Peers string `bencode:"peers"`
}
func (t *TorrentFile) buildTrackerURL(peerID [20]byte, port uint16) (string, error) {
base, err := url.Parse(t.Announce)
if err != nil {
return "", err
}
params := url.Values{
"info_hash": []string{string(t.InfoHash[:])},
"peer_id": []string{string(peerID[:])},
"port": []string{strconv.Itoa(int(Port))},
"uploaded": []string{"0"},
"downloaded": []string{"0"},
"compact": []string{"1"},
"left": []string{strconv.Itoa(t.Length)},
}
base.RawQuery = params.Encode()
return base.String(), nil
}
func (t *TorrentFile) requestPeers(peerID [20]byte, port uint16) ([]peers.Peer, error) {
url, err := t.buildTrackerURL(peerID, port)
if err != nil {
return nil, err
}
c := &http.Client{Timeout: 15 * time.Second}
resp, err := c.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
trackerResp := bencodeTrackerResp{}
err = bencode.Unmarshal(resp.Body, &trackerResp)
if err != nil {
return nil, err
}
return peers.Unmarshal([]byte(trackerResp.Peers))
}