fuse integreated
This commit is contained in:
@@ -9,8 +9,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/debridmediamanager.com/zurg/internal/config"
|
||||
"github.com/debridmediamanager.com/zurg/internal/torrent"
|
||||
"github.com/debridmediamanager.com/zurg/pkg/logutil"
|
||||
"github.com/debridmediamanager.com/zurg/pkg/realdebrid"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
@@ -23,13 +23,14 @@ type Downloader struct {
|
||||
lock sync.Mutex
|
||||
storage *Storage
|
||||
c config.ConfigInterface
|
||||
t *torrent.TorrentManager
|
||||
log *zap.SugaredLogger
|
||||
}
|
||||
|
||||
type DownloadCallback func(error, []byte)
|
||||
|
||||
// NewDownloader creates a new download manager
|
||||
func NewDownloader(threads int, storage *Storage, bufferSize int64, c config.ConfigInterface) (*Downloader, error) {
|
||||
func NewDownloader(threads int, storage *Storage, bufferSize int64, t *torrent.TorrentManager, c config.ConfigInterface) (*Downloader, error) {
|
||||
rlog := logutil.NewLogger()
|
||||
log := rlog.Named("downloader")
|
||||
|
||||
@@ -39,6 +40,7 @@ func NewDownloader(threads int, storage *Storage, bufferSize int64, c config.Con
|
||||
callbacks: make(map[RequestID][]DownloadCallback, 100),
|
||||
storage: storage,
|
||||
c: c,
|
||||
t: t,
|
||||
log: log,
|
||||
}
|
||||
|
||||
@@ -103,10 +105,7 @@ func (d *Downloader) downloadFromAPI(request *Request, buffer []byte, delay int6
|
||||
time.Sleep(time.Duration(delay) * time.Second)
|
||||
}
|
||||
|
||||
unrestrictFn := func() (*realdebrid.UnrestrictResponse, error) {
|
||||
return realdebrid.UnrestrictLink(d.c.GetToken(), request.file.Link)
|
||||
}
|
||||
resp := realdebrid.RetryUntilOk(unrestrictFn)
|
||||
resp := d.t.UnrestrictUntilOk(request.file.Link)
|
||||
if resp == nil {
|
||||
return fmt.Errorf("cannot unrestrict file %s %s", request.file.Path, request.file.Link)
|
||||
}
|
||||
|
||||
@@ -58,6 +58,7 @@ func NewManager(
|
||||
checkThreads,
|
||||
loadThreads,
|
||||
maxChunks int,
|
||||
t *torrent.TorrentManager,
|
||||
c config.ConfigInterface) (*Manager, error) {
|
||||
|
||||
pageSize := int64(os.Getpagesize())
|
||||
@@ -81,7 +82,7 @@ func NewManager(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
downloader, err := NewDownloader(loadThreads, storage, chunkSize, c)
|
||||
downloader, err := NewDownloader(loadThreads, storage, chunkSize, t, c)
|
||||
if nil != err {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package dav
|
||||
|
||||
func Directory(path string) Response {
|
||||
return Response{
|
||||
Href: customPathEscape(path),
|
||||
Href: "/" + customPathEscape(path),
|
||||
Propstat: PropStat{
|
||||
Prop: Prop{
|
||||
ResourceType: ResourceType{Value: "<d:collection/>"},
|
||||
@@ -14,7 +14,7 @@ func Directory(path string) Response {
|
||||
|
||||
func File(path string, fileSize int64, added string, link string) Response {
|
||||
return Response{
|
||||
Href: customPathEscape(path),
|
||||
Href: "/" + customPathEscape(path),
|
||||
Propstat: PropStat{
|
||||
Prop: Prop{
|
||||
ContentLength: fileSize,
|
||||
|
||||
65
pkg/http/client.go
Normal file
65
pkg/http/client.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/debridmediamanager.com/zurg/internal/config"
|
||||
"github.com/debridmediamanager.com/zurg/pkg/logutil"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type HTTPClient struct {
|
||||
Client *http.Client
|
||||
MaxRetries int
|
||||
Backoff func(attempt int) time.Duration
|
||||
CheckRespStatus func(resp *http.Response, err error, log *zap.SugaredLogger) bool
|
||||
BearerToken string
|
||||
log *zap.SugaredLogger
|
||||
config config.ConfigInterface
|
||||
}
|
||||
|
||||
func (r *HTTPClient) Do(req *http.Request) (*http.Response, error) {
|
||||
if r.config != nil && strings.Contains(req.Host, "download.real-debrid.") {
|
||||
if host := r.config.GetRandomPreferredHost(); host != "" {
|
||||
req.Host = r.config.GetRandomPreferredHost()
|
||||
}
|
||||
}
|
||||
if r.BearerToken != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+r.BearerToken)
|
||||
}
|
||||
var resp *http.Response
|
||||
var err error
|
||||
for attempt := 0; attempt < r.MaxRetries; attempt++ {
|
||||
resp, err = r.Client.Do(req)
|
||||
if !r.CheckRespStatus(resp, err, r.log) {
|
||||
return resp, err
|
||||
}
|
||||
time.Sleep(r.Backoff(attempt))
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func NewHTTPClient(token string, maxRetries int, c config.ConfigInterface) *HTTPClient {
|
||||
return &HTTPClient{
|
||||
BearerToken: token,
|
||||
Client: &http.Client{},
|
||||
MaxRetries: maxRetries,
|
||||
Backoff: func(attempt int) time.Duration {
|
||||
return time.Duration(attempt) * time.Second
|
||||
},
|
||||
CheckRespStatus: func(resp *http.Response, err error, log *zap.SugaredLogger) bool {
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
if resp.StatusCode == 429 {
|
||||
return true
|
||||
}
|
||||
// no need to retry
|
||||
return false
|
||||
},
|
||||
log: logutil.NewLogger().Named("client"),
|
||||
config: c,
|
||||
}
|
||||
}
|
||||
@@ -3,94 +3,70 @@ package realdebrid
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/debridmediamanager.com/zurg/internal/config"
|
||||
zurghttp "github.com/debridmediamanager.com/zurg/pkg/http"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func UnrestrictCheck(accessToken, link string) (*UnrestrictResponse, error) {
|
||||
type RealDebrid struct {
|
||||
log *zap.SugaredLogger
|
||||
client *zurghttp.HTTPClient
|
||||
}
|
||||
|
||||
func NewRealDebrid(accessToken string, config config.ConfigInterface, log *zap.SugaredLogger) *RealDebrid {
|
||||
maxRetries := 10
|
||||
client := zurghttp.NewHTTPClient(accessToken, maxRetries, nil)
|
||||
return &RealDebrid{
|
||||
log: log,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (rd *RealDebrid) UnrestrictCheck(link string) (*UnrestrictResponse, error) {
|
||||
data := url.Values{}
|
||||
data.Set("link", link)
|
||||
|
||||
req, err := http.NewRequest("POST", "https://api.real-debrid.com/rest/1.0/unrestrict/check", bytes.NewBufferString(data.Encode()))
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when creating a unrestrict check request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := rd.client.Do(req)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when executing the unrestrict check request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when reading the body of unrestrict check response: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("HTTP error: %s", resp.Status)
|
||||
}
|
||||
|
||||
var response UnrestrictResponse
|
||||
err = json.Unmarshal(body, &response)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when decoding unrestrict check JSON: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
func UnrestrictLink(accessToken, link string) (*UnrestrictResponse, error) {
|
||||
data := url.Values{}
|
||||
data.Set("link", link)
|
||||
|
||||
req, err := http.NewRequest("POST", "https://api.real-debrid.com/rest/1.0/unrestrict/link", bytes.NewBufferString(data.Encode()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("HTTP error: %s", resp.Status)
|
||||
}
|
||||
|
||||
var response UnrestrictResponse
|
||||
err = json.Unmarshal(body, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !canFetchFirstByte(response.Download) {
|
||||
return nil, fmt.Errorf("can't fetch first byte")
|
||||
}
|
||||
rd.log.Info("Link %s is streamable? %v", response.Streamable)
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
// GetTorrents returns all torrents, paginated
|
||||
// if customLimit is 0, the default limit of 2500 is used
|
||||
func GetTorrents(accessToken string, customLimit int) ([]Torrent, int, error) {
|
||||
func (rd *RealDebrid) GetTorrents(customLimit int) ([]Torrent, int, error) {
|
||||
baseURL := "https://api.real-debrid.com/rest/1.0/torrents"
|
||||
var allTorrents []Torrent
|
||||
page := 1
|
||||
@@ -110,26 +86,24 @@ func GetTorrents(accessToken string, customLimit int) ([]Torrent, int, error) {
|
||||
|
||||
req, err := http.NewRequest("GET", reqURL, nil)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when creating a get torrents request: %v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := rd.client.Do(req)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when executing the get torrents request: %v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, 0, fmt.Errorf("HTTP error: %s", resp.Status)
|
||||
}
|
||||
// if status code is not 2xx, return erro
|
||||
|
||||
var torrents []Torrent
|
||||
decoder := json.NewDecoder(resp.Body)
|
||||
err = decoder.Decode(&torrents)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when decoding get torrents JSON: %v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
@@ -147,39 +121,35 @@ func GetTorrents(accessToken string, customLimit int) ([]Torrent, int, error) {
|
||||
|
||||
page++
|
||||
}
|
||||
|
||||
return allTorrents, totalCount, nil
|
||||
}
|
||||
|
||||
func GetTorrentInfo(accessToken, id string) (*Torrent, error) {
|
||||
func (rd *RealDebrid) GetTorrentInfo(id string) (*TorrentInfo, error) {
|
||||
url := "https://api.real-debrid.com/rest/1.0/torrents/info/" + id
|
||||
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when creating a get info request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := rd.client.Do(req)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when executing the get info request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when reading the body of get info response: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("HTTP error: %s", resp.Status)
|
||||
}
|
||||
|
||||
var response Torrent
|
||||
var response TorrentInfo
|
||||
err = json.Unmarshal(body, &response)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when : %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -187,86 +157,54 @@ func GetTorrentInfo(accessToken, id string) (*Torrent, error) {
|
||||
}
|
||||
|
||||
// SelectTorrentFiles selects files of a torrent to start it.
|
||||
func SelectTorrentFiles(accessToken string, id string, files string) error {
|
||||
// Prepare request data
|
||||
func (rd *RealDebrid) SelectTorrentFiles(id string, files string) error {
|
||||
data := url.Values{}
|
||||
data.Set("files", files)
|
||||
|
||||
// Construct request URL
|
||||
reqURL := fmt.Sprintf("https://api.real-debrid.com/rest/1.0/torrents/selectFiles/%s", id)
|
||||
req, err := http.NewRequest("POST", reqURL, bytes.NewBufferString(data.Encode()))
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when creating a select files request: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Set request headers
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// Send the request
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := rd.client.Do(req)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when executing the select files request: %v", err)
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Handle response status codes
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK, http.StatusNoContent:
|
||||
return nil // Success
|
||||
case http.StatusAccepted:
|
||||
return errors.New("action already done")
|
||||
case http.StatusBadRequest:
|
||||
return errors.New("bad request")
|
||||
case http.StatusUnauthorized:
|
||||
return errors.New("bad token (expired or invalid)")
|
||||
case http.StatusForbidden:
|
||||
return errors.New("permission denied (account locked or not premium)")
|
||||
case http.StatusNotFound:
|
||||
return errors.New("wrong parameter (invalid file id(s)) or unknown resource (invalid id)")
|
||||
default:
|
||||
return fmt.Errorf("unexpected HTTP error: %s", resp.Status)
|
||||
}
|
||||
rd.log.Debugf("Started the download for torrent id=%s", len(strings.Split(files, ",")), id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteTorrent deletes a torrent from the torrents list.
|
||||
func DeleteTorrent(accessToken string, id string) error {
|
||||
func (rd *RealDebrid) DeleteTorrent(id string) error {
|
||||
// Construct request URL
|
||||
reqURL := fmt.Sprintf("https://api.real-debrid.com/rest/1.0/torrents/delete/%s", id)
|
||||
req, err := http.NewRequest("DELETE", reqURL, nil)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when creating a delete torrent request: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Set request headers
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
// Send the request
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := rd.client.Do(req)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when executing the delete torrent request: %v", err)
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Handle response status codes
|
||||
switch resp.StatusCode {
|
||||
case http.StatusNoContent:
|
||||
return nil // Success
|
||||
case http.StatusUnauthorized:
|
||||
return errors.New("bad token (expired or invalid)")
|
||||
case http.StatusForbidden:
|
||||
return errors.New("permission denied (account locked)")
|
||||
case http.StatusNotFound:
|
||||
return errors.New("unknown resource")
|
||||
default:
|
||||
return fmt.Errorf("unexpected HTTP error: %s", resp.Status)
|
||||
}
|
||||
rd.log.Debugf("Deleted torrent with id=%s", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddMagnetHash adds a magnet link to download.
|
||||
func AddMagnetHash(accessToken, magnet string) (*MagnetResponse, error) {
|
||||
func (rd *RealDebrid) AddMagnetHash(magnet string) (*MagnetResponse, error) {
|
||||
// Prepare request data
|
||||
data := url.Values{}
|
||||
data.Set("magnet", fmt.Sprintf("magnet:?xt=urn:btih:%s", magnet))
|
||||
@@ -275,77 +213,94 @@ func AddMagnetHash(accessToken, magnet string) (*MagnetResponse, error) {
|
||||
reqURL := "https://api.real-debrid.com/rest/1.0/torrents/addMagnet"
|
||||
req, err := http.NewRequest("POST", reqURL, bytes.NewBufferString(data.Encode()))
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when creating an add magnet request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Set request headers
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// Send the request
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := rd.client.Do(req)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when executing the add magnet request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Handle response status codes
|
||||
switch resp.StatusCode {
|
||||
case http.StatusCreated:
|
||||
var response MagnetResponse
|
||||
err := json.NewDecoder(resp.Body).Decode(&response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &response, nil
|
||||
case http.StatusBadRequest:
|
||||
return nil, errors.New("bad request")
|
||||
case http.StatusUnauthorized:
|
||||
return nil, errors.New("bad token (expired or invalid)")
|
||||
case http.StatusForbidden:
|
||||
return nil, errors.New("permission denied (account locked or not premium)")
|
||||
case http.StatusServiceUnavailable:
|
||||
return nil, errors.New("service unavailable")
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected HTTP error: %s", resp.Status)
|
||||
var response MagnetResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&response)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when decoding add magnet JSON: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rd.log.Debugf("Added magnet %s with id=%s", magnet, response.ID)
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
// GetActiveTorrentCount gets the number of currently active torrents and the current maximum limit.
|
||||
func GetActiveTorrentCount(accessToken string) (*ActiveTorrentCountResponse, error) {
|
||||
func (rd *RealDebrid) GetActiveTorrentCount() (*ActiveTorrentCountResponse, error) {
|
||||
// Construct request URL
|
||||
reqURL := "https://api.real-debrid.com/rest/1.0/torrents/activeCount"
|
||||
req, err := http.NewRequest("GET", reqURL, nil)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when creating a active torrents request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Set request headers
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
// Send the request
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := rd.client.Do(req)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when executing the active torrents request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Handle response status codes
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK:
|
||||
var response ActiveTorrentCountResponse
|
||||
err := json.NewDecoder(resp.Body).Decode(&response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &response, nil
|
||||
case http.StatusUnauthorized:
|
||||
return nil, errors.New("bad token (expired or invalid)")
|
||||
case http.StatusForbidden:
|
||||
return nil, errors.New("permission denied (account locked)")
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected HTTP error: %s", resp.Status)
|
||||
var response ActiveTorrentCountResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&response)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when decoding active torrents JSON: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
func (rd *RealDebrid) UnrestrictLink(link string) (*UnrestrictResponse, error) {
|
||||
data := url.Values{}
|
||||
data.Set("link", link)
|
||||
|
||||
req, err := http.NewRequest("POST", "https://api.real-debrid.com/rest/1.0/unrestrict/link", bytes.NewBufferString(data.Encode()))
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when creating a unrestrict link request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
resp, err := rd.client.Do(req)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when executing the unrestrict link request: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when reading the body of unrestrict link response: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var response UnrestrictResponse
|
||||
err = json.Unmarshal(body, &response)
|
||||
if err != nil {
|
||||
rd.log.Errorf("Error when decoding unrestrict link JSON: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !canFetchFirstByte(response.Download) {
|
||||
return nil, fmt.Errorf("can't fetch first byte")
|
||||
}
|
||||
|
||||
// rd.log.Debugf("Unrestricted link %s into %s", link, response.Download)
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
106
pkg/realdebrid/network.go
Normal file
106
pkg/realdebrid/network.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package realdebrid
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type IPInfo struct {
|
||||
Address string
|
||||
Hops int
|
||||
Latency time.Duration
|
||||
}
|
||||
|
||||
func traceroute(ip string) (int, time.Duration, error) {
|
||||
cmd := exec.Command("traceroute", "-n", "-q", "1", "-w", "1", ip)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
output := string(out)
|
||||
lines := strings.Split(output, "\n")
|
||||
|
||||
hopCount := len(lines) - 1
|
||||
|
||||
var latency time.Duration
|
||||
if hopCount > 0 {
|
||||
lastLine := lines[hopCount-1]
|
||||
fmt.Println(lastLine)
|
||||
parts := strings.Fields(lastLine)
|
||||
if len(parts) >= 3 {
|
||||
latencyValue, parseErr := strconv.ParseFloat(parts[2], 64)
|
||||
if parseErr == nil {
|
||||
latency = time.Duration(latencyValue * float64(time.Millisecond))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return hopCount, latency, nil
|
||||
}
|
||||
|
||||
func RunTest() {
|
||||
fmt.Println("Running network test...")
|
||||
|
||||
ips := []string{"20.download.real-debrid.cloud", "20.download.real-debrid.com", "21.download.real-debrid.cloud", "21.download.real-debrid.com", "22.download.real-debrid.cloud", "22.download.real-debrid.com", "23.download.real-debrid.cloud", "23.download.real-debrid.com", "30.download.real-debrid.cloud", "30.download.real-debrid.com", "31.download.real-debrid.cloud", "31.download.real-debrid.com", "32.download.real-debrid.cloud", "32.download.real-debrid.com", "34.download.real-debrid.cloud", "34.download.real-debrid.com", "40.download.real-debrid.cloud", "40.download.real-debrid.com", "41.download.real-debrid.cloud", "41.download.real-debrid.com", "42.download.real-debrid.cloud", "42.download.real-debrid.com", "43.download.real-debrid.cloud", "43.download.real-debrid.com", "44.download.real-debrid.cloud", "44.download.real-debrid.com", "45.download.real-debrid.cloud", "45.download.real-debrid.com", "50.download.real-debrid.cloud", "50.download.real-debrid.com", "51.download.real-debrid.cloud", "51.download.real-debrid.com", "52.download.real-debrid.cloud", "52.download.real-debrid.com", "53.download.real-debrid.cloud", "53.download.real-debrid.com", "54.download.real-debrid.cloud", "54.download.real-debrid.com", "55.download.real-debrid.cloud", "55.download.real-debrid.com", "56.download.real-debrid.cloud", "56.download.real-debrid.com", "57.download.real-debrid.cloud", "57.download.real-debrid.com", "58.download.real-debrid.cloud", "58.download.real-debrid.com", "59.download.real-debrid.cloud", "59.download.real-debrid.com", "60.download.real-debrid.cloud", "60.download.real-debrid.com", "61.download.real-debrid.cloud", "61.download.real-debrid.com", "62.download.real-debrid.cloud", "62.download.real-debrid.com", "63.download.real-debrid.cloud", "63.download.real-debrid.com", "64.download.real-debrid.cloud", "64.download.real-debrid.com", "65.download.real-debrid.cloud", "65.download.real-debrid.com", "66.download.real-debrid.cloud", "66.download.real-debrid.com", "67.download.real-debrid.cloud", "67.download.real-debrid.com", "68.download.real-debrid.cloud", "68.download.real-debrid.com", "69.download.real-debrid.cloud", "69.download.real-debrid.com", "hkg1.download.real-debrid.com", "lax1.download.real-debrid.com", "lon1.download.real-debrid.com", "mum1.download.real-debrid.com", "rbx.download.real-debrid.com", "sgp1.download.real-debrid.com", "tlv1.download.real-debrid.com", "tyo1.download.real-debrid.com"}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
infoChan := make(chan IPInfo, len(ips))
|
||||
semaphore := make(chan struct{}, 10)
|
||||
|
||||
for _, ip := range ips {
|
||||
wg.Add(1)
|
||||
semaphore <- struct{}{}
|
||||
go func(ip string) {
|
||||
defer wg.Done()
|
||||
hops, latency, err := traceroute(ip)
|
||||
if err != nil {
|
||||
fmt.Println("Error performing traceroute:", err)
|
||||
} else {
|
||||
infoChan <- IPInfo{Address: ip, Hops: hops, Latency: latency}
|
||||
}
|
||||
<-semaphore
|
||||
}(ip)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(infoChan)
|
||||
|
||||
var ipInfos []IPInfo
|
||||
for info := range infoChan {
|
||||
ipInfos = append(ipInfos, info)
|
||||
}
|
||||
|
||||
sort.Slice(ipInfos, func(i, j int) bool {
|
||||
if ipInfos[i].Hops == ipInfos[j].Hops {
|
||||
return ipInfos[i].Latency < ipInfos[j].Latency
|
||||
}
|
||||
return ipInfos[i].Hops < ipInfos[j].Hops
|
||||
})
|
||||
var lowestLatency time.Duration
|
||||
if len(ipInfos) > 0 {
|
||||
lowestLatency = ipInfos[0].Latency
|
||||
for _, info := range ipInfos {
|
||||
if info.Latency < lowestLatency {
|
||||
lowestLatency = info.Latency
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
latencyThreshold := lowestLatency + lowestLatency/3
|
||||
|
||||
var okIPs []IPInfo
|
||||
for _, info := range ipInfos {
|
||||
if info.Latency <= latencyThreshold {
|
||||
okIPs = append(okIPs, info)
|
||||
}
|
||||
}
|
||||
for _, info := range okIPs {
|
||||
fmt.Printf("Host: %s, Hops: %d, Latency: %v\n", info.Address, info.Hops, info.Latency)
|
||||
}
|
||||
}
|
||||
@@ -20,31 +20,45 @@ type UnrestrictResponse struct {
|
||||
}
|
||||
|
||||
type Torrent struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"filename"`
|
||||
OriginalName string `json:"original_filename"`
|
||||
Hash string `json:"hash"`
|
||||
Progress int `json:"-"`
|
||||
Added string `json:"added"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
Links []string `json:"links"`
|
||||
Files []File `json:"files,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"filename"`
|
||||
Hash string `json:"hash"`
|
||||
Progress int `json:"-"`
|
||||
Added string `json:"added"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
Links []string `json:"links"`
|
||||
}
|
||||
|
||||
func (t *Torrent) UnmarshalJSON(data []byte) error {
|
||||
type Alias Torrent
|
||||
type TorrentInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"filename"`
|
||||
Hash string `json:"hash"`
|
||||
Progress int `json:"-"`
|
||||
Status string `json:"status"`
|
||||
Added string `json:"added"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
Links []string `json:"links"`
|
||||
OriginalName string `json:"original_filename"` // from info
|
||||
OriginalBytes int64 `json:"original_bytes"` // from info
|
||||
Files []File `json:"files"` // from info
|
||||
ForRepair bool `json:"-"`
|
||||
Version string `json:"-"`
|
||||
}
|
||||
|
||||
func (i *TorrentInfo) UnmarshalJSON(data []byte) error {
|
||||
type Alias TorrentInfo
|
||||
aux := &struct {
|
||||
Progress float64 `json:"progress"`
|
||||
*Alias
|
||||
}{
|
||||
Alias: (*Alias)(t),
|
||||
Alias: (*Alias)(i),
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, &aux); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
t.Progress = int(math.Round(aux.Progress))
|
||||
i.Progress = int(math.Round(aux.Progress))
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,19 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func RetryUntilOk[T any](fn func() (T, error)) T {
|
||||
func (rd *RealDebrid) UnrestrictUntilOk(link string) *UnrestrictResponse {
|
||||
if link == "" {
|
||||
return nil
|
||||
}
|
||||
unrestrictFn := func(link string) (*UnrestrictResponse, error) {
|
||||
return rd.UnrestrictLink(link)
|
||||
}
|
||||
return retryUntilOk(func() (*UnrestrictResponse, error) {
|
||||
return unrestrictFn(link)
|
||||
})
|
||||
}
|
||||
|
||||
func retryUntilOk[T any](fn func() (T, error)) T {
|
||||
const initialDelay = 1 * time.Second
|
||||
const maxDelay = 128 * time.Second
|
||||
for i := 0; ; i++ {
|
||||
Reference in New Issue
Block a user