-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
bhd.go
92 lines (79 loc) · 2.21 KB
/
bhd.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
package tracker
import (
"encoding/json"
"fmt"
"github.com/l3uddz/tqm/httputils"
"github.com/l3uddz/tqm/logger"
"github.com/lucperkins/rek"
"github.com/sirupsen/logrus"
"go.uber.org/ratelimit"
"net/http"
"strings"
"time"
)
type BHDConfig struct {
Key string `koanf:"api_key"`
}
type BHD struct {
cfg BHDConfig
http *http.Client
log *logrus.Entry
}
func NewBHD(c BHDConfig) *BHD {
l := logger.GetLogger("bhd-api")
return &BHD{
cfg: c,
http: httputils.NewRetryableHttpClient(15*time.Second, ratelimit.New(1, ratelimit.WithoutSlack), l),
log: l,
}
}
func (c *BHD) Name() string {
return "BHD"
}
func (c *BHD) Check(host string) bool {
return strings.Contains(host, "beyond-hd.me")
}
func (c *BHD) IsUnregistered(torrent *Torrent) (error, bool) {
type Request struct {
Hash string `json:"info_hash"`
Action string `json:"action"`
}
type Response struct {
StatusCode int `json:"status_code"`
Page int `json:"page"`
Results []struct {
Name string `json:"name"`
InfoHash string `json:"info_hash"`
} `json:"results"`
TotalPages int `json:"total_pages"`
TotalResults int `json:"total_results"`
Success bool `json:"success"`
}
// prepare request
url := httputils.Join("https://beyond-hd.me/api/torrents", c.cfg.Key)
payload := &Request{
Hash: torrent.Hash,
Action: "search",
}
// send request
resp, err := rek.Post(url, rek.Client(c.http), rek.Json(payload))
if err != nil {
c.log.WithError(err).Errorf("Failed searching for %s (hash: %s)", torrent.Name, torrent.Hash)
return fmt.Errorf("bhd: request search: %w", err), false
}
defer resp.Body().Close()
// validate response
if resp.StatusCode() != 200 {
c.log.WithError(err).Errorf("Failed validating search response for %s (hash: %s), response: %s",
torrent.Name, torrent.Hash, resp.Status())
return fmt.Errorf("bhd: validate search response: %s", resp.Status()), false
}
// decode response
b := new(Response)
if err := json.NewDecoder(resp.Body()).Decode(b); err != nil {
c.log.WithError(err).Errorf("Failed decoding search response for %s (hash: %s)",
torrent.Name, torrent.Hash)
return fmt.Errorf("bhd: decode search response: %w", err), false
}
return nil, b.TotalResults < 1
}