repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,99 +1,91 @@ from abc import ABC, abstractmethod from datetime import datetime -from typing import Tuple - -from loguru import logger -from RTN import parse - -from program.media import MovieMediaType, ShowMediaType -from program.settings.manager import settings_manager - -DEFAULT_VIDEO_EXTENSIONS = ["mp4", "mkv...
_:warning: Potential issue_ **Resolve return type mismatch in `add_torrent` method** The method signature indicates a return type of `int`, but the docstring specifies `str`. This inconsistency may cause confusion about the expected return type. Please update either the method's return type or the docstring to ens...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,99 +1,91 @@ from abc import ABC, abstractmethod from datetime import datetime -from typing import Tuple - -from loguru import logger -from RTN import parse - -from program.media import MovieMediaType, ShowMediaType -from program.settings.manager import settings_manager - -DEFAULT_VIDEO_EXTENSIONS = ["mp4", "mkv...
_:warning: Potential issue_ **Fix return type inconsistency in `validate` method** The `validate` method's return type in the signature is `bool`, but the docstring indicates it returns a `ValidationResult`. Additionally, `ValidationResult` is not imported or defined in this context. To resolve this inconsistency,...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,113 @@ +from datetime import datetime +from typing import Dict, List, Literal, Optional, Union +from loguru import logger +from pydantic import BaseModel, Field +from program.settings.manager import settings_manager + + +DEFAULT_VIDEO_EXTENSIONS = ["mp4", "mkv", "avi"] +ALLOWED_VIDEO_EXTENSIONS = [ + "mp4...
_:warning: Potential issue_ **Correct the logical condition to properly filter filenames** The condition in the `if` statement may not correctly filter out unwanted files. Currently, the condition returns `None` only if the filename does **not** end with any allowed extensions **and** `'sample'` is **not** in the fil...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,41 +1,32 @@ +from typing import List, Optional, Union from loguru import logger -from program.media.item import MediaItem, MovieMediaType, ShowMediaType +from program.media.item import MediaItem, Show, Season, Episode, Movie from program.media.state import States from program.media.stream import Stream from...
_:warning: Potential issue_ **Potential Issue: Unpredictable downloader service selection due to unordered dictionary** The selection of the downloader service using an unordered dictionary could lead to inconsistent behavior since the order of services is not guaranteed in all Python versions. Consider using an `...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -47,100 +38,131 @@ def validate(self): return True def run(self, item: MediaItem): - logger.debug(f"Running downloader for {item.log_string}") + logger.debug(f"Starting download process for {item.log_string} ({item.id})") + + if item.active_stream: + logger.debug(f"Ski...
_:warning: Potential issue_ **Inconsistent return type handling in `get_instant_availability`** The `validate_stream` method treats the result of `get_instant_availability` as a single `TorrentContainer`, but the method is declared to return a `List[TorrentContainer]`. To resolve this inconsistency, update the ret...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,334 +1,191 @@ -# import contextlib -# from datetime import datetime -# from pathlib import Path -# from posixpath import splitext -# from typing import Generator - -# from requests import ConnectTimeout -# from RTN import parse -# from RTN.exceptions import GarbageTorrent - -# from program.db.db import db -# from...
_:hammer_and_wrench: Refactor suggestion_ **Use specific exception handling for better error clarity** Catching all exceptions with `except Exception as e` can make debugging harder and may suppress important error information. Consider catching specific exceptions that are likely to occur in this context. Update t...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,334 +1,191 @@ -# import contextlib -# from datetime import datetime -# from pathlib import Path -# from posixpath import splitext -# from typing import Generator - -# from requests import ConnectTimeout -# from RTN import parse -# from RTN.exceptions import GarbageTorrent - -# from program.db.db import db -# from...
_:hammer_and_wrench: Refactor suggestion_ **Add checks for missing or unexpected response data** In the `get_instant_availability` method, accessing `response["data"]` without verifying its existence may lead to `KeyError` if the key is missing. Similarly, ensure that `torrent["files"]` exists before iterating over i...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -236,11 +209,25 @@ def delete_torrent(self, torrent_id: str): Delete a torrent Required by DownloaderBase """ - if not self.initialized: - raise AllDebridError("Downloader not properly initialized") - try: - self.api.request_handler.execute(HttpMethod....
_:warning: Potential issue_ **Ensure correct return type in `get_files_and_links`** The method `get_files_and_links` is annotated to return `List[DebridFile]`, but it returns `magnet_info.get("files", {})`, which may not match the expected type. Modify the method to return a list of `DebridFile` instances: ```dif...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -222,11 +188,18 @@ def get_torrent_info(self, torrent_id: str) -> dict: raise AllDebridError("Downloader not properly initialized") try: - response = self.api.request_handler.execute(HttpMethod.GET, "magnet/status", id=torrent_id) + response = self.api.request_handler.ex...
_:warning: Potential issue_ **Fix incorrect progress calculation in `get_torrent_info`** The progress is calculated as `info["size"] / info["downloaded"]`, which is incorrect. It should be `info["downloaded"] / info["size"]` to represent the fraction of data downloaded. Apply this diff to correct the calculation: ...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -116,60 +116,29 @@ def _validate_premium(self) -> bool: logger.error(f"Failed to validate premium status: {e}") return False - def get_instant_availability(self, infohashes: List[str]) -> Dict[str, list]: + def get_instant_availability(self, infohash: str, item_type: str) -> Optional[To...
_:warning: Potential issue_ **Avoid returning inside a `finally` block to prevent exception suppression** Returning inside a `finally` block suppresses any exceptions raised in the `try` or `except` blocks, hindering proper error handling and debugging. Move the `return` statement outside the `finally` block: ```...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -130,73 +128,67 @@ def _validate_premium(self) -> bool: logger.error(f"Failed to validate premium status: {e}") return False - def get_instant_availability(self, infohashes: List[str]) -> Dict[str, list]: + def get_instant_availability(self, infohash: str, item_type: str) -> Optiona...
_:hammer_and_wrench: Refactor suggestion_ **Add unit tests for new and modified methods** The methods `get_instant_availability` and `_process_torrent` include significant new logic. To ensure their correctness and prevent future regressions, please add unit tests covering various scenarios, including successful exec...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -130,73 +128,67 @@ def _validate_premium(self) -> bool: logger.error(f"Failed to validate premium status: {e}") return False - def get_instant_availability(self, infohashes: List[str]) -> Dict[str, list]: + def get_instant_availability(self, infohash: str, item_type: str) -> Optiona...
_:hammer_and_wrench: Refactor suggestion_ **Update the docstring to match the new method signature** The `get_instant_availability` method now accepts a single `infohash` and `item_type`, but the docstring still refers to 'multiple infohashes'. Please update the docstring to accurately describe the method's functiona...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -209,49 +201,44 @@ def add_torrent(self, infohash: str) -> str: logger.error(f"Failed to add torrent {infohash}: {e}") raise - def select_files(self, torrent_id: str, files: List[str]): - """ - Select files from a torrent - Required by DownloaderBase - """ -...
_:warning: Potential issue_ **Handle missing keys in the API response to prevent `KeyError`** When processing the response data in `get_torrent_info`, you're accessing keys like `"files"`, `"id"`, `"path"`, and `"bytes"` directly. If any of these keys are missing in the API response, it could result in a `KeyError`. ...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,5 +1,7 @@ import os +import sys
_:hammer_and_wrench: Refactor suggestion_ **Remove unused import `sys`** The `sys` module imported on line 2 is not used in the current codebase. Since it's only referenced in the commented-out code, please remove this unused import to clean up the code. Apply this diff to remove the unused import: ```diff -impor...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,5 +1,7 @@ import os +import sys import threading +import time
_:hammer_and_wrench: Refactor suggestion_ **Remove unused import `time`** The `time` module imported on line 4 is not used in the current codebase. It was only used in the commented-out code. Please remove this unused import. Apply this diff to remove the unused import: ```diff -import time ``` <!-- suggestion_...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -186,6 +187,95 @@ def submit_job(self, service, program, event=None): sse_manager.publish_event("event_update", self.get_event_updates()) future.add_done_callback(lambda f:self._process_future(f, service)) + # For debugging purposes we can monitor the execution time of the service. (comment ou...
_:hammer_and_wrench: Refactor suggestion_ **Remove large block of commented-out code** Lines 190-278 contain a large block of code that is entirely commented out. Keeping such large blocks of commented-out code can clutter the codebase and reduce readability. If this code is no longer needed, please remove it. If it'...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,114 @@ +from datetime import datetime +from typing import Dict, List, Literal, Optional, Union + +from loguru import logger +from pydantic import BaseModel, Field + +from program.settings.manager import settings_manager + +DEFAULT_VIDEO_EXTENSIONS = ["mp4", "mkv", "avi"] +ALLOWED_VIDEO_EXTENSIONS = [ + "m...
_:warning: Potential issue_ **Fix the logical condition and membership test** The condition has incorrect logic and syntax. It should reject files that either don't have allowed extensions or contain 'sample'. ```diff -if not any(filename.endswith(ext) for ext in VIDEO_EXTENSIONS) and not "sample" in filename.lower(...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,41 +1,38 @@ +from typing import List, Optional, Union + from loguru import logger -from program.media.item import MediaItem, MovieMediaType, ShowMediaType +from program.media.item import Episode, MediaItem, Movie, Season, Show from program.media.state import States from program.media.stream import Stream +fr...
_:hammer_and_wrench: Refactor suggestion_ **Consider using a more robust service selection strategy** The current service selection using `next()` on an unordered dictionary could lead to unpredictable behavior. Additionally, the initialization doesn't provide visibility into which service was selected. Consider th...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -47,100 +44,131 @@ def validate(self): return True def run(self, item: MediaItem): - logger.debug(f"Running downloader for {item.log_string}") + logger.debug(f"Starting download process for {item.log_string} ({item.id})") + + if item.active_stream: + logger.debug(f"Ski...
_:hammer_and_wrench: Refactor suggestion_ **Add error handling for service method calls** The service method calls could fail if the service is not properly initialized or encounters network issues. Consider adding error handling: ```diff def download_cached_stream(self, stream: Stream, container: TorrentCont...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,334 +1,195 @@ -# import contextlib -# from datetime import datetime -# from pathlib import Path -# from posixpath import splitext -# from typing import Generator - -# from requests import ConnectTimeout -# from RTN import parse -# from RTN.exceptions import GarbageTorrent - -# from program.db.db import db -# from...
_:hammer_and_wrench: Refactor suggestion_ **Use specific exception handling** The broad exception catch could mask important errors. Consider catching specific exceptions for better error handling. ```diff - except Exception as e: + except TorBoxError as e: + logger.debug(f"TorBo...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -209,49 +205,44 @@ def add_torrent(self, infohash: str) -> str: logger.error(f"Failed to add torrent {infohash}: {e}") raise - def select_files(self, torrent_id: str, files: List[str]): - """ - Select files from a torrent - Required by DownloaderBase - """ -...
_:hammer_and_wrench: Refactor suggestion_ **Optimize sleep delay and add input validation** The fixed sleep delay could be replaced with a more dynamic approach, and the method should validate input parameters. ```diff - def select_files(self, torrent_id: str, ids: List[int] = None) -> None: + def select_files...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -130,73 +132,67 @@ def _validate_premium(self) -> bool: logger.error(f"Failed to validate premium status: {e}") return False - def get_instant_availability(self, infohashes: List[str]) -> Dict[str, list]: + def get_instant_availability(self, infohash: str, item_type: str) -> Optiona...
_:hammer_and_wrench: Refactor suggestion_ **Improve method structure and status validation** The method could benefit from: 1. Breaking down the video file filtering logic into a separate method 2. Using an enum for status comparison instead of string literals 3. Adding a timeout for the status check ```diff + de...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,10 +1,17 @@ +import time from datetime import datetime from typing import Dict, Iterator, List, Optional, Tuple from loguru import logger from requests import Session from requests.exceptions import ConnectTimeout +from program.services.downloaders.models import ( + VIDEO_EXTENSIONS,
_:hammer_and_wrench: Refactor suggestion_ **Remove unused import `VIDEO_EXTENSIONS`** The `VIDEO_EXTENSIONS` import from `program.services.downloaders.models` is not used in this file. Removing it maintains a clean and maintainable codebase. Apply this diff to remove the unused import: ```diff from program.servi...
riven
github_2023
python
903
rivenmedia
coderabbitai[bot]
@@ -1,10 +1,17 @@ +import time from datetime import datetime from typing import Dict, Iterator, List, Optional, Tuple
_:hammer_and_wrench: Refactor suggestion_ **Remove unused imports from `typing` module** The imports `Dict`, `Iterator`, and `Tuple` from the `typing` module are not used in this file. Removing unused imports helps keep the code clean and reduces clutter. Apply this diff to remove the unused imports: ```diff -fro...
riven
github_2023
python
901
rivenmedia
coderabbitai[bot]
@@ -45,7 +45,8 @@ def validate(self) -> bool: return False try: url = f"{self.settings.url}/{self.settings.filter}/manifest.json" - response = self.request_handler.execute(HttpMethod.GET, url, timeout=10) + headers = {"User-Agent": "Mozilla/5.0"} + res...
_:warning: Potential issue_ **Add headers consistently across all HTTP requests** The User-Agent header is only added to the validate() method but not to the scrape() method. This inconsistency could lead to different behavior between validation and actual scraping. Consider moving the headers to a class-level const...
riven
github_2023
python
888
rivenmedia
coderabbitai[bot]
@@ -351,11 +351,11 @@ async def remove_item(request: Request, ids: str) -> RemoveResponse: if symlink_service: symlink_service.delete_item_symlinks_by_id(item.id) - with db.Session() as session: - requested_id = session.execute(select(MediaItem.requested_id).whe...
_:hammer_and_wrench: Refactor suggestion_ **Enhance error handling for Overseerr request deletion** While the Overseerr integration looks good, the error handling could be improved to handle potential failures when deleting requests. Consider wrapping the Overseerr request deletion in a try-catch block: ```diff ...
riven
github_2023
python
884
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,47 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_i...
_:warning: Potential issue_ **Apply same robustness improvements as other endpoints** The status endpoint needs similar improvements for error handling and race condition prevention. ```diff @router.get("/status", operation_id="queue_status") async def queue_status(request: Request) -> QueueStatusResponse: + if...
riven
github_2023
python
884
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,47 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_i...
_:warning: Potential issue_ **Add error handling and use proper model instantiation** Several improvements are needed for robustness: 1. Add error handling for invalid item_ids 2. Validate that event manager exists 3. Use model constructor for type safety 4. Handle potential race conditions ```diff @router.post("/p...
riven
github_2023
python
884
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,47 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_i...
_:warning: Potential issue_ **Apply same robustness improvements as pause endpoint** The resume endpoint needs similar improvements for error handling and race condition prevention. ```diff @router.post("/resume", operation_id="resume_queue") async def resume_queue(request: Request, item_id: Optional[str] = None) ...
riven
github_2023
python
884
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,446 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_...
_:warning: Potential issue_ **Fix SyntaxError caused by misplaced `import os` statement** There's a SyntaxError at line 47 due to the `import os` statement being incorrectly placed immediately after the closing brace of the return statement without a newline or semicolon. Apply this diff to correct the error: ```...
riven
github_2023
python
883
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,446 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel
_:hammer_and_wrench: Refactor suggestion_ **Remove duplicate import of `BaseModel` from `pydantic`.** The import statement `from pydantic import BaseModel` is present twice, at lines 3 and 57. Removing the redundant import will clean up the code. Apply this diff to remove the duplicate import: ```diff - from pyda...
riven
github_2023
python
883
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,446 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_...
_:hammer_and_wrench: Refactor suggestion_ **Update docstring in `remove_id_from_running` for correct parameter.** The docstring references `item (MediaItem)`, but the function parameter is `item_id: str`. Adjust the `Args` section to match the function signature. Apply this diff: ```diff Args: - item ...
riven
github_2023
python
883
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,446 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_...
_:hammer_and_wrench: Refactor suggestion_ **Fix the parameter type in docstring of `cancel_job`.** The docstring specifies `item_id (int)`, whereas the function signature has `item_id: str`. Update the docstring to ensure consistency. Apply this diff: ```diff Args: - item_id (int): The event item whos...
riven
github_2023
python
883
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,446 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_...
_:hammer_and_wrench: Refactor suggestion_ **Correct the parameter name and type in the docstring of `remove_id_from_queue`.** The docstring's `Args` section incorrectly mentions `item (MediaItem)` instead of `item_id (str)`, which doesn't match the function signature. Update the docstring to reflect the correct param...
riven
github_2023
python
883
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,446 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_...
_:hammer_and_wrench: Refactor suggestion_ **Modify the return type annotation in `get_paused_items` to use `List[str]`.** Change the return type from `list[str]` to `List[str]` for compatibility with Python versions earlier than 3.9. Apply this diff: ```diff - def get_paused_items(self) -> list[str]: + def ...
riven
github_2023
python
883
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,446 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_...
_:warning: Potential issue_ **Fix the syntax error at line 47 by separating statements.** At line 47, the code `}import os` combines the closing brace of the dictionary and an import statement on the same line without proper separation, leading to a `SyntaxError`. Move `import os` to a new line. Apply this diff to...
riven
github_2023
python
883
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,446 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_...
_:hammer_and_wrench: Refactor suggestion_ **Use `List` from `typing` module instead of `list` for type annotations.** In the `__init__` method, type annotations use `list[Type]`, which is only supported in Python 3.9 and later. To maintain compatibility with earlier Python versions, replace `list[Type]` with `List[Ty...
riven
github_2023
python
883
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,446 @@ +from typing import Optional, List +from fastapi import APIRouter, Request +from pydantic import BaseModel + +router = APIRouter( + prefix="/queue", + tags=["queue"], + responses={404: {"description": "Not found"}}, +) + +class QueueStatusResponse(BaseModel): + is_paused: bool + paused_...
_:warning: Potential issue_ **Correct the logging statement in `cancel_job` to prevent `AttributeError`.** At line 266, `future_item` is likely a string representing the item ID and does not have a `log_string` attribute. Accessing `future_item.log_string` would raise an `AttributeError`. Update the logging statement...
riven
github_2023
others
868
rivenmedia
coderabbitai[bot]
@@ -1,5 +1,27 @@ # Changelog +## [0.19.0](https://github.com/rivenmedia/riven/compare/v0.18.0...v0.19.0) (2024-11-13) + + +### Features + +* add reindexing of movie/shows in unreleased or ongoing state ([139d936](https://github.com/rivenmedia/riven/commit/139d936442de4d5a37e32fb482beb2e65557464c)) +* added upload lo...
_:hammer_and_wrench: Refactor suggestion_ **Improve changelog entry clarity and completeness.** The entry contains "wip" and combines multiple unrelated changes into a single line. Consider splitting and clarifying: ```diff -* disable reindexing. wip. change get items endpoint to use id instead of imdbid. ([5123567]...
riven
github_2023
others
868
rivenmedia
coderabbitai[bot]
@@ -1,5 +1,28 @@ # Changelog +## [0.19.0](https://github.com/rivenmedia/riven/compare/v0.18.0...v0.19.0) (2024-11-14) + + +### Features + +* add reindexing of movie/shows in unreleased or ongoing state ([139d936](https://github.com/rivenmedia/riven/commit/139d936442de4d5a37e32fb482beb2e65557464c)) +* added upload lo...
_:hammer_and_wrench: Refactor suggestion_ **Improve changelog entry clarity and consistency.** The current entry is vague and has formatting inconsistencies: 1. Specify which scrapers were tweaked and what was fine-tuned 2. Remove the trailing period for consistency with other entries 3. Hyphenate "fine-tuning" ```d...
riven
github_2023
others
868
rivenmedia
coderabbitai[bot]
@@ -1,5 +1,28 @@ # Changelog +## [0.19.0](https://github.com/rivenmedia/riven/compare/v0.18.0...v0.19.0) (2024-11-14) + + +### Features + +* add reindexing of movie/shows in unreleased or ongoing state ([139d936](https://github.com/rivenmedia/riven/commit/139d936442de4d5a37e32fb482beb2e65557464c)) +* added upload lo...
_:hammer_and_wrench: Refactor suggestion_ **Split changelog entry into separate items.** Multiple significant changes are combined into a single entry. Consider splitting them for better clarity and tracking. ```diff -* updated torbox scraper to use api key. refactored scrapers slightly. added more logging to scrape...
riven
github_2023
python
882
rivenmedia
coderabbitai[bot]
@@ -397,51 +397,61 @@ def _init_db_from_symlinks(self): errors = [] added_items = set() - progress, console = create_progress_bar(len(items)) - task = progress.add_task("Enriching items with metadata", total=len(items), log="") + # Convert...
_:hammer_and_wrench: Refactor suggestion_ **Consider adding transaction rollback on errors** While committing after each chunk is good, consider adding explicit transaction rollback on errors to ensure data consistency. ```diff -# Commit after each chunk -session.commit() +try: + # Commit after each chunk + se...
riven
github_2023
python
880
rivenmedia
Gaisberg
@@ -212,39 +212,43 @@ def _retry_library(self) -> None: for item_id in result.scalars(): self.em.add_event(Event(emitted_by="RetryLibrary", item_id=item_id)) - def _reindex_ongoing(self) -> None: - """Reindex ongoing items.""" + def _update_ongoing(self) -> None: + ""...
Debug log maybe?
riven
github_2023
python
880
rivenmedia
Gaisberg
@@ -212,39 +212,43 @@ def _retry_library(self) -> None: for item_id in result.scalars(): self.em.add_event(Event(emitted_by="RetryLibrary", item_id=item_id)) - def _reindex_ongoing(self) -> None: - """Reindex ongoing items.""" + def _update_ongoing(self) -> None: + ""...
Could store_state() return previous, new state tuple instead?
riven
github_2023
python
880
rivenmedia
Gaisberg
@@ -212,39 +212,43 @@ def _retry_library(self) -> None: for item_id in result.scalars(): self.em.add_event(Event(emitted_by="RetryLibrary", item_id=item_id)) - def _reindex_ongoing(self) -> None: - """Reindex ongoing items.""" + def _update_ongoing(self) -> None: + ""...
This will not add shows with only episodes changed into queue
riven
github_2023
python
880
rivenmedia
Gaisberg
@@ -212,39 +212,43 @@ def _retry_library(self) -> None: for item_id in result.scalars(): self.em.add_event(Event(emitted_by="RetryLibrary", item_id=item_id)) - def _reindex_ongoing(self) -> None: - """Reindex ongoing items.""" + def _update_ongoing(self) -> None: + ""...
Again this should be debug
riven
github_2023
python
880
rivenmedia
coderabbitai[bot]
@@ -212,39 +212,43 @@ def _retry_library(self) -> None: for item_id in result.scalars(): self.em.add_event(Event(emitted_by="RetryLibrary", item_id=item_id)) - def _reindex_ongoing(self) -> None: - """Reindex ongoing items.""" + def _update_ongoing(self) -> None: + ""...
_:hammer_and_wrench: Refactor suggestion_ **Enhance error handling for database consistency** The current error handling catches exceptions but continues processing, which might leave the database in an inconsistent state. Consider rolling back the session on error and implementing retry logic. Here's a suggested im...
riven
github_2023
python
880
rivenmedia
coderabbitai[bot]
@@ -212,39 +212,43 @@ def _retry_library(self) -> None: for item_id in result.scalars(): self.em.add_event(Event(emitted_by="RetryLibrary", item_id=item_id)) - def _reindex_ongoing(self) -> None: - """Reindex ongoing items.""" + def _update_ongoing(self) -> None: + ""...
_:hammer_and_wrench: Refactor suggestion_ **Optimize database operations by batching commits** The current implementation commits changes for each item individually, which can be inefficient for large datasets. Consider batching the commits to improve performance. Here's a suggested optimization: ```diff counter =...
riven
github_2023
python
880
rivenmedia
coderabbitai[bot]
@@ -212,39 +212,42 @@ def _retry_library(self) -> None: for item_id in result.scalars(): self.em.add_event(Event(emitted_by="RetryLibrary", item_id=item_id)) - def _reindex_ongoing(self) -> None: - """Reindex ongoing items.""" + def _update_ongoing(self) -> None: + ""...
_:hammer_and_wrench: Refactor suggestion_ **Optimize database operations and enhance error handling** The current implementation has several areas for improvement: 1. Individual commits for each item can impact performance 2. No transaction rollback on error 3. No batch processing Consider this optimized implementat...
riven
github_2023
python
880
rivenmedia
Gaisberg
@@ -141,11 +141,13 @@ def __generate_composite_key(item: dict) -> str | None: item_type = item.get("type", "unknown") return f"{item_type}_{trakt_id}" - def store_state(self, given_state=None) -> None: + def store_state(self, given_state=None) -> tuple[States, States]: + """Store the st...
This wont do, as last_state is written in the line before. Could you store last_state into a temporary variable and provide it here?
riven
github_2023
python
880
rivenmedia
coderabbitai[bot]
@@ -141,11 +141,14 @@ def __generate_composite_key(item: dict) -> str | None: item_type = item.get("type", "unknown") return f"{item_type}_{trakt_id}" - def store_state(self, given_state=None) -> None: + def store_state(self, given_state=None) -> tuple[States, States]: + """Store the st...
_:hammer_and_wrench: Refactor suggestion_ **Improve event publishing logic for initial state transitions.** The condition `if previous_state and previous_state != new_state` might skip event publishing when `previous_state` is None, which could be important for tracking initial state assignments. Consider this alter...
riven
github_2023
python
879
rivenmedia
coderabbitai[bot]
@@ -218,7 +218,7 @@ def _get_indexer_from_json(self, json_content: str) -> list[ProwlarrIndexer]: """Parse the indexers from the XML content""" indexer_list = [] for indexer in json.loads(json_content): - indexer_list.append(ProwlarrIndexer(title=indexer["name"], id=str(indexer["id...
_:hammer_and_wrench: Refactor suggestion_ **Improve readability by breaking down the complex list comprehension.** The current line is difficult to read and maintain. Consider restructuring for better clarity: ```diff - indexer_list.append(ProwlarrIndexer(title=indexer["name"], id=str(indexer["id"]), link...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -104,7 +105,7 @@ def update_item_attributes(self, item: MediaItem, info, container) -> bool: elif item.type == "episode": show = item.parent.parent file_season, file_episodes = self.service.file_finder.container_file_matches_episode(file) - if fil...
_:bulb: Codebase verification_ **Review comment is partially valid - Documentation exists but tests are missing** The filesize validation criteria is already well-documented in `shared.py` with clear logging messages explaining the acceptable ranges and configuration validation. However, there are no dedicated tests ...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -162,3 +117,48 @@ def hash_from_uri(magnet_uri: str) -> str: return magnet_uri start = magnet_uri.index("urn:btih:") + len("urn:btih:") return magnet_uri[start : start + 40] + +min_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_min +max_movie_filesize = settings_manager.s...
_:hammer_and_wrench: Refactor suggestion_ **Improve validation function readability and maintainability.** The validation function could benefit from: 1. A docstring explaining its purpose 2. Extracted helper functions to reduce duplication 3. Better error messages including the actual invalid values Consider refact...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -162,3 +117,48 @@ return magnet_uri start = magnet_uri.index("urn:btih:") + len("urn:btih:") return magnet_uri[start : start + 40] + +min_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_min +max_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_max +...
_:hammer_and_wrench: Refactor suggestion_ **Add type hints and extract common validation logic.** The function needs: 1. Type hints for parameters and return value 2. A docstring explaining the validation rules 3. Extracted common validation logic shared with `filesize_is_acceptable_show` Consider refactoring to: `...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -162,3 +117,48 @@ return magnet_uri start = magnet_uri.index("urn:btih:") + len("urn:btih:") return magnet_uri[start : start + 40] + +min_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_min +max_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_max +...
_:hammer_and_wrench: Refactor suggestion_ **Extract common validation logic to reduce duplication.** This function is nearly identical to `filesize_is_acceptable_movie`. Consider extracting the common validation logic into a shared function. Consider refactoring both functions to use a shared implementation: ```pyt...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -162,3 +118,75 @@ def hash_from_uri(magnet_uri: str) -> str: return magnet_uri start = magnet_uri.index("urn:btih:") + len("urn:btih:") return magnet_uri[start : start + 40] + +min_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_min +max_movie_filesize = settings_manager.s...
_:hammer_and_wrench: Refactor suggestion_ **Use an enum for media types instead of strings.** Using string literals for media types is error-prone. Consider using an enum to make the code more maintainable and type-safe. ```diff +from enum import Enum, auto + +class MediaType(Enum): + MOVIE = "movie" + SHOW = ...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -162,3 +118,75 @@ return magnet_uri start = magnet_uri.index("urn:btih:") + len("urn:btih:") return magnet_uri[start : start + 40] + +min_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_min +max_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_max +...
_:hammer_and_wrench: Refactor suggestion_ **Add error handling for validation initialization.** The global validation state is initialized at module level without error handling. Consider wrapping it in a try-except block to ensure the module can still be imported if validation fails. ```diff -are_filesizes_valid = ...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -162,3 +118,75 @@ return magnet_uri start = magnet_uri.index("urn:btih:") + len("urn:btih:") return magnet_uri[start : start + 40] + +min_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_min +max_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_max +...
_:warning: Potential issue_ **Fix error logging and improve validation efficiency.** There are two issues in the validation function: 1. Bug: Accessing `.name` on a string in the error log 2. Performance: Unnecessary float conversion for infinite max size ```diff if not are_filesizes_valid: - logger.err...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -62,9 +62,9 @@ class TorboxModel(Observable): class DownloadersModel(Observable): video_extensions: List[str] = ["mp4", "mkv", "avi"] prefer_speed_over_quality: bool = True - movie_filesize_mb_min: int = -1 # MB + movie_filesize_mb_min: int = 0 # MB movie_filesize_mb_max: int = -1 # MB (-1 i...
_:hammer_and_wrench: Refactor suggestion_ **Add validation and documentation for episode filesize constraints.** Similar to movie filesize, add validation and improve documentation for episode filesize constraints. ```diff - episode_filesize_mb_min: int = 0 # MB - episode_filesize_mb_max: int = -1 # MB (-1 i...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -62,9 +62,9 @@ class DownloadersModel(Observable): video_extensions: List[str] = ["mp4", "mkv", "avi"] prefer_speed_over_quality: bool = True - movie_filesize_mb_min: int = -1 # MB + movie_filesize_mb_min: int = 0 # MB movie_filesize_mb_max: int = -1 # MB (-1 is no limit)
_:hammer_and_wrench: Refactor suggestion_ **Add validation and documentation for movie filesize constraints.** Consider adding field validation to ensure minimum size doesn't exceed maximum size, and improve documentation of the constraints. ```diff - movie_filesize_mb_min: int = 0 # MB - movie_filesize_mb_ma...
riven
github_2023
python
869
rivenmedia
Gaisberg
@@ -90,21 +91,24 @@ def update_item_attributes(self, item: MediaItem, info, container) -> bool: item = item container = container for file in container.values(): - if item.type == "movie" and self.service.file_finder.container_file_matches_movie(file): + if item.type == ...
Please handle this outside the method
riven
github_2023
python
869
rivenmedia
Gaisberg
@@ -116,4 +120,7 @@ def update_item_attributes(self, item: MediaItem, info, container) -> bool: # We have to make sure the episode is correct if item is an episode if item.type != "episode" or (item.type == "episode" and episode.number == item.number): ...
same as above
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -162,3 +119,71 @@ def hash_from_uri(magnet_uri: str) -> str: return magnet_uri start = magnet_uri.index("urn:btih:") + len("urn:btih:") return magnet_uri[start : start + 40] + +min_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_min +max_movie_filesize = settings_manager.s...
_:hammer_and_wrench: Refactor suggestion_ **Optimize validation logic and improve type safety.** The validation function has a few areas for improvement: 1. Converting to `float("inf")` is unnecessary when max_mb is -1 2. Using string literals for media types is error-prone 3. Error messages could be more descriptive...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -162,3 +119,71 @@ return magnet_uri start = magnet_uri.index("urn:btih:") + len("urn:btih:") return magnet_uri[start : start + 40] + +min_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_min +max_movie_filesize = settings_manager.settings.downloaders.movie_filesize_mb_max +...
_:bulb: Codebase verification_ Based on the results, I can now generate the final response as we have confirmed the absence of tests and limited documentation. **Tests and documentation needed for filesize validation feature** The codebase currently lacks: - Unit tests for the new filesize validation functions in `s...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -406,7 +423,7 @@ def copy(self, other): return self def __init__(self, item): - self.type = "movie" + self.type = MovieMediaType.Movie.value
_:warning: Potential issue_ **Move type assignments after super().__init__() call.** In the `Movie` and `Episode` classes, the type is assigned before calling the parent constructor. This could lead to issues if the parent constructor relies on the type being initialized. Move the type assignment after the super call...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -73,6 +73,12 @@ def run_service(service, item,): logger.error(f"Service {service.__class__.__name__} returned invalid results: {service_results}") return + # ensure that info hash is lower case in each result + if isinstance(service_results, dict): + ...
_:bulb: Codebase verification_ **Add tests for the info hash normalization logic** The verification confirms that: 1. There are no existing tests for the scraper's info hash normalization functionality 2. The info hash normalization is used in multiple places (scrapers, downloaders, and routes) 3. The project has an...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -114,6 +121,19 @@ def update_item_attributes(self, item: MediaItem, info, container) -> bool: episode.alternative_folder = info["original_filename"] episode.active_stream = {"infohash": info["hash"], "id": info["id"]} # We have to...
_:bulb: Codebase verification_ Based on the gathered information, I can now provide the final response: **File size validation implementation needs test coverage** While the implementation in `shared.py` is well-structured with proper validation logic, error handling, and configurable size limits, there are no dedic...
riven
github_2023
python
869
rivenmedia
coderabbitai[bot]
@@ -110,10 +123,24 @@ def update_item_attributes(self, item: MediaItem, info, container) -> bool: episode = next((episode for episode in season.episodes if episode.number == file_episode), None) if episode and episode.state not in [States.Completed, States.Symlinked, St...
_:warning: Potential issue_ **Add test coverage for file size validation.** As mentioned in the PR objectives and past reviews, tests are missing for the file size validation functionality. Please add tests to cover: - Movie file size validation - Show file size validation - Invalid file size handling - Edge cases (e...
riven
github_2023
python
869
rivenmedia
dreulavelle
@@ -17,6 +18,22 @@ from ..db.db_functions import blacklist_stream, reset_streams from .stream import Stream +class ShowMediaType(Enum): + """Show media types""" + Show = "show" + Season = "season" + Episode = "episode" + +class MovieMediaType(Enum): + """Media types""" + Movie = "movie" + +class M...
we dont need these classes lol, no need to make it more complicated than it has to be! ;)
riven
github_2023
python
862
rivenmedia
coderabbitai[bot]
@@ -159,24 +159,29 @@ def process_shows(directory: Path, item_type: str, is_anime: bool = False) -> Ge for episode in os.listdir(directory / show / season): if os.path.splitext(episode)[1][1:] not in ALLOWED_VIDEO_EXTENSIONS: continue - if not (episode_n...
_:warning: Potential issue_ **Ensure `end_ep` is greater than or equal to `start_ep`** When determining the range of episodes, if `end_ep` is less than `start_ep`, the `range` function will not iterate as expected. Add a check to confirm that `end_ep` is greater than or equal to `start_ep`. Apply this diff to add ...
riven
github_2023
python
862
rivenmedia
coderabbitai[bot]
@@ -159,24 +159,29 @@ def process_shows(directory: Path, item_type: str, is_anime: bool = False) -> Ge for episode in os.listdir(directory / show / season): if os.path.splitext(episode)[1][1:] not in ALLOWED_VIDEO_EXTENSIONS: continue - if not (episode_n...
_:warning: Potential issue_ **Avoid deleting files when episode number extraction fails** Deleting files when the episode number cannot be extracted may lead to unintended data loss, especially if the filename format is non-standard. Instead of removing the file, consider logging the issue and skipping the file to al...
riven
github_2023
python
862
rivenmedia
coderabbitai[bot]
@@ -159,24 +159,29 @@ def process_shows(directory: Path, item_type: str, is_anime: bool = False) -> Ge for episode in os.listdir(directory / show / season): if os.path.splitext(episode)[1][1:] not in ALLOWED_VIDEO_EXTENSIONS: continue - if not (episode_n...
_:warning: Potential issue_ **Add error handling for missing episode numbers in regex matches** When processing `ep_range`, if `ep_range[0]` is `None` or empty, calling `int(ep_range[0])` will raise a `ValueError`. To ensure robust processing, add checks to handle missing or invalid episode numbers before converting ...
riven
github_2023
python
862
rivenmedia
Gaisberg
@@ -159,24 +159,29 @@ def process_shows(directory: Path, item_type: str, is_anime: bool = False) -> Ge for episode in os.listdir(directory / show / season): if os.path.splitext(episode)[1][1:] not in ALLOWED_VIDEO_EXTENSIONS: continue - if not (episode_n...
Now that I think of it, please use RTN/parsett for this.
riven
github_2023
python
862
rivenmedia
coderabbitai[bot]
@@ -159,24 +160,26 @@ def process_shows(directory: Path, item_type: str, is_anime: bool = False) -> Ge for episode in os.listdir(directory / show / season): if os.path.splitext(episode)[1][1:] not in ALLOWED_VIDEO_EXTENSIONS: continue - if not (episode_n...
_:warning: Potential issue_ **Remove automatic file deletion to prevent data loss** Automatically deleting files that can't be parsed is risky and could lead to unintended data loss, especially if the issue is temporary or due to a parsing error. This was previously flagged in past reviews. Apply this diff to log th...
riven
github_2023
python
862
rivenmedia
coderabbitai[bot]
@@ -159,24 +160,26 @@ def process_shows(directory: Path, item_type: str, is_anime: bool = False) -> Ge for episode in os.listdir(directory / show / season): if os.path.splitext(episode)[1][1:] not in ALLOWED_VIDEO_EXTENSIONS: continue - if not (episode_n...
_:hammer_and_wrench: Refactor suggestion_ **Add validation for episode numbers** The code should validate episode numbers before processing them to ensure they are positive integers and within a reasonable range. Apply this diff to add validation: ```diff for episode_number in episode_numbers: + if not isinstan...
riven
github_2023
python
870
rivenmedia
coderabbitai[bot]
@@ -102,14 +102,15 @@ async def get_items( if Levenshtein.ratio(filter_lower, state_enum.name.lower()) >= 0.82: filter_states.append(state_enum) break - if len(filter_states) == len(states): - query = query.where(MediaItem.last_state.in_(filte...
_:hammer_and_wrench: Refactor suggestion_ **Improve Python syntax using `not in` operator.** The condition should use Python's `not in` operator for better readability and consistency with Python idioms. ```diff - if not 'All' in states: + if 'All' not in states: ``` <!-- suggestion_start --> <detai...
riven
github_2023
others
861
rivenmedia
coderabbitai[bot]
@@ -1,5 +1,20 @@ # Changelog +## [0.18.0](https://github.com/rivenmedia/riven/compare/v0.17.0...v0.18.0) (2024-11-05) + + +### Features + +* add retry policy and connection pool configuration to request utils ([#864](https://github.com/rivenmedia/riven/issues/864)) ([1713a51](https://github.com/rivenmedia/riven/comm...
_:warning: Potential issue_ **Remove duplicate bug fix entry.** The following bug fix entry appears twice: ```diff -* add HTTP adapter configuration for Jackett and Prowlarr scrapers to manage connection pool size ([0c8057a](https://github.com/rivenmedia/riven/commit/0c8057aef45fcccd2c855a8413729b39020439db)) -* add ...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -1 +1,41 @@ +from .listrr_api import ListrrAPI, ListrrAPIError +from .trakt_api import TraktAPI, TraktAPIError +from .plex_api import PlexAPI, PlexAPIError +from .overseerr_api import OverseerrAPI, OverseerrAPIError +from .mdblist_api import MdblistAPI, MdblistAPIError +from program.settings.manager import settings_...
_:warning: Potential issue_ **Add missing `__setup_listrr()` call in bootstrap sequence.** The `__setup_listrr()` function is defined but never called in the bootstrap sequence. This could lead to Listrr API functionality being unavailable. ```diff def bootstrap_apis(): __setup_trakt() __setup_plex() ...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -1 +1,41 @@ +from .listrr_api import ListrrAPI, ListrrAPIError +from .trakt_api import TraktAPI, TraktAPIError +from .plex_api import PlexAPI, PlexAPIError +from .overseerr_api import OverseerrAPI, OverseerrAPIError +from .mdblist_api import MdblistAPI, MdblistAPIError +from program.settings.manager import settings_...
_:hammer_and_wrench: Refactor suggestion_ **Add error handling for API initialization.** API initialization could fail due to various reasons (invalid credentials, network issues, etc.). Consider wrapping the initialization in try-except blocks to handle potential errors gracefully. Example implementation for Plex (...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -1 +1,41 @@ +from .listrr_api import ListrrAPI, ListrrAPIError +from .trakt_api import TraktAPI, TraktAPIError +from .plex_api import PlexAPI, PlexAPIError +from .overseerr_api import OverseerrAPI, OverseerrAPIError +from .mdblist_api import MdblistAPI, MdblistAPIError +from program.settings.manager import settings_...
_:warning: Potential issue_ **Add enabled check and configuration validation for TraktAPI setup.** Unlike other API setups, TraktAPI initialization lacks an enabled check and configuration validation. This could lead to unnecessary initialization or runtime errors. ```diff def __setup_trakt(): + if not settings_...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -50,7 +51,7 @@ async def overseerr(request: Request) -> Dict[str, Any]: def get_imdbid_from_overseerr(req: OverseerrWebhook) -> str: """Get the imdb_id from the Overseerr webhook""" imdb_id = req.media.imdbId - trakt_api = TraktAPI(rate_limit=False) + trakt_api = di[TraktAPI]
_:hammer_and_wrench: Refactor suggestion_ **Add error handling for dependency injection** While the change to DI is good, we should handle potential DI container errors when retrieving the TraktAPI instance. Consider wrapping the DI retrieval with error handling: ```diff - trakt_api = di[TraktAPI] + try: + ...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -30,6 +30,7 @@ def validate(self): if not self.settings.lists: logger.error("Mdblist is enabled, but list is empty.") return False + self.api = di[MdblistAPI]
_:hammer_and_wrench: Refactor suggestion_ **Add error handling for DI resolution** The dependency injection could fail if MdblistAPI is not registered in the DI container. Consider adding try-except to handle potential DI resolution errors. ```diff - self.api = di[MdblistAPI] + try: + self.a...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -3,6 +3,7 @@ from loguru import logger from requests import HTTPError from program.apis.plex_api import PlexAPI +from kink import di
_:bulb: Codebase verification_ **DI setup is properly configured but needs initialization order fix** The DI setup shows a potential initialization order issue: - `PlexAPI` is both directly instantiated and registered with DI in `apis/__init__.py` - Other modules correctly use `di[PlexAPI]` for dependency injection -...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -43,6 +43,13 @@ def validate_account(self): def validate_server(self): self.plex_server = PlexServer(self.BASE_URL, token=self.token, session=self.request_handler.session, timeout=60) + def set_rss_urls(self, rss_urls: List[str]): + self.rss_urls = rss_urls + + def clear_rss_urls(self): ...
_:hammer_and_wrench: Refactor suggestion_ **Add validation and improve documentation for RSS URL management methods.** The new methods provide good encapsulation of RSS URL management, but could benefit from additional validation and documentation. Consider these improvements: ```diff -def set_rss_urls(self, rss_ur...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -122,13 +126,15 @@ def start(self): latest_version = get_version() logger.log("PROGRAM", f"Riven v{latest_version} starting!") + settings_manager.register_observer(self.initialize_apis)
_:hammer_and_wrench: Refactor suggestion_ **Add validation for API initialization success.** While the initialization order is correct, the code should validate that APIs are properly initialized before proceeding with service initialization. Consider adding a validation method and using it: ```diff + def valida...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -64,8 +65,11 @@ self.malloc_time = time.monotonic()-50 self.last_snapshot = None - def initialize_services(self): + def initialize_apis(self): + bootstrap_apis()
_:hammer_and_wrench: Refactor suggestion_ **Add error handling and logging to API initialization.** The method should include error handling and logging to track API initialization status and handle potential failures gracefully. Consider this implementation: ```diff def initialize_apis(self): + logger.log("PRO...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -99,19 +99,22 @@ class TraktOAuthInitiateResponse(BaseModel): @router.get("/trakt/oauth/initiate", operation_id="trakt_oauth_initiate") async def initiate_trakt_oauth(request: Request) -> TraktOAuthInitiateResponse: - trakt = request.app.program.services.get(TraktContent) - if trakt is None: + trakt_api...
_:hammer_and_wrench: Refactor suggestion_ **Return an instance of `TraktOAuthInitiateResponse` instead of a dictionary** The function `initiate_trakt_oauth` is annotated to return a `TraktOAuthInitiateResponse` object but returns a dictionary instead. To align with the return type and ensure proper serialization, ret...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -99,19 +99,22 @@ @router.get("/trakt/oauth/initiate", operation_id="trakt_oauth_initiate") async def initiate_trakt_oauth(request: Request) -> TraktOAuthInitiateResponse: - trakt = request.app.program.services.get(TraktContent) - if trakt is None: + trakt_api = di[TraktAPI] + if trakt_api is None: ...
_:hammer_and_wrench: Refactor suggestion_ **Use appropriate HTTP status codes and improve error handling** The current implementation raises exceptions with status code 404 when `trakt_api` or `trakt_api_key` is not found. Since these are server-side configuration issues, consider using 500 Internal Server Error or 5...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -29,16 +32,17 @@ class TraktAPI: "short_list": re.compile(r"https://trakt.tv/lists/\d+") } - def __init__(self, api_key: Optional[str] = None, rate_limit: bool = True): - self.api_key = api_key - rate_limit_params = get_rate_limit_params(max_calls=1000, period=300) if rate_limit else...
_:warning: Potential issue_ **Ensure OAuth parameters are validated and handled securely** The `__init__` method now accepts `oauth_client_id`, `oauth_client_secret`, and `oauth_redirect_uri`, all defaulting to `None`. However, there's no validation to ensure these are provided when necessary. This could lead to runt...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -279,6 +283,38 @@ logger.error(f"Unknown item type {item_type} for {data.title} not found in list of acceptable items") return None + def perform_oauth_flow(self) -> str: + """Initiate the OAuth flow and return the authorization URL.""" + params = { + "...
_:hammer_and_wrench: Refactor suggestion_ **Handle missing OAuth parameters in `perform_oauth_flow`** The `perform_oauth_flow` method uses `self.oauth_client_id` and `self.oauth_redirect_uri` without checking if they are `None`. If these are not set, it could lead to a malformed URL or runtime errors. Add validati...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -279,6 +283,38 @@ logger.error(f"Unknown item type {item_type} for {data.title} not found in list of acceptable items") return None + def perform_oauth_flow(self) -> str: + """Initiate the OAuth flow and return the authorization URL.""" + params = { + "...
_:warning: Potential issue_ **Ensure secure storage of access and refresh tokens** Tokens are being saved using `settings_manager.save()`. It's important to ensure that the tokens are stored securely to prevent unauthorized access. Verify that `settings_manager` securely stores sensitive information, such as encry...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -29,16 +32,17 @@ "short_list": re.compile(r"https://trakt.tv/lists/\d+") } - def __init__(self, api_key: Optional[str] = None, rate_limit: bool = True): - self.api_key = api_key - rate_limit_params = get_rate_limit_params(max_calls=1000, period=300) if rate_limit else None - s...
_:warning: Potential issue_ **Avoid hardcoding sensitive information** The `CLIENT_ID` is hardcoded within the class. While client IDs may not be as sensitive as client secrets, it's best practice to avoid hardcoding credentials in the codebase. Retrieve the `CLIENT_ID` from a secure configuration or environment v...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -279,6 +283,38 @@ logger.error(f"Unknown item type {item_type} for {data.title} not found in list of acceptable items") return None + def perform_oauth_flow(self) -> str: + """Initiate the OAuth flow and return the authorization URL.""" + params = { + "...
_:warning: Potential issue_ **Incorrect use of API key in OAuth token exchange** In the `handle_oauth_callback` method, the `api_key` parameter is used to set the `trakt-api-key` header with a `Bearer` token, which is unconventional for an OAuth token exchange. Additionally, the `api_key` parameter may not be necessa...
riven
github_2023
python
859
rivenmedia
coderabbitai[bot]
@@ -10,6 +10,7 @@ from program.utils import root_dir import alembic +from program.utils import root_dir
_:hammer_and_wrench: Refactor suggestion_ **Remove duplicate import of `root_dir`.** The import statement at line 13 re-imports `root_dir` from `program.utils`, which is already imported at line 10. This redundant import should be removed to clean up the code. Apply this diff to remove the duplicate import: ```di...
riven
github_2023
python
857
rivenmedia
coderabbitai[bot]
@@ -0,0 +1,146 @@ +import time +import responses +from requests.exceptions import HTTPError +from program.utils.request import create_service_session, get_rate_limit_params, HttpMethod, BaseRequestHandler, ResponseType, RateLimitExceeded + +@responses.activate +def test_rate_limiter_with_base_request_handler(): + #...
_:hammer_and_wrench: Refactor suggestion_ **Improve code reuse and test reliability.** Consider these improvements: 1. Extract common setup code into a fixture 2. Make the reset wait time relative to the rate limit 3. Consider parameterizing similar test cases ```diff +import pytest + +@pytest.fixture +def rate_limi...
riven
github_2023
python
857
rivenmedia
coderabbitai[bot]
@@ -118,9 +118,13 @@ def _request(self, method: HttpMethod, endpoint: str, ignore_base_url: Optional[ logger.debug(f"ResponseObject: status_code={response_obj.status_code}, data={response_obj.data}") return response_obj - except RequestException as e: - logger.error(f"R...
_:warning: Potential issue_ **Ensure `e.response` is not `None` before accessing `status_code`** When handling `HTTPError`, there is a possibility that `e.response` may be `None`. Accessing `e.response.status_code` without checking can raise an `AttributeError`. Consider adding a check to ensure `e.response` is not `...
riven
github_2023
python
848
rivenmedia
coderabbitai[bot]
@@ -7,31 +18,26 @@ class MdblistAPI: def __init__(self, api_key: str): self.api_key = api_key - rate_limit_params = get_rate_limit_params(per_minute=60) - - self.session = create_service_session( - rate_limit_params=rate_limit_params, - use_cache=False - ) + ...
_:hammer_and_wrench: Refactor suggestion_ **Consider moving API key handling to the request handler.** Currently, the API key is exposed in URL parameters. It would be more secure to handle this in the request handler, either through headers or by adding it to the request parameters internally. Example refactor: ``...
riven
github_2023
python
848
rivenmedia
coderabbitai[bot]
@@ -13,12 +22,13 @@ def __init__(self, api_key: str): self.BASE_URL = "https://listrr.pro" self.api_key = api_key self.headers = {"X-Api-Key": self.api_key} - self.session = create_service_session() - self.session.headers.update(self.headers) + session = create_service_se...
_:hammer_and_wrench: Refactor suggestion_ **Remove redundant base URL in validate method.** The base URL is already configured in the request handler during initialization. The endpoint should be relative. ```diff - return self.request_handler.execute(HttpMethod.GET, self.BASE_URL) + return self.reques...
riven
github_2023
python
848
rivenmedia
coderabbitai[bot]
@@ -33,9 +43,9 @@ page, total_pages = 1, 1 while page <= total_pages: try: - url = f"{self.BASE_URL}/api/List/{content_type}/{list_id}/ReleaseDate/Descending/{page}" - response = get(session=self.session, url=url).response - ...
_:hammer_and_wrench: Refactor suggestion_ **Use relative URL path and custom exception handling.** The URL should be relative since base URL is handled by the request handler. Also, consider catching and re-raising ListrrAPIError for consistent error handling. ```diff - url = f"api/List/{content_t...