mirror of
https://github.com/ap-pauloafonso/ratio-spoof.git
synced 2026-03-11 17:45:32 +00:00
some corrections and tests2
This commit is contained in:
parent
f9ca05394d
commit
804fe5c0de
6 changed files with 356 additions and 83 deletions
|
|
@ -45,7 +45,13 @@ type torrentDict struct {
|
|||
}
|
||||
|
||||
//TorrentDictParse decodes the bencoded bytes and builds the torrentInfo file
|
||||
func TorrentDictParse(dat []byte) (*TorrentInfo, error) {
|
||||
func TorrentDictParse(dat []byte) (torrent *TorrentInfo, err error) {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
err = e.(error)
|
||||
}
|
||||
}()
|
||||
|
||||
dict, _ := mapParse(0, &dat)
|
||||
torrentMap := torrentDict{resultMap: dict}
|
||||
return &TorrentInfo{
|
||||
|
|
@ -54,7 +60,7 @@ func TorrentDictParse(dat []byte) (*TorrentInfo, error) {
|
|||
TotalSize: torrentMap.extractTotalSize(),
|
||||
TrackerInfo: torrentMap.extractTrackerInfo(),
|
||||
InfoHashURLEncoded: torrentMap.extractInfoHashURLEncoded(dat),
|
||||
}, nil
|
||||
}, err
|
||||
}
|
||||
|
||||
func (T *torrentDict) extractInfoHashURLEncoded(rawData []byte) string {
|
||||
|
|
@ -115,10 +121,16 @@ func (T *torrentDict) extractTrackerInfo() *TrackerInfo {
|
|||
return &trackerInfo
|
||||
}
|
||||
|
||||
//Decode accepts a byte slice and returns a map with information parsed.(panic if it fails)
|
||||
func Decode(data []byte) map[string]interface{} {
|
||||
//Decode accepts a byte slice and returns a map with information parsed.
|
||||
func Decode(data []byte) (dataMap map[string]interface{}, err error) {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
err = e.(error)
|
||||
}
|
||||
}()
|
||||
|
||||
result, _ := findParse(0, &data)
|
||||
return result.(map[string]interface{})
|
||||
return result.(map[string]interface{}), err
|
||||
}
|
||||
|
||||
func findParse(currentIdx int, data *[]byte) (result interface{}, nextIdx int) {
|
||||
|
|
|
|||
|
|
@ -106,7 +106,8 @@ func TestDecode(T *testing.T) {
|
|||
for _, f := range files {
|
||||
T.Run(f.Name(), func(t *testing.T) {
|
||||
data, _ := ioutil.ReadFile("./torrent_files_test/" + f.Name())
|
||||
t.Log(Decode(data)["info"].(map[string]interface{})["name"])
|
||||
result, _ := Decode(data)
|
||||
t.Log(result["info"].(map[string]interface{})["name"])
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,12 @@ import (
|
|||
"github.com/ap-pauloafonso/ratio-spoof/internal/bencode"
|
||||
)
|
||||
|
||||
const (
|
||||
minPortNumber = 1
|
||||
maxPortNumber = 65535
|
||||
speedSuffixLength = 4
|
||||
)
|
||||
|
||||
type InputArgs struct {
|
||||
TorrentPath string
|
||||
InitialDownloaded string
|
||||
|
|
@ -51,8 +57,8 @@ func (I *InputArgs) ParseInput(torrentInfo *bencode.TorrentInfo) (*InputParsed,
|
|||
return nil, err
|
||||
}
|
||||
|
||||
if I.Port < 1 || I.Port > 65535 {
|
||||
return nil, errors.New("port number must be between 1 and 65535")
|
||||
if I.Port < minPortNumber || I.Port > maxPortNumber {
|
||||
return nil, errors.New(fmt.Sprint("port number must be between %i and %i", minPortNumber, maxPortNumber))
|
||||
}
|
||||
|
||||
return &InputParsed{InitialDownloaded: downloaded,
|
||||
|
|
@ -75,7 +81,10 @@ func checkSpeedSufix(input string) (valid bool, suffix string) {
|
|||
}
|
||||
|
||||
func extractInputInitialByteCount(initialSizeInput string, totalBytes int, errorIfHigher bool) (int, error) {
|
||||
byteCount := strSize2ByteSize(initialSizeInput, totalBytes)
|
||||
byteCount, err := strSize2ByteSize(initialSizeInput, totalBytes)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if errorIfHigher && byteCount > totalBytes {
|
||||
return 0, errors.New("initial downloaded can not be higher than the torrent size")
|
||||
}
|
||||
|
|
@ -84,66 +93,96 @@ func extractInputInitialByteCount(initialSizeInput string, totalBytes int, error
|
|||
}
|
||||
return byteCount, nil
|
||||
}
|
||||
|
||||
//Takes an dirty speed input and returns the bytes per second based on the suffixes
|
||||
// example 1kbps(string) > 1024 bytes per second (int)
|
||||
func extractInputByteSpeed(initialSpeedInput string) (int, error) {
|
||||
ok, suffix := checkSpeedSufix(initialSpeedInput)
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("speed must be in %v", validSpeedSufixes)
|
||||
}
|
||||
number, _ := strconv.ParseFloat(initialSpeedInput[:len(initialSpeedInput)-4], 64)
|
||||
if number < 0 {
|
||||
speedVal, err := strconv.ParseFloat(initialSpeedInput[:len(initialSpeedInput)-speedSuffixLength], 64)
|
||||
if err != nil {
|
||||
return 0, errors.New("invalid speed number")
|
||||
}
|
||||
if speedVal < 0 {
|
||||
return 0, errors.New("speed can not be negative")
|
||||
}
|
||||
|
||||
if suffix == "kbps" {
|
||||
number *= 1024
|
||||
speedVal *= 1024
|
||||
} else {
|
||||
number = number * 1024 * 1024
|
||||
speedVal = speedVal * 1024 * 1024
|
||||
}
|
||||
ret := int(number)
|
||||
ret := int(speedVal)
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func strSize2ByteSize(input string, totalSize int) int {
|
||||
lowerInput := strings.ToLower(input)
|
||||
|
||||
parseStrNumberFn := func(strWithSufix string, sufixLength, n int) int {
|
||||
v, _ := strconv.ParseFloat(strWithSufix[:len(lowerInput)-sufixLength], 64)
|
||||
result := v * math.Pow(1024, float64(n))
|
||||
return int(result)
|
||||
func extractByteSizeNumber(strWithSufix string, sufixLength, power int) (int, error) {
|
||||
v, err := strconv.ParseFloat(strWithSufix[:len(strWithSufix)-sufixLength], 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
result := v * math.Pow(1024, float64(power))
|
||||
return int(result), nil
|
||||
}
|
||||
|
||||
func strSize2ByteSize(input string, totalSize int) (int, error) {
|
||||
lowerInput := strings.ToLower(input)
|
||||
invalidSizeError := errors.New("invalid input size")
|
||||
switch {
|
||||
case strings.HasSuffix(lowerInput, "kb"):
|
||||
{
|
||||
return parseStrNumberFn(lowerInput, 2, 1)
|
||||
v, err := extractByteSizeNumber(lowerInput, 2, 1)
|
||||
if err != nil {
|
||||
return 0, invalidSizeError
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
case strings.HasSuffix(lowerInput, "mb"):
|
||||
{
|
||||
return parseStrNumberFn(lowerInput, 2, 2)
|
||||
v, err := extractByteSizeNumber(lowerInput, 2, 2)
|
||||
if err != nil {
|
||||
return 0, invalidSizeError
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
case strings.HasSuffix(lowerInput, "gb"):
|
||||
{
|
||||
return parseStrNumberFn(lowerInput, 2, 3)
|
||||
v, err := extractByteSizeNumber(lowerInput, 2, 3)
|
||||
if err != nil {
|
||||
return 0, invalidSizeError
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
case strings.HasSuffix(lowerInput, "tb"):
|
||||
{
|
||||
return parseStrNumberFn(lowerInput, 2, 4)
|
||||
v, err := extractByteSizeNumber(lowerInput, 2, 4)
|
||||
if err != nil {
|
||||
return 0, invalidSizeError
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
case strings.HasSuffix(lowerInput, "b"):
|
||||
{
|
||||
return parseStrNumberFn(lowerInput, 1, 0)
|
||||
v, err := extractByteSizeNumber(lowerInput, 1, 0)
|
||||
if err != nil {
|
||||
return 0, invalidSizeError
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
case strings.HasSuffix(lowerInput, "%"):
|
||||
{
|
||||
v, _ := strconv.ParseFloat(lowerInput[:len(lowerInput)-1], 64)
|
||||
if v < 0 || v > 100 {
|
||||
panic("percent value must be in (0-100)")
|
||||
v, err := strconv.ParseFloat(lowerInput[:len(lowerInput)-1], 64)
|
||||
if v < 0 || v > 100 || err != nil {
|
||||
return 0, errors.New("percent value must be in (0-100)")
|
||||
}
|
||||
result := int(float64(v/100) * float64(totalSize))
|
||||
|
||||
return result
|
||||
return result, nil
|
||||
}
|
||||
|
||||
default:
|
||||
panic("Size not found")
|
||||
return 0, errors.New("Size not found")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,34 +1,245 @@
|
|||
package input
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func CheckError(out error, want error, t *testing.T) {
|
||||
t.Helper()
|
||||
if out == nil && want == nil {
|
||||
return
|
||||
}
|
||||
if out != nil && want == nil {
|
||||
t.Errorf("got %v, want %v", out.Error(), "")
|
||||
}
|
||||
if out == nil && want != nil {
|
||||
t.Errorf("got %v, want %v", "", want.Error())
|
||||
}
|
||||
if out != nil && want != nil && out.Error() != want.Error() {
|
||||
t.Errorf("got %v, want %v", out.Error(), want.Error())
|
||||
}
|
||||
|
||||
}
|
||||
func TestExtractInputInitialByteCount(T *testing.T) {
|
||||
data := []struct {
|
||||
name string
|
||||
inSize string
|
||||
inTotal int
|
||||
inErrorIfHigher bool
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "[Donwloaded - error if higher]100kb input with 200kb limit shouldn't return error test",
|
||||
inSize: "100kb",
|
||||
inTotal: 204800,
|
||||
inErrorIfHigher: true,
|
||||
},
|
||||
{
|
||||
name: "[Donwloaded - error if higher]300kb input with 200kb limit should return error test",
|
||||
inSize: "300kb",
|
||||
inTotal: 204800,
|
||||
inErrorIfHigher: true,
|
||||
err: errors.New("initial downloaded can not be higher than the torrent size"),
|
||||
},
|
||||
{
|
||||
name: "[Uploaded]100kb input with 200kb limit shouldn't return error test",
|
||||
inSize: "100kb",
|
||||
inTotal: 204800,
|
||||
inErrorIfHigher: false,
|
||||
},
|
||||
{
|
||||
name: "[Uploaded]300kb input with 200kb limit shouldn't return error test",
|
||||
inSize: "300kb",
|
||||
inTotal: 204800,
|
||||
inErrorIfHigher: false,
|
||||
},
|
||||
{
|
||||
name: "[Donwloaded] -100kb should return negative number error test",
|
||||
inSize: "-100kb",
|
||||
inTotal: 204800,
|
||||
inErrorIfHigher: true,
|
||||
err: errors.New("initial value can not be negative"),
|
||||
},
|
||||
{
|
||||
name: "[Uploaded] -100kb should return negative number error test",
|
||||
inSize: "-100kb",
|
||||
inTotal: 204800,
|
||||
inErrorIfHigher: false,
|
||||
err: errors.New("initial value can not be negative"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, td := range data {
|
||||
T.Run(td.name, func(t *testing.T) {
|
||||
_, err := extractInputInitialByteCount(td.inSize, td.inTotal, td.inErrorIfHigher)
|
||||
CheckError(err, td.err, t)
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestStrSize2ByteSize(T *testing.T) {
|
||||
|
||||
data := []struct {
|
||||
name string
|
||||
in string
|
||||
inTotalSize int
|
||||
out int
|
||||
err error
|
||||
}{
|
||||
{"100kb", 100, 102400},
|
||||
{"1kb", 0, 1024},
|
||||
{"1mb", 0, 1048576},
|
||||
{"1gb", 0, 1073741824},
|
||||
{"1.5gb", 0, 1610612736},
|
||||
{"1tb", 0, 1099511627776},
|
||||
{"1b", 0, 1},
|
||||
{"100%", 10737418240, 10737418240},
|
||||
{"55%", 943718400, 519045120},
|
||||
{
|
||||
name: "100kb test",
|
||||
in: "100kb",
|
||||
inTotalSize: 100,
|
||||
out: 102400,
|
||||
},
|
||||
{
|
||||
name: "1kb test",
|
||||
in: "1kb",
|
||||
inTotalSize: 0,
|
||||
out: 1024,
|
||||
},
|
||||
{
|
||||
name: "1mb test",
|
||||
in: "1mb",
|
||||
inTotalSize: 0,
|
||||
out: 1048576,
|
||||
},
|
||||
{
|
||||
name: "1gb test",
|
||||
in: "1gb",
|
||||
inTotalSize: 0,
|
||||
out: 1073741824,
|
||||
},
|
||||
{
|
||||
name: "1.5gb test",
|
||||
in: "1.5gb",
|
||||
inTotalSize: 0,
|
||||
out: 1610612736,
|
||||
},
|
||||
{
|
||||
name: "1tb test",
|
||||
in: "1tb",
|
||||
inTotalSize: 0,
|
||||
out: 1099511627776,
|
||||
},
|
||||
{
|
||||
name: "1b test",
|
||||
in: "1b",
|
||||
inTotalSize: 0,
|
||||
out: 1,
|
||||
},
|
||||
{
|
||||
name: "10xb test",
|
||||
in: "10xb",
|
||||
inTotalSize: 0,
|
||||
err: errors.New("invalid input size"),
|
||||
},
|
||||
{
|
||||
name: `100% test`,
|
||||
in: "100%",
|
||||
inTotalSize: 10737418240,
|
||||
out: 10737418240,
|
||||
},
|
||||
{
|
||||
name: `55% test`,
|
||||
in: "55%",
|
||||
inTotalSize: 943718400,
|
||||
out: 519045120,
|
||||
},
|
||||
{
|
||||
name: `5kg test`,
|
||||
in: "5kg",
|
||||
err: errors.New("Size not found"),
|
||||
},
|
||||
{
|
||||
name: `-1% test`,
|
||||
in: "-1%",
|
||||
err: errors.New("percent value must be in (0-100)"),
|
||||
},
|
||||
{
|
||||
name: `101% test`,
|
||||
in: "101%",
|
||||
err: errors.New("percent value must be in (0-100)"),
|
||||
},
|
||||
{
|
||||
name: `a% test`,
|
||||
in: "a%",
|
||||
err: errors.New("percent value must be in (0-100)"),
|
||||
},
|
||||
}
|
||||
|
||||
for idx, td := range data {
|
||||
T.Run(fmt.Sprint(idx), func(t *testing.T) {
|
||||
got := strSize2ByteSize(td.in, td.inTotalSize)
|
||||
for _, td := range data {
|
||||
T.Run(td.name, func(t *testing.T) {
|
||||
got, err := strSize2ByteSize(td.in, td.inTotalSize)
|
||||
if td.err != nil {
|
||||
if td.err.Error() != err.Error() {
|
||||
t.Errorf("got %v, want %v", err.Error(), td.err.Error())
|
||||
}
|
||||
}
|
||||
if got != td.out {
|
||||
t.Errorf("got %v, want %v", got, td.out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractInputByteSpeed(T *testing.T) {
|
||||
|
||||
data := []struct {
|
||||
name string
|
||||
speed string
|
||||
expected int
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "1kbps test",
|
||||
speed: "1kbps",
|
||||
expected: 1024,
|
||||
},
|
||||
{
|
||||
name: "1024kbps test",
|
||||
speed: "1024kbps",
|
||||
expected: 1048576,
|
||||
},
|
||||
{
|
||||
name: "1mbps test",
|
||||
speed: "1mbps",
|
||||
expected: 1048576,
|
||||
},
|
||||
{
|
||||
name: "2.5mbps test",
|
||||
speed: "2.5mbps",
|
||||
expected: 2621440,
|
||||
},
|
||||
{
|
||||
name: "2.5tbps test",
|
||||
speed: "2.5tbps",
|
||||
err: errors.New("speed must be in [kbps mbps]"),
|
||||
},
|
||||
{
|
||||
name: "-akbps test",
|
||||
speed: "-akbps",
|
||||
err: errors.New("invalid speed number"),
|
||||
},
|
||||
{
|
||||
name: "-10kbps test",
|
||||
speed: "-10kbps",
|
||||
err: errors.New("speed can not be negative"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, td := range data {
|
||||
T.Run(td.name, func(t *testing.T) {
|
||||
got, err := extractInputByteSpeed(td.speed)
|
||||
if td.err != nil {
|
||||
if td.err.Error() != err.Error() {
|
||||
t.Errorf("got %v, want %v", err.Error(), td.err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if got != td.expected {
|
||||
t.Errorf("got %v, want %v", got, td.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
package ratiospoof
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"math/rand"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
|
@ -70,17 +72,17 @@ func NewRatioSpoofState(input input.InputArgs, torrentClient TorrentClientEmulat
|
|||
|
||||
torrentInfo, err := bencode.TorrentDictParse(dat)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
return nil, errors.New("failed to parse the torrent file")
|
||||
}
|
||||
|
||||
httpTracker, err := tracker.NewHttpTracker(torrentInfo, changeTimerCh)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
inputParsed, err := input.ParseInput(torrentInfo)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &RatioSpoof{
|
||||
|
|
@ -108,6 +110,8 @@ func (R *RatioSpoof) gracefullyExit() {
|
|||
R.Status = "stopped"
|
||||
R.NumWant = 0
|
||||
R.fireAnnounce(false)
|
||||
fmt.Printf("Gracefully exited successfully.\n")
|
||||
|
||||
}
|
||||
|
||||
func (R *RatioSpoof) Run() {
|
||||
|
|
@ -150,7 +154,7 @@ func (R *RatioSpoof) addAnnounce(currentDownloaded, currentUploaded, currentLeft
|
|||
R.AnnounceCount++
|
||||
R.AnnounceHistory.pushValueHistory(AnnounceEntry{Count: R.AnnounceCount, Downloaded: currentDownloaded, Uploaded: currentUploaded, Left: currentLeft, PercentDownloaded: percentDownloaded})
|
||||
}
|
||||
func (R *RatioSpoof) fireAnnounce(retry bool) {
|
||||
func (R *RatioSpoof) fireAnnounce(retry bool) error {
|
||||
lastAnnounce := R.AnnounceHistory.Back().(AnnounceEntry)
|
||||
replacer := strings.NewReplacer("{infohash}", R.TorrentInfo.InfoHashURLEncoded,
|
||||
"{port}", fmt.Sprint(R.Input.Port),
|
||||
|
|
@ -162,12 +166,16 @@ func (R *RatioSpoof) fireAnnounce(retry bool) {
|
|||
"{event}", R.Status,
|
||||
"{numwant}", fmt.Sprint(R.NumWant))
|
||||
query := replacer.Replace(R.BitTorrentClient.Query())
|
||||
trackerResp := R.Tracker.Announce(query, R.BitTorrentClient.Headers(), retry, R.timerUpdateCh)
|
||||
trackerResp, err := R.Tracker.Announce(query, R.BitTorrentClient.Headers(), retry, R.timerUpdateCh)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to reach the tracker:\n%s ", err.Error())
|
||||
}
|
||||
|
||||
if trackerResp != nil {
|
||||
R.updateSeedersAndLeechers(*trackerResp)
|
||||
R.updateInterval(*trackerResp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (R *RatioSpoof) generateNextAnnounce() {
|
||||
R.timerUpdateCh <- R.AnnounceInterval
|
||||
|
|
|
|||
|
|
@ -46,42 +46,37 @@ func (T *HttpTracker) SwapFirst(currentIdx int) {
|
|||
T.Urls[currentIdx] = aux
|
||||
}
|
||||
|
||||
func (T *HttpTracker) Announce(query string, headers map[string]string, retry bool, timerUpdateChannel chan<- int) *TrackerResponse {
|
||||
var trackerResp *TrackerResponse
|
||||
func (T *HttpTracker) Announce(query string, headers map[string]string, retry bool, timerUpdateChannel chan<- int) (*TrackerResponse, error) {
|
||||
defer func() {
|
||||
T.RetryAttempt = 0
|
||||
}()
|
||||
if retry {
|
||||
retryDelay := 30 * time.Second
|
||||
for {
|
||||
exit := false
|
||||
func() {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
timerUpdateChannel <- int(retryDelay.Seconds())
|
||||
T.RetryAttempt++
|
||||
time.Sleep(retryDelay)
|
||||
retryDelay *= 2
|
||||
if retryDelay.Seconds() > 900 {
|
||||
retryDelay = 900
|
||||
}
|
||||
}
|
||||
}()
|
||||
trackerResp = T.tryMakeRequest(query, headers)
|
||||
exit = true
|
||||
}()
|
||||
if exit {
|
||||
break
|
||||
trackerResp, err := T.tryMakeRequest(query, headers)
|
||||
if err != nil {
|
||||
timerUpdateChannel <- int(retryDelay.Seconds())
|
||||
T.RetryAttempt++
|
||||
time.Sleep(retryDelay)
|
||||
retryDelay *= 2
|
||||
if retryDelay.Seconds() > 900 {
|
||||
retryDelay = 900
|
||||
}
|
||||
continue
|
||||
}
|
||||
return trackerResp, nil
|
||||
}
|
||||
|
||||
} else {
|
||||
trackerResp = T.tryMakeRequest(query, headers)
|
||||
resp, err := T.tryMakeRequest(query, headers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
T.RetryAttempt = 0
|
||||
|
||||
return trackerResp
|
||||
|
||||
}
|
||||
|
||||
func (t *HttpTracker) tryMakeRequest(query string, headers map[string]string) *TrackerResponse {
|
||||
func (t *HttpTracker) tryMakeRequest(query string, headers map[string]string) (*TrackerResponse, error) {
|
||||
for idx, baseUrl := range t.Urls {
|
||||
completeURL := buildFullUrl(baseUrl, query)
|
||||
t.LastAnounceRequest = completeURL
|
||||
|
|
@ -94,7 +89,7 @@ func (t *HttpTracker) tryMakeRequest(query string, headers map[string]string) *T
|
|||
if resp.StatusCode == http.StatusOK {
|
||||
bytesR, _ := ioutil.ReadAll(resp.Body)
|
||||
if len(bytesR) == 0 {
|
||||
return nil
|
||||
continue
|
||||
}
|
||||
mimeType := http.DetectContentType(bytesR)
|
||||
if mimeType == "application/x-gzip" {
|
||||
|
|
@ -103,17 +98,24 @@ func (t *HttpTracker) tryMakeRequest(query string, headers map[string]string) *T
|
|||
gzipReader.Close()
|
||||
}
|
||||
t.LastTackerResponse = string(bytesR)
|
||||
decodedResp := bencode.Decode(bytesR)
|
||||
decodedResp, err := bencode.Decode(bytesR)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ret, err := extractTrackerResponse(decodedResp)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if idx != 0 {
|
||||
t.SwapFirst(idx)
|
||||
}
|
||||
ret := extractTrackerResponse(decodedResp)
|
||||
return &ret
|
||||
|
||||
return &ret, nil
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
panic("Connection error with the tracker")
|
||||
return nil, errors.New("Connection error with the tracker")
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -124,15 +126,15 @@ func buildFullUrl(baseurl, query string) string {
|
|||
return baseurl + "?" + strings.TrimLeft(query, "?")
|
||||
}
|
||||
|
||||
func extractTrackerResponse(datatrackerResponse map[string]interface{}) TrackerResponse {
|
||||
func extractTrackerResponse(datatrackerResponse map[string]interface{}) (TrackerResponse, error) {
|
||||
var result TrackerResponse
|
||||
if v, ok := datatrackerResponse["failure reason"].(string); ok && len(v) > 0 {
|
||||
panic(errors.New(v))
|
||||
return result, errors.New(v)
|
||||
}
|
||||
result.MinInterval, _ = datatrackerResponse["min interval"].(int)
|
||||
result.Interval, _ = datatrackerResponse["interval"].(int)
|
||||
result.Seeders, _ = datatrackerResponse["complete"].(int)
|
||||
result.Leechers, _ = datatrackerResponse["incomplete"].(int)
|
||||
return result
|
||||
return result, nil
|
||||
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue