Skip to content
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

Add StremThru as streaming provider #345

Merged
merged 2 commits into from
Nov 19, 2024

Conversation

MunifTanjim
Copy link
Contributor

@MunifTanjim MunifTanjim commented Nov 6, 2024

StremThru: https://github.com/MunifTanjim/stremthru

Example Config for StremThru:

STREMTHRU_PROXY_AUTH=user-one:password-one,user-two:password-two                                                                 
STREMTHRU_STORE_AUTH="*:realdebrid:rd-api-key-one,user-two:realdebrid:rd-api-key-two"

Run by following: https://github.com/MunifTanjim/stremthru?tab=readme-ov-file#usage

Summary by CodeRabbit

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new streaming provider option, "StremThru," allowing users to configure additional settings including a Service URL.
    • Added fields for user credentials (email, password) and options for enabling watchlist catalogs.
    • Enhanced validation for the Service URL input to ensure proper formatting.
  • UI/UX Improvements

    • Updated the configuration interface to include a new section for entering the Service URL, which is displayed based on user selection.
    • Adjusted CSS styles to accommodate new UI elements.
  • Bug Fixes

    • Improved handling of provider-specific errors and validation for user input related to the new streaming service.

Copy link
Contributor

coderabbitai bot commented Nov 6, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces updates across multiple files to support a new streaming provider, "StremThru." Key changes include the addition of a new service option and an associated URL field in the StreamingProvider class within db/schemas.py, modifications to the HTML configuration for user input, and enhancements to JavaScript logic for handling service URLs. New utility functions and a client class for the StremThru service are created, ensuring proper interaction with the streaming API. Additionally, CSS styles are adjusted to accommodate the new input fields.

Changes

File Change Summary
db/schemas.py Added field: url, added service literal "stremthru" in StreamingProvider.
resources/css/styles.css Updated selector for margin-top to include #service_url_section.
resources/html/configure.html Added option for "StremThru (Interface)" and a new section for "Service URL" input.
resources/js/config_script.js Introduced constant servicesRequiringUrl for handling visibility of service_url_section; modified validation logic for URL input.
streaming_providers/mapper.py Added mappings for "stremthru" in various function dictionaries for caching and fetching data.
streaming_providers/stremthru/client.py Introduced StremThru class with methods for API interaction and error handling.
streaming_providers/stremthru/utils.py Added utility functions for interacting with StremThru, including URL retrieval and torrent management.
utils/const.py Updated STREAMING_SERVICE_REQUIREMENTS to include "stremthru" with required parameters.

Possibly related PRs

Suggested labels

hacktoberfest-accepted

🐇 In the meadow, hops a little hare,
With fields of code, we craft with care.
StremThru's here, with URLs to share,
New options bloom, like springtime air.
So let us code, with joy and glee,
For every change, a new journey! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@MunifTanjim MunifTanjim force-pushed the feat-stremthru branch 2 times, most recently from 6b33eab to bf8fae3 Compare November 6, 2024 12:23
@mhdzumair
Copy link
Owner

Nice, lmk once you're done with the changes.

@MunifTanjim MunifTanjim force-pushed the feat-stremthru branch 2 times, most recently from bbf8876 to 649d6f2 Compare November 6, 2024 19:19
@mhdzumair
Copy link
Owner

is it ready for review? Please add validate credential function as well.

@MunifTanjim
Copy link
Contributor Author

Not ready yet. I'm on vacation, will be back on 16th Nov and finish it after that.

@mhdzumair
Copy link
Owner

No worries, take your time & enjoy the vacation

@MunifTanjim MunifTanjim marked this pull request as ready for review November 18, 2024 15:11
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🧹 Outside diff range and nitpick comments (11)
streaming_providers/mapper.py (1)

Line range hint 137-138: Add StremThru to credential validation mapping.

The VALIDATE_CREDENTIALS_FUNCTIONS dictionary needs to be updated to include the StremThru provider. This is critical for implementing the requested credential validation functionality.

Add the following entry to the dictionary:

 VALIDATE_CREDENTIALS_FUNCTIONS = {
     "alldebrid": validate_alldebrid_credentials,
     "debridlink": validate_debridlink_credentials,
     "offcloud": validate_offcloud_credentials,
     "pikpak": validate_pikpak_credentials,
     "premiumize": validate_premiumize_credentials,
     "qbittorrent": validate_qbittorrent_credentials,
     "realdebrid": validate_realdebrid_credentials,
     "seedr": validate_seedr_credentials,
     "torbox": validate_torbox_credentials,
+    "stremthru": validate_stremthru_credentials,
 }
utils/const.py (1)

132-132: Document the StremThru configuration requirements.

Consider adding a comment above the STREAMING_SERVICE_REQUIREMENTS dictionary to document:

  • The expected URL format for StremThru
  • Token acquisition process
  • Any specific requirements or limitations

Example documentation:

# StremThru configuration:
# - url: The StremThru service endpoint (e.g., https://api.stremthru.example.com)
# - token: API token obtained from StremThru dashboard
db/schemas.py (1)

Line range hint 142-149: Add field descriptions for better documentation.

The new fields lack descriptions which are important for API documentation and developer understanding.

Add descriptions to the fields:

-    url: str | None = Field(default=None, alias="u")
+    url: str | None = Field(
+        default=None,
+        alias="u",
+        description="Base URL for the StremThru service"
+    )
-    token: str | None = Field(default=None, alias="tk")
+    token: str | None = Field(
+        default=None,
+        alias="tk",
+        description="Authentication token for StremThru API access"
+    )
-    email: str | None = Field(default=None, alias="em")
+    email: str | None = Field(
+        default=None,
+        alias="em",
+        description="Email address for StremThru account"
+    )
-    password: str | None = Field(default=None, alias="pw")
+    password: str | None = Field(
+        default=None,
+        alias="pw",
+        description="Password for StremThru account"
+    )
-    enable_watchlist_catalogs: bool = Field(default=True, alias="ewc")
+    enable_watchlist_catalogs: bool = Field(
+        default=True,
+        alias="ewc",
+        description="Enable/disable watchlist catalogs feature"
+    )
-    qbittorrent_config: QBittorrentConfig | None = Field(default=None, alias="qbc")
+    qbittorrent_config: QBittorrentConfig | None = Field(
+        default=None,
+        alias="qbc",
+        description="Configuration for qBittorrent integration"
+    )
-    download_via_browser: bool = Field(default=False, alias="dvb")
+    download_via_browser: bool = Field(
+        default=False,
+        alias="dvb",
+        description="Enable downloading through browser instead of direct download"
+    )
-    only_show_cached_streams: bool = Field(default=False, alias="oscs")
+    only_show_cached_streams: bool = Field(
+        default=False,
+        alias="oscs",
+        description="Show only cached streams to improve performance"
+    )
resources/js/config_script.js (1)

172-180: Add null check for service URL input element.

While the logic is correct, it's recommended to add a null check for the service URL input element to prevent potential runtime errors if the element is not found in the DOM.

-    const serviceUrlInput = document.getElementById('service_url');
+    const serviceUrlInput = document.getElementById('service_url');
+    if (!serviceUrlInput) {
+        console.warn('Service URL input element not found');
+        return;
+    }
resources/html/configure.html (1)

69-78: Consider enhancing accessibility for the service URL section.

The service URL section is well-structured and follows Bootstrap conventions. However, consider adding aria-describedby to link the input field with its validation message for better screen reader support.

-        <input class="form-control" type="text" id="service_url" name="service_url" placeholder="https://" aria-label="Service URL"
+        <input class="form-control" type="text" id="service_url" name="service_url" placeholder="https://" aria-label="Service URL" aria-describedby="service_url_feedback"
               value="{{ user_data.streaming_provider.url if user_data.streaming_provider.url else '' }}">
-        <div class="invalid-feedback">
+        <div class="invalid-feedback" id="service_url_feedback">
             Service URL should be valid.
         </div>
streaming_providers/stremthru/client.py (2)

65-65: Simplify conditional check

The default return value of dict.get() is None, so specifying it explicitly is unnecessary.

Apply this diff to simplify the condition:

-        if response_data.get("error", None):
+        if response_data.get("error"):
🧰 Tools
🪛 Ruff

65-65: Use response_data.get("error") instead of response_data.get("error", None)

Replace response_data.get("error", None) with response_data.get("error")

(SIM910)


91-97: Handle potential KeyError when accessing 'items'

If available_torrents["data"] does not contain the key "items", a KeyError will be raised.

Consider safely accessing the "items" key:

-        for torrent in available_torrents["data"]["items"]:
+        items = available_torrents.get("data", {}).get("items", [])
+        for torrent in items:
             if torrent["hash"] == info_hash:
                 return torrent
streaming_providers/stremthru/utils.py (4)

17-22: Add missing type annotations for function parameters

For better code clarity and to utilize static analysis tools effectively, consider adding type annotations to the get_torrent_info function parameters and return type.

Apply this diff to add type annotations:

 async def get_torrent_info(st_client, info_hash):
+async def get_torrent_info(
+    st_client: StremThru, info_hash: str
+) -> Optional[dict]:
     torrent_info = await st_client.get_available_torrent(info_hash)
     if torrent_info and torrent_info["status"] == "downloaded":
         return torrent_info
     return None

24-27: Add missing type annotations for function parameters

Similarly, enhance the add_new_torrent function by adding type annotations to its parameters and return type.

Apply this diff:

 async def add_new_torrent(st_client, magnet_link):
+async def add_new_torrent(
+    st_client: StremThru, magnet_link: str
+) -> str:
     response_data = await st_client.add_magnet_link(magnet_link)
     return response_data["id"]

95-106: Document return behavior on exceptions in fetch_downloaded_info_hashes_from_st

When a ProviderException occurs, the function returns an empty list. It's important to document this behavior in the docstring to inform users of the potential return values.

Update the docstring to reflect the behavior:

     """Fetches the info_hashes of all torrents downloaded in the StremThru account.
 
+    Returns:
+        list[str]: A list of info_hashes. Returns an empty list if an exception occurs.
     """

117-132: Simplify the logic in validate_stremthru_credentials

Since get_user_info() will raise an exception on failure, the additional check for response may be unnecessary. Simplify the function by removing redundant conditions.

Apply this diff to streamline the function:

 async def validate_stremthru_credentials(user_data: UserData, user_ip: str) -> dict:
     """Validates the StremThru credentials."""
     try:
         async with _get_client(user_data) as client:
-            response = await client.get_user_info()
-            if response:
-                return {"status": "success"}
-            return {
-                "status": "error",
-                "message": "Invalid StremThru credentials.",
-            }
+            await client.get_user_info()
+            return {"status": "success"}
     except ProviderException as error:
         return {
             "status": "error",
             "message": f"Failed to verify StremThru credential, error: {error.message}",
         }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9b88c7f and 9215b73.

📒 Files selected for processing (8)
  • db/schemas.py (1 hunks)
  • resources/css/styles.css (1 hunks)
  • resources/html/configure.html (1 hunks)
  • resources/js/config_script.js (4 hunks)
  • streaming_providers/mapper.py (5 hunks)
  • streaming_providers/stremthru/client.py (1 hunks)
  • streaming_providers/stremthru/utils.py (1 hunks)
  • utils/const.py (1 hunks)
🧰 Additional context used
🪛 Ruff
streaming_providers/stremthru/client.py

65-65: Use response_data.get("error") instead of response_data.get("error", None)

Replace response_data.get("error", None) with response_data.get("error")

(SIM910)

🔇 Additional comments (9)
streaming_providers/mapper.py (2)

82-82: LGTM! Dictionary mappings are consistent.

The StremThru provider entries are correctly added to all function mapping dictionaries, following the same pattern as other providers.

Also applies to: 96-96, 110-110, 124-124


64-69: Verify the credential validation implementation.

Let's verify that the credential validation function is implemented in the StremThru utils module.

✅ Verification successful

Credential validation function is properly implemented

The validate_stremthru_credentials function is correctly implemented in streaming_providers/stremthru/utils.py at line 117. The function:

  • Takes required parameters: user_data and user_ip
  • Validates credentials by attempting to fetch user info
  • Returns appropriate success/error responses with status messages
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the credential validation function is implemented in the StremThru utils module.

# Search for the credential validation function implementation
rg -p "def validate_stremthru_credentials" "streaming_providers/stremthru"

# Check the utils module content
fd "utils.py" "streaming_providers/stremthru" --exec cat {}

Length of output: 4470

utils/const.py (1)

132-132: Verify security implications of configurable service URL.

While the implementation follows the existing pattern, allowing user-configurable service URLs requires careful consideration:

  1. Ensure the application validates the URL format and enforces HTTPS.
  2. Consider adding URL validation in the schema to prevent security risks like SSRF.
  3. Document the expected URL format and any restrictions.

Let's verify the URL validation implementation:

✅ Verification successful

URL validation is properly implemented - no security concerns

The codebase has robust URL validation mechanisms in place:

  • is_valid_url() function validates URL structure (scheme and netloc)
  • validate_live_stream_url() performs both structure and connectivity validation
  • URLs are validated through Pydantic schema validation in db/schemas.py
  • Service validation includes error handling for HTTP status codes and request errors

The implementation follows secure patterns:

  • URL validation is enforced before any request is made
  • Proper error handling and logging is in place
  • Schema validation ensures required fields are present
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for URL validation logic in schema and provider implementation
echo "Searching for URL validation..."
rg -l "url.*valid|valid.*url" --type py

# Search for HTTPS enforcement
echo "Checking HTTPS enforcement..."
rg -l "https.*only|enforce.*https" --type py

# Look for documentation
echo "Checking for documentation..."
fd -e md -e rst . -x grep -l "stremthru"

Length of output: 547


Script:

#!/bin/bash
# Check URL validation in schemas and validation helper
echo "=== URL Validation in Schemas ==="
rg -A 5 -B 5 "url.*valid|valid.*url" db/schemas.py utils/validation_helper.py

# Check if StremThru config is validated
echo -e "\n=== StremThru Config Validation ==="
rg -A 10 "stremthru" db/config.py db/schemas.py

# Look for URL pattern validation
echo -e "\n=== URL Pattern Validation ==="
rg "https?://" utils/validation_helper.py db/schemas.py

Length of output: 9512

db/schemas.py (2)

Line range hint 151-163: Verify StremThru requirements in const.py.

The validator uses STREAMING_SERVICE_REQUIREMENTS from const.py. Need to ensure StremThru's requirements are properly defined.

Let's check the const.py file:

#!/bin/bash
# Description: Check if StremThru requirements are defined in const.py
# Expected: Should find STREAMING_SERVICE_REQUIREMENTS dictionary with "stremthru" key

# Search for the requirements dictionary
rg -A 10 'STREAMING_SERVICE_REQUIREMENTS\s*=\s*{' const.py

# Search specifically for stremthru in const.py
rg '"stremthru"' const.py

140-140: LGTM! Verify consistent usage of service name.

The addition of "stremthru" follows the existing naming pattern and is properly integrated.

Let's verify consistent usage of the service name across the codebase:

✅ Verification successful

Service name "stremthru" is used consistently across the codebase

The verification shows consistent usage of "stremthru" (lowercase) in all configuration and implementation files:

  • Correctly used in db/schemas.py
  • Consistently used in service mappings in utils/const.py
  • Properly implemented in dedicated module streaming_providers/stremthru/
  • Correctly referenced in frontend files (resources/js/config_script.js and resources/html/configure.html)

The implementation follows the established naming pattern and maintains consistency throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of "stremthru" service name
# Expected: All occurrences should use lowercase "stremthru"

# Search for any variations of the service name
rg -i 'strem.?thru' --type-add 'config:*.{json,yaml,yml,toml}' --type-add 'template:*.{html,htm,template}' --type config --type python --type javascript --type template

Length of output: 368


Script:

#!/bin/bash
# Let's try a more comprehensive search for any variations of "stremthru"
rg -i "stremthru|strem.?thru" 

# Also search specifically in Python files for streaming provider related code
rg -t py "StreamingProvider|STREAMING" -A 5

Length of output: 5440

resources/css/styles.css (1)

375-377: LGTM! Consistent styling for the service URL section.

The addition of #service_url_section to the margin-top selector maintains consistent spacing with other form sections.

Let's verify that the HTML implementation uses the correct element ID:

✅ Verification successful

CSS styling matches HTML implementation perfectly

The #service_url_section selector is correctly implemented in the HTML, following the same pattern as other form sections (signup_section, oauth_section, and token_input). All sections are consistently structured as div elements with corresponding IDs and share similar display patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the service_url_section element ID exists in the HTML file
# and follows the same pattern as other sections

# Search for the service_url_section ID in HTML files
rg -l 'id="service_url_section"' '*.html'

# Also check for similar section IDs to verify consistency
rg -l 'id="(signup_section|oauth_section|token_input)"' '*.html'

Length of output: 204


Script:

#!/bin/bash
# Let's first find HTML files in the repository
fd -e html

# Then search for the service_url_section ID in all files (not just HTML)
# as the ID might be in a template file
rg -l 'id="service_url_section"'

# Also check for similar section IDs to verify consistency
rg -l 'id="(signup_section|oauth_section|token_input)"'

Length of output: 310


Script:

#!/bin/bash
# Let's check the context of these IDs in configure.html to ensure they're used consistently
rg -A 2 -B 2 'id="(service_url_section|signup_section|oauth_section|token_input)"' resources/html/configure.html

Length of output: 1735

resources/js/config_script.js (1)

5-5: LGTM! Constants declaration follows established patterns.

The new constant follows the same naming convention and structure as other configuration arrays in the codebase.

resources/html/configure.html (1)

66-66: LGTM! StremThru provider option is properly integrated.

The new streaming provider option is correctly implemented with proper value, display text, and selected state handling.

streaming_providers/stremthru/client.py (1)

24-24: Verify the use of 'Proxy-Authorization' header

Ensure that the Proxy-Authorization header is correct for authenticating with the StremThru API. If the API requires the standard Authorization header, this may cause authentication issues.

Would you like to confirm the required authentication headers with the API documentation?

Comment on lines 64 to 70
from streaming_providers.stremthru.utils import (
update_st_cache_status,
fetch_downloaded_info_hashes_from_st,
delete_all_torrents_from_st,
get_video_url_from_stremthru,
)
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add missing credential validation function import.

The import block is missing the credential validation function for StremThru, which was specifically requested in the PR discussion. All other providers include this function for credential validation.

Add the following import:

 from streaming_providers.stremthru.utils import (
     update_st_cache_status,
     fetch_downloaded_info_hashes_from_st,
     delete_all_torrents_from_st,
     get_video_url_from_stremthru,
+    validate_stremthru_credentials,
 )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
from streaming_providers.stremthru.utils import (
update_st_cache_status,
fetch_downloaded_info_hashes_from_st,
delete_all_torrents_from_st,
get_video_url_from_stremthru,
)
from streaming_providers.stremthru.utils import (
update_st_cache_status,
fetch_downloaded_info_hashes_from_st,
delete_all_torrents_from_st,
get_video_url_from_stremthru,
validate_stremthru_credentials,
)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Address this

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mhdzumair, to address this issue, please add the missing import for validate_stremthru_credentials:

from streaming_providers.stremthru.utils import (
    update_st_cache_status,
    fetch_downloaded_info_hashes_from_st,
    delete_all_torrents_from_st,
    get_video_url_from_stremthru,
    validate_stremthru_credentials,
)

Additionally, update the VALIDATE_CREDENTIALS_FUNCTIONS dictionary to include StremThru:

VALIDATE_CREDENTIALS_FUNCTIONS = {
    "alldebrid": validate_alldebrid_credentials,
    "debridlink": validate_debridlink_credentials,
    "offcloud": validate_offcloud_credentials,
    "pikpak": validate_pikpak_credentials,
    "premiumize": validate_premiumize_credentials,
    "qbittorrent": validate_qbittorrent_credentials,
    "realdebrid": validate_realdebrid_credentials,
    "seedr": validate_seedr_credentials,
    "torbox": validate_torbox_credentials,
    "stremthru": validate_stremthru_credentials,
}

This ensures that credential validation for StremThru is properly implemented, consistent with the other providers.

db/schemas.py Outdated Show resolved Hide resolved
db/schemas.py Show resolved Hide resolved
resources/js/config_script.js Outdated Show resolved Hide resolved
streaming_providers/stremthru/client.py Outdated Show resolved Hide resolved
streaming_providers/stremthru/client.py Outdated Show resolved Hide resolved
streaming_providers/stremthru/utils.py Show resolved Hide resolved
streaming_providers/stremthru/utils.py Outdated Show resolved Hide resolved
streaming_providers/stremthru/utils.py Outdated Show resolved Hide resolved
streaming_providers/stremthru/utils.py Outdated Show resolved Hide resolved
@mhdzumair
Copy link
Owner

Address the above suggestion which contain 👍

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (7)
streaming_providers/mapper.py (1)

111-111: Consider renaming the dictionary for consistency.

While the mapping itself is correct, there's a naming inconsistency:

  • The dictionary is named DELETE_ALL_WATCHLIST_FUNCTIONS
  • Most functions, including delete_all_torrents_from_st, use "torrents" in their names
  • Only RealDebrid uses "watchlist" terminology

Consider renaming the dictionary to DELETE_ALL_TORRENTS_FUNCTIONS to better reflect its purpose and maintain consistency with the majority of the function names.

resources/html/configure.html (1)

69-78: Enhance the service URL input field.

While the implementation is functionally correct, consider these improvements for better user experience:

 <div id="service_url_section" style="display:none" class="mb-4">
     <label for="service_url">Service URL:</label>
     <input class="form-control" type="text" id="service_url" name="service_url" 
-           placeholder="https://" 
+           placeholder="https://stremthru.example.com"
+           pattern="https?:\/\/.+"
            aria-label="Service URL"
            value="{{ user_data.streaming_provider.url if user_data.streaming_provider.url else '' }}">
     <div class="invalid-feedback">
-        Service URL should be valid.
+        Please enter a valid URL starting with http:// or https://
     </div>
+    <small class="form-text text-muted">
+        Enter the StremThru service URL. Example: https://stremthru.example.com
+    </small>
 </div>
streaming_providers/stremthru/client.py (4)

7-13: Consider removing the unused StremThruError class

The StremThruError exception class is defined but not used anywhere in the code. Removing unused classes can help keep the codebase clean and maintainable.


28-30: Remove the unnecessary __del__ method

The __del__ method is empty and doesn't perform any cleanup operations. If there's no specific destructor logic needed, it's better to remove it to simplify the class.

Apply this diff to remove the method:

-    def __del__(self):
-        pass

57-57: Simplify the dict.get() usage

The default value None in res.get("error", None) is redundant since None is the default return value when the key is missing.

Apply this diff to simplify the code:

-        if res.get("error", None):
+        if res.get("error"):

66-66: Simplify the dict.get() usage

Similar to a previous case, the default None can be omitted in response_data.get("error", None).

Apply this diff to simplify the code:

-        if response_data.get("error", None):
+        if response_data.get("error"):
🧰 Tools
🪛 Ruff

66-66: Use response_data.get("error") instead of response_data.get("error", None)

Replace response_data.get("error", None) with response_data.get("error")

(SIM910)

streaming_providers/stremthru/utils.py (1)

29-44: Add type annotations for consistency

To enhance code readability and maintain consistency across the codebase, consider adding type annotations to the wait_for_download_and_get_link function parameters.

Apply this diff to add type annotations:

 async def wait_for_download_and_get_link(
-    st_client, torrent_id, filename, file_index, episode, max_retries, retry_interval
+    st_client: StremThru,
+    torrent_id: str,
+    filename: str,
+    file_index: int,
+    episode: int,
+    max_retries: int,
+    retry_interval: int,
 ):

Remember to import any necessary types, such as StremThru, at the beginning of your module.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9215b73 and b17859b.

📒 Files selected for processing (8)
  • db/schemas.py (1 hunks)
  • resources/css/styles.css (1 hunks)
  • resources/html/configure.html (1 hunks)
  • resources/js/config_script.js (4 hunks)
  • streaming_providers/mapper.py (6 hunks)
  • streaming_providers/stremthru/client.py (1 hunks)
  • streaming_providers/stremthru/utils.py (1 hunks)
  • utils/const.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • db/schemas.py
  • resources/css/styles.css
  • resources/js/config_script.js
  • utils/const.py
🧰 Additional context used
🪛 Ruff
streaming_providers/stremthru/client.py

66-66: Use response_data.get("error") instead of response_data.get("error", None)

Replace response_data.get("error", None) with response_data.get("error")

(SIM910)

🔇 Additional comments (8)
streaming_providers/mapper.py (6)

64-70: LGTM! Import block is complete and well-structured.

The import block follows the established pattern and includes all necessary functions, including the credential validation function that was previously requested.


83-83: LGTM! Cache update function mapping is correct.

The mapping follows the established pattern and uses consistent naming conventions.


97-97: LGTM! Info hashes fetch function mapping is correct.

The mapping follows the established pattern and maintains consistency with other providers.


125-125: LGTM! Video URL function mapping is correct.

The mapping follows the established pattern and maintains consistency with other providers.


139-139: LGTM! Credential validation function is properly implemented.

The mapping addresses the previous request for credential validation and follows the established pattern consistently.


Line range hint 64-139: Verify StremThru utility functions implementation.

Let's verify that all the mapped functions are properly implemented in the StremThru utils module.

✅ Verification successful

Let me verify the function implementations further by checking their actual implementation details.


All StremThru utility functions are properly implemented

All the required functions are implemented with appropriate:

  • Async/await patterns
  • Type hints
  • Error handling
  • Client session management using _get_client context manager
  • Consistent return types matching other providers' implementations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify StremThru utility functions implementation

# Check if all required functions are implemented
echo "Checking StremThru utility functions implementation..."
ast-grep --pattern 'def update_st_cache_status' streaming_providers/stremthru/utils.py
ast-grep --pattern 'def fetch_downloaded_info_hashes_from_st' streaming_providers/stremthru/utils.py
ast-grep --pattern 'def delete_all_torrents_from_st' streaming_providers/stremthru/utils.py
ast-grep --pattern 'def get_video_url_from_stremthru' streaming_providers/stremthru/utils.py
ast-grep --pattern 'def validate_stremthru_credentials' streaming_providers/stremthru/utils.py

# Check function signatures and return types
echo "Checking function signatures and return types..."
rg -A 1 'def (update_st_cache_status|fetch_downloaded_info_hashes_from_st|delete_all_torrents_from_st|get_video_url_from_stremthru|validate_stremthru_credentials)' streaming_providers/stremthru/utils.py

Length of output: 1464


Script:

#!/bin/bash
# Description: Check implementation details of StremThru utility functions

echo "Checking function implementations..."
rg -A 15 'async def (update_st_cache_status|fetch_downloaded_info_hashes_from_st|delete_all_torrents_from_st|get_video_url_from_stremthru|validate_stremthru_credentials)' streaming_providers/stremthru/utils.py

Length of output: 2870

resources/html/configure.html (1)

66-66: LGTM: StremThru provider option added correctly.

The new streaming provider option is properly integrated with the existing dropdown, including correct template syntax for selection state.

streaming_providers/stremthru/utils.py (1)

46-70: Well-structured implementation of get_video_url_from_stremthru

The function is well-organized, and the use of asynchronous context managers improves resource management.

streaming_providers/stremthru/client.py Show resolved Hide resolved
streaming_providers/stremthru/client.py Show resolved Hide resolved
streaming_providers/stremthru/client.py Outdated Show resolved Hide resolved
streaming_providers/stremthru/client.py Show resolved Hide resolved
streaming_providers/stremthru/utils.py Show resolved Hide resolved
streaming_providers/stremthru/utils.py Show resolved Hide resolved
@mhdzumair mhdzumair merged commit 73c9bf2 into mhdzumair:main Nov 19, 2024
1 check was pending
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants