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
|
|
|
|
2020-01-02 10:39:35 -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[:])},
|
2022-04-10 20:16:44 +08:00
|
|
|
"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
|
|
|
|
|
}
|
|
|
|
|
|
2020-01-02 10:39:35 -05:00
|
|
|
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
|
|
|
}
|