1
0
mirror of https://github.com/veggiedefender/torrent-client.git synced 2025-11-06 09:29:16 +02:00
Files
torrent-client/torrentfile/tracker.go

58 lines
1.3 KiB
Go
Raw Normal View History

2019-12-29 14:02:50 -05:00
package torrentfile
2019-12-21 23:14:33 -05:00
import (
"net/http"
"net/url"
"strconv"
2020-01-02 10:34:47 -05:00
"time"
2019-12-21 23:14:33 -05:00
"github.com/veggiedefender/torrent-client/peers"
2019-12-21 23:14:33 -05:00
"github.com/jackpal/bencode-go"
)
2019-12-22 14:54:54 -05:00
type bencodeTrackerResp struct {
2019-12-21 23:14:33 -05:00
Interval int `bencode:"interval"`
2020-01-02 13:07:59 -05:00
Peers string `bencode:"peers"`
2019-12-21 23:14:33 -05:00
}
2019-12-29 14:02:50 -05:00
func (t *TorrentFile) buildTrackerURL(peerID [20]byte, port uint16) (string, error) {
2019-12-22 14:54:54 -05:00
base, err := url.Parse(t.Announce)
2019-12-21 23:14:33 -05:00
if err != nil {
return "", err
}
params := url.Values{
2019-12-22 15:19:46 -05:00
"info_hash": []string{string(t.InfoHash[:])},
"peer_id": []string{string(peerID[:])},
"port": []string{strconv.Itoa(int(port))},
2019-12-21 23:14:33 -05:00
"uploaded": []string{"0"},
"downloaded": []string{"0"},
"compact": []string{"1"},
2019-12-22 14:54:54 -05:00
"left": []string{strconv.Itoa(t.Length)},
2019-12-21 23:14:33 -05:00
}
base.RawQuery = params.Encode()
return base.String(), nil
}
func (t *TorrentFile) requestPeers(peerID [20]byte, port uint16) ([]peers.Peer, error) {
2019-12-22 14:54:54 -05:00
url, err := t.buildTrackerURL(peerID, port)
2019-12-21 23:14:33 -05:00
if err != nil {
return nil, err
}
2020-01-02 10:34:47 -05:00
c := &http.Client{Timeout: 15 * time.Second}
resp, err := c.Get(url)
2019-12-21 23:14:33 -05:00
if err != nil {
return nil, err
}
defer resp.Body.Close()
2019-12-22 14:54:54 -05:00
trackerResp := bencodeTrackerResp{}
2019-12-21 23:14:33 -05:00
err = bencode.Unmarshal(resp.Body, &trackerResp)
if err != nil {
return nil, err
}
2020-01-02 13:07:59 -05:00
return peers.Unmarshal([]byte(trackerResp.Peers))
2019-12-21 23:14:33 -05:00
}