-
-
Notifications
You must be signed in to change notification settings - Fork 127
feat: add Real-Debrid API client for premium download speeds #325
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mvanhorn
wants to merge
6
commits into
SurgeDM:main
Choose a base branch
from
mvanhorn:feat/debrid-integration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9f71ea7
feat: add Real-Debrid API client for premium download speeds
mvanhorn cf6ad5c
fix(debrid): cache supported hosts to avoid HTTP call on every IsSupp…
mvanhorn 6f1fa3a
fix(debrid): add RWMutex to prevent data race on cached hosts
mvanhorn 09830d4
style: remove redundant inline comments in realdebrid.go
mvanhorn 2cb1c98
fix: wire up Debrid settings tab in TUI
mvanhorn 491e35e
fix: reduce host cache TTL to 5min and use consistent time reference
mvanhorn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| package debrid | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
| ) | ||
|
|
||
| // Client is a Real-Debrid API client. | ||
| type Client struct { | ||
| apiKey string | ||
| httpClient *http.Client | ||
| baseURL string | ||
| mu sync.RWMutex | ||
| cachedHosts []string | ||
| hostsCached time.Time | ||
| } | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
|
|
||
| // NewClient creates a new Real-Debrid client with the given API key. | ||
| func NewClient(apiKey string) *Client { | ||
| return &Client{ | ||
| apiKey: apiKey, | ||
| httpClient: &http.Client{ | ||
| Timeout: 30 * time.Second, | ||
| }, | ||
| baseURL: "https://api.real-debrid.com/rest/1.0", | ||
| } | ||
| } | ||
|
|
||
| // UnrestrictResult holds the response from unrestricting a link. | ||
| type UnrestrictResult struct { | ||
| ID string `json:"id"` | ||
| Filename string `json:"filename"` | ||
| FileSize int64 `json:"filesize"` | ||
| Link string `json:"link"` | ||
| Download string `json:"download"` | ||
| Host string `json:"host"` | ||
| MimeType string `json:"mimeType"` | ||
| } | ||
|
|
||
| // apiError represents an error response from Real-Debrid. | ||
| type apiError struct { | ||
| ErrorCode int `json:"error_code"` | ||
| Error string `json:"error"` | ||
| } | ||
|
|
||
| // Unrestrict takes a hosted file URL and returns a direct download URL. | ||
| func (c *Client) Unrestrict(link string) (*UnrestrictResult, error) { | ||
| if c.apiKey == "" { | ||
| return nil, fmt.Errorf("debrid: API key is required") | ||
| } | ||
|
|
||
| data := url.Values{} | ||
| data.Set("link", link) | ||
|
|
||
| req, err := http.NewRequest(http.MethodPost, c.baseURL+"/unrestrict/link", strings.NewReader(data.Encode())) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("debrid: failed to create request: %w", err) | ||
| } | ||
| req.Header.Set("Authorization", "Bearer "+c.apiKey) | ||
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") | ||
|
|
||
| resp, err := c.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("debrid: request failed: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("debrid: failed to read response: %w", err) | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| var apiErr apiError | ||
| if json.Unmarshal(body, &apiErr) == nil && apiErr.Error != "" { | ||
| return nil, fmt.Errorf("debrid: API error %d: %s", apiErr.ErrorCode, apiErr.Error) | ||
| } | ||
| return nil, fmt.Errorf("debrid: unexpected status %d", resp.StatusCode) | ||
| } | ||
|
|
||
| var result UnrestrictResult | ||
| if err := json.Unmarshal(body, &result); err != nil { | ||
| return nil, fmt.Errorf("debrid: failed to parse response: %w", err) | ||
| } | ||
|
|
||
| if result.Download == "" { | ||
| return nil, fmt.Errorf("debrid: no download URL in response") | ||
| } | ||
|
|
||
| return &result, nil | ||
| } | ||
|
|
||
| // SupportedHosts returns the list of supported file hosting domains. | ||
| func (c *Client) SupportedHosts() ([]string, error) { | ||
| req, err := http.NewRequest(http.MethodGet, c.baseURL+"/hosts/domains", nil) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("debrid: failed to create request: %w", err) | ||
| } | ||
|
|
||
| resp, err := c.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("debrid: request failed: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("debrid: unexpected status %d", resp.StatusCode) | ||
| } | ||
|
|
||
| var domains []string | ||
| if err := json.NewDecoder(resp.Body).Decode(&domains); err != nil { | ||
| return nil, fmt.Errorf("debrid: failed to parse hosts response: %w", err) | ||
| } | ||
|
|
||
| return domains, nil | ||
| } | ||
|
|
||
| // supportedHostsCached returns the supported hosts list, caching briefly to | ||
| // avoid making a live HTTP call on every invocation. | ||
| func (c *Client) supportedHostsCached() ([]string, error) { | ||
| now := time.Now() | ||
|
|
||
| c.mu.RLock() | ||
| if c.cachedHosts != nil && now.Sub(c.hostsCached) < 5*time.Minute { | ||
| hosts := c.cachedHosts | ||
| c.mu.RUnlock() | ||
| return hosts, nil | ||
| } | ||
| c.mu.RUnlock() | ||
|
|
||
| c.mu.Lock() | ||
| defer c.mu.Unlock() | ||
| // Double-check after acquiring write lock. | ||
| now = time.Now() | ||
| if c.cachedHosts != nil && now.Sub(c.hostsCached) < 5*time.Minute { | ||
| return c.cachedHosts, nil | ||
| } | ||
| hosts, err := c.SupportedHosts() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| c.cachedHosts = hosts | ||
| c.hostsCached = now | ||
| return hosts, nil | ||
| } | ||
|
|
||
| // IsSupported checks if a URL's host is supported by Real-Debrid. | ||
| func (c *Client) IsSupported(rawURL string) bool { | ||
| parsed, err := url.Parse(rawURL) | ||
| if err != nil { | ||
| return false | ||
| } | ||
| host := strings.ToLower(parsed.Hostname()) | ||
|
|
||
| hosts, err := c.supportedHostsCached() | ||
| if err != nil { | ||
| return false | ||
| } | ||
|
|
||
| for _, h := range hosts { | ||
| h = strings.ToLower(h) | ||
| if h == host || strings.HasSuffix(host, "."+h) { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| package debrid | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestUnrestrict_Success(t *testing.T) { | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| assert.Equal(t, http.MethodPost, r.Method) | ||
| assert.Equal(t, "/unrestrict/link", r.URL.Path) | ||
| assert.Contains(t, r.Header.Get("Authorization"), "Bearer") | ||
|
|
||
| _ = json.NewEncoder(w).Encode(UnrestrictResult{ | ||
| ID: "test123", | ||
| Filename: "file.zip", | ||
| FileSize: 1024, | ||
| Download: "https://direct.example.com/file.zip", | ||
| Host: "mega.nz", | ||
| }) | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| client := NewClient("test-api-key") | ||
| client.baseURL = server.URL | ||
|
|
||
| result, err := client.Unrestrict("https://mega.nz/file/abc") | ||
| require.NoError(t, err) | ||
| assert.Equal(t, "file.zip", result.Filename) | ||
| assert.Equal(t, "https://direct.example.com/file.zip", result.Download) | ||
| } | ||
|
|
||
| func TestUnrestrict_NoAPIKey(t *testing.T) { | ||
| client := NewClient("") | ||
| _, err := client.Unrestrict("https://mega.nz/file/abc") | ||
| assert.Error(t, err) | ||
| assert.Contains(t, err.Error(), "API key is required") | ||
| } | ||
|
|
||
| func TestUnrestrict_APIError(t *testing.T) { | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusForbidden) | ||
| _ = json.NewEncoder(w).Encode(apiError{ | ||
| ErrorCode: 8, | ||
| Error: "Bad token", | ||
| }) | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| client := NewClient("bad-key") | ||
| client.baseURL = server.URL | ||
|
|
||
| _, err := client.Unrestrict("https://mega.nz/file/abc") | ||
| assert.Error(t, err) | ||
| assert.Contains(t, err.Error(), "Bad token") | ||
| } | ||
|
|
||
| func TestSupportedHosts(t *testing.T) { | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| assert.Equal(t, "/hosts/domains", r.URL.Path) | ||
| _ = json.NewEncoder(w).Encode([]string{"mega.nz", "rapidgator.net", "uploaded.net"}) | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| client := NewClient("test-key") | ||
| client.baseURL = server.URL | ||
|
|
||
| hosts, err := client.SupportedHosts() | ||
| require.NoError(t, err) | ||
| assert.Contains(t, hosts, "mega.nz") | ||
| } | ||
|
|
||
| func TestIsSupported(t *testing.T) { | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| _ = json.NewEncoder(w).Encode([]string{"mega.nz", "rapidgator.net"}) | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| client := NewClient("test-key") | ||
| client.baseURL = server.URL | ||
|
|
||
| assert.True(t, client.IsSupported("https://mega.nz/file/abc")) | ||
| assert.True(t, client.IsSupported("https://www.mega.nz/file/abc")) | ||
| assert.False(t, client.IsSupported("https://example.com/file")) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CategoryOrder()now includes"Debrid", so the tab appears in the settings UI. However,view_settings.gowas not updated:getSettingValueshas nocase "Debrid"(all three fields will display as blank), andsetSettingValuealso has nocase "Debrid"(edits will be silently discarded). The PR description explicitly promises a working TUI settings tab, but the wiring is missing.view_settings.goneeds two additions:…plus a corresponding
setDebridSettingmethod.Prompt To Fix With AI