forked from Deflix-tv/go-debrid
/
legacy.go
353 lines (320 loc) · 12.2 KB
/
legacy.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package premiumize
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/tidwall/gjson"
"go.uber.org/zap"
debrid "github.com/axutio/go-debrid"
)
type LegacyClientOptions struct {
BaseURL string
Timeout time.Duration
CacheAge time.Duration
ExtraHeaders []string
// When setting this to true, the user's original IP address is read from Auth.IP and forwarded to Premiumize when creating a direct download links.
// Only required if the library is used in an app on a machine
// whose outgoing IP is different from the machine that's going to request the cached file/stream URL.
ForwardOriginIP bool
}
var DefaultLegacyClientOpts = LegacyClientOptions{
BaseURL: "https://www.premiumize.me/api",
Timeout: 5 * time.Second,
CacheAge: 24 * time.Hour,
}
type LegacyClient struct {
baseURL string
httpClient *http.Client
// For API key validity
apiKeyCache debrid.Cache
// For info_hash instant availability
availabilityCache debrid.Cache
cacheAge time.Duration
extraHeaders map[string]string
forwardOriginIP bool
logger *zap.Logger
}
func NewLegacyClient(opts LegacyClientOptions, apiKeyCache, availabilityCache debrid.Cache, logger *zap.Logger) (*LegacyClient, error) {
// Precondition check
if opts.BaseURL == "" {
return nil, errors.New("opts.BaseURL must not be empty")
}
for _, extraHeader := range opts.ExtraHeaders {
if extraHeader != "" {
colonIndex := strings.Index(extraHeader, ":")
if colonIndex <= 0 || colonIndex == len(extraHeader)-1 {
return nil, errors.New("opts.ExtraHeaders elements must have a format like \"X-Foo: bar\"")
}
}
}
extraHeaderMap := make(map[string]string, len(opts.ExtraHeaders))
for _, extraHeader := range opts.ExtraHeaders {
if extraHeader != "" {
extraHeaderParts := strings.SplitN(extraHeader, ":", 2)
extraHeaderMap[extraHeaderParts[0]] = extraHeaderParts[1]
}
}
return &LegacyClient{
baseURL: opts.BaseURL,
httpClient: &http.Client{
Timeout: opts.Timeout,
},
apiKeyCache: apiKeyCache,
availabilityCache: availabilityCache,
cacheAge: opts.CacheAge,
extraHeaders: extraHeaderMap,
forwardOriginIP: opts.ForwardOriginIP,
logger: logger,
}, nil
}
func (c *LegacyClient) TestAPIkey(ctx context.Context, auth Auth) error {
zapFieldDebridSite := zap.String("debridSite", "Premiumize")
zapFieldAPIkey := zap.String("keyOrToken", auth.KeyOrToken)
c.logger.Debug("Testing API key...", zapFieldDebridSite, zapFieldAPIkey)
// Check cache first.
// Note: Only when an API key is valid a cache item was created, becausean API key is probably valid for another 24 hours, while whenan API key is invalid it's likely that the user makes a payment to Premiumize to extend his premium status and make his API key valid again *within* 24 hours.
created, found, err := c.apiKeyCache.Get(auth.KeyOrToken)
if err != nil {
c.logger.Error("Couldn't decode API key cache item", zap.Error(err), zapFieldDebridSite, zapFieldAPIkey)
} else if !found {
c.logger.Debug("API key not found in cache", zapFieldDebridSite, zapFieldAPIkey)
} else if time.Since(created) > (24 * time.Hour) {
expiredSince := time.Since(created.Add(24 * time.Hour))
c.logger.Debug("API key cached as valid, but item is expired", zap.Duration("expiredSince", expiredSince), zapFieldDebridSite, zapFieldAPIkey)
} else {
c.logger.Debug("API key cached as valid", zapFieldDebridSite, zapFieldAPIkey)
return nil
}
resBytes, err := c.get(ctx, c.baseURL+"/account/info", auth)
if err != nil {
return fmt.Errorf("Couldn't fetch user info from www.premiumize.me with the provided API key: %v", err)
}
if gjson.GetBytes(resBytes, "status").String() != "success" {
errMsg := gjson.GetBytes(resBytes, "message").String()
return fmt.Errorf("Got error response from www.premiumize.me: %v", errMsg)
}
c.logger.Debug("API key OK", zapFieldDebridSite, zapFieldAPIkey)
// Create cache item
if err = c.apiKeyCache.Set(auth.KeyOrToken); err != nil {
c.logger.Error("Couldn't cache API key", zap.Error(err), zapFieldDebridSite, zapFieldAPIkey)
}
return nil
}
func (c *LegacyClient) CheckInstantAvailability(ctx context.Context, auth Auth, infoHashes ...string) []string {
zapFieldDebridSite := zap.String("debridSite", "Premiumize")
zapFieldAPItoken := zap.String("keyOrToken", auth.KeyOrToken)
// Precondition check
if len(infoHashes) == 0 {
return nil
}
// Only check the ones of which we don't know that they're valid (or which our knowledge that they're valid is more than 24 hours old).
// We don't cache unavailable ones, because that might change often!
var result []string
infoHashesNotFound := false
infoHashesExpired := false
infoHashesValid := false
requestRequired := false
var unknownAvailailabilityValues []string
for _, infoHash := range infoHashes {
zapFieldInfoHash := zap.String("infoHash", infoHash)
created, found, err := c.availabilityCache.Get(infoHash)
if err != nil {
c.logger.Error("Couldn't decode availability cache item", zap.Error(err), zapFieldInfoHash, zapFieldDebridSite, zapFieldAPItoken)
requestRequired = true
unknownAvailailabilityValues = append(unknownAvailailabilityValues, infoHash)
} else if !found {
infoHashesNotFound = true
requestRequired = true
unknownAvailailabilityValues = append(unknownAvailailabilityValues, infoHash)
} else if time.Since(created) > (c.cacheAge) {
infoHashesExpired = true
requestRequired = true
unknownAvailailabilityValues = append(unknownAvailailabilityValues, infoHash)
} else {
infoHashesValid = true
result = append(result, infoHash)
}
}
var unknownAvailabilityData url.Values
if len(unknownAvailailabilityValues) > 0 {
unknownAvailabilityData = url.Values{"items[]": unknownAvailailabilityValues}
}
if infoHashesNotFound {
if !infoHashesExpired && !infoHashesValid {
c.logger.Debug("No info_hash found in availability cache", zapFieldDebridSite, zapFieldAPItoken)
} else {
c.logger.Debug("Some info_hash not found in availability cache", zapFieldDebridSite, zapFieldAPItoken)
}
}
if infoHashesExpired {
if !infoHashesNotFound && !infoHashesValid {
c.logger.Debug("Availability for all info_hash cached as valid, but they're expired", zapFieldDebridSite, zapFieldAPItoken)
} else {
c.logger.Debug("Availability for some info_hash cached as valid, but items are expired", zapFieldDebridSite, zapFieldAPItoken)
}
}
if infoHashesValid {
if !infoHashesNotFound && !infoHashesExpired {
c.logger.Debug("Availability for all info_hash cached as valid", zapFieldDebridSite, zapFieldAPItoken)
} else {
c.logger.Debug("Availability for some info_hash cached as valid", zapFieldDebridSite, zapFieldAPItoken)
}
}
// Only make HTTP request if we didn't find all hashes in the cache yet
if requestRequired {
url := c.baseURL + "/cache/check"
resBytes, err := c.post(ctx, url, auth, unknownAvailabilityData, false)
if err != nil {
c.logger.Error("Couldn't check torrents' instant availability on www.premiumize.me", zap.Error(err), zapFieldDebridSite, zapFieldAPItoken)
return nil
}
if gjson.GetBytes(resBytes, "status").String() != "success" {
errMsg := gjson.GetBytes(resBytes, "message").String()
c.logger.Error("Got error response from www.premiumize.me", zap.String("errorMessage", errMsg))
return nil
}
boolResponse := gjson.ParseBytes(resBytes).Get("response").Array()
for i, boolItem := range boolResponse {
isAvailable := boolItem.Bool()
if !isAvailable {
continue
}
infoHash := unknownAvailailabilityValues[i]
infoHash = strings.ToUpper(infoHash)
result = append(result, infoHash)
// Create cache item
if err = c.availabilityCache.Set(infoHash); err != nil {
c.logger.Error("Couldn't cache availability", zap.Error(err), zapFieldDebridSite, zapFieldAPItoken)
}
}
}
return result
}
func (c *LegacyClient) GetStreamURL(ctx context.Context, magnetURL string, auth Auth) (string, error) {
zapFieldDebridSite := zap.String("debridSite", "Premiumize")
zapFieldAPIkey := zap.String("keyOrToken", auth.KeyOrToken)
c.logger.Debug("Adding magnet to Premiumize...", zapFieldDebridSite, zapFieldAPIkey)
data := url.Values{}
data.Set("src", magnetURL)
// Premiumize asks for the original IP only for directdl requests
if c.forwardOriginIP {
if auth.IP == "" {
return "", errors.New("auth.IP is empty but client is configured to forward the user's original IP")
}
data.Add("download_ip", auth.IP)
}
resBytes, err := c.post(ctx, c.baseURL+"/transfer/directdl", auth, data, true)
if err != nil {
return "", fmt.Errorf("Couldn't add magnet to Premiumize: %v", err)
}
if gjson.GetBytes(resBytes, "status").String() != "success" {
errMsg := gjson.GetBytes(resBytes, "message").String()
return "", fmt.Errorf("Got error response from www.premiumize.me: %v", errMsg)
}
c.logger.Debug("Finished adding magnet to Premiumize", zapFieldDebridSite, zapFieldAPIkey)
content := gjson.GetBytes(resBytes, "content").Array()
ddlLink, err := selectLink(ctx, content)
if err != nil {
return "", fmt.Errorf("Couldn't find proper link in magnet status: %v", err)
} else if ddlLink == "" {
return "", fmt.Errorf("Couldn't find proper link in magnet status")
}
c.logger.Debug("Created direct download link", zap.String("ddlLink", ddlLink), zapFieldDebridSite, zapFieldAPIkey)
return ddlLink, nil
}
func (c *LegacyClient) get(ctx context.Context, url string, auth Auth) ([]byte, error) {
if auth.OAuth2 {
url += "?access_token=" + auth.KeyOrToken
} else {
url += "?apikey=" + auth.KeyOrToken
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("Couldn't create GET request: %v", err)
}
for headerKey, headerVal := range c.extraHeaders {
req.Header.Add(headerKey, headerVal)
}
c.logger.Debug("Sending request to Premiumize", zap.String("request", fmt.Sprintf("%+v", req)))
res, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Couldn't send GET request: %v", err)
}
defer res.Body.Close()
// Check server response
if res.StatusCode != http.StatusOK {
resBody, _ := ioutil.ReadAll(res.Body)
if len(resBody) == 0 {
return nil, fmt.Errorf("bad HTTP response status: %v (GET request to '%v')", res.Status, url)
}
return nil, fmt.Errorf("bad HTTP response status: %v (GET request to '%v'; response body: '%s')", res.Status, url, resBody)
}
return ioutil.ReadAll(res.Body)
}
func (c *LegacyClient) post(ctx context.Context, urlString string, auth Auth, data url.Values, form bool) ([]byte, error) {
if auth.OAuth2 {
urlString += "?access_token=" + auth.KeyOrToken
} else {
urlString += "?apikey=" + auth.KeyOrToken
}
var req *http.Request
var err error
if form {
req, err = http.NewRequest("POST", urlString, strings.NewReader(data.Encode()))
} else {
// map[string][]string
for k, vals := range data {
for _, val := range vals {
urlString += "&" + url.QueryEscape(k) + "=" + url.QueryEscape(val)
}
}
req, err = http.NewRequest("POST", urlString, nil)
}
if err != nil {
return nil, fmt.Errorf("Couldn't create POST request: %v", err)
}
if form {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
for headerKey, headerVal := range c.extraHeaders {
req.Header.Add(headerKey, headerVal)
}
c.logger.Debug("Sending request to Premiumize", zap.String("request", fmt.Sprintf("%+v", req)))
res, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Couldn't send POST request: %v", err)
}
defer res.Body.Close()
// Check server response
if res.StatusCode != http.StatusOK {
resBody, _ := ioutil.ReadAll(res.Body)
if len(resBody) == 0 {
return nil, fmt.Errorf("bad HTTP response status: %v (GET request to '%v')", res.Status, urlString)
}
return nil, fmt.Errorf("bad HTTP response status: %v (GET request to '%v'; response body: '%s')", res.Status, urlString, resBody)
}
return ioutil.ReadAll(res.Body)
}
func selectLink(ctx context.Context, linkResults []gjson.Result) (string, error) {
// Precondition check
if len(linkResults) == 0 {
return "", fmt.Errorf("Empty slice of content")
}
var link string
var size int64
for _, res := range linkResults {
if res.Get("size").Int() > size {
size = res.Get("size").Int()
link = res.Get("link").String()
}
}
if link == "" {
return "", fmt.Errorf("No link found")
}
return link, nil
}