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 | 848 | rivenmedia | coderabbitai[bot] | @@ -64,7 +65,7 @@ def scrape(self, item: MediaItem) -> tuple[Dict[str, str], int]:
if identifier:
url += identifier
- response = get(self.session, f"{url}.json", timeout=self.timeout)
+ response = self.request_handler.execute(HttpMethod.GET, f"{url}.json", timeout=self.timeout)
... | _:hammer_and_wrench: Refactor suggestion_
**Add defensive response data handling**
The current implementation assumes `response.data.streams` exists. Consider adding defensive checks to handle potential malformed responses gracefully.
```diff
- response = self.request_handler.execute(HttpMethod.GET, f"{url}.j... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -31,7 +41,7 @@ def validate(self) -> bool:
return False
try:
- response = get(f"{self.settings.url}/Users?api_key={self.settings.api_key}")
+ response = self.request_handler.execute(HttpMethod.GET, f"{self.settings.url}/Users?api_key={self.settings.api_key}") | _:warning: Potential issue_
**Security: API key exposed in URL.**
The API key should be passed as a query parameter instead of being embedded in the URL path to prevent it from being logged in server logs or proxy servers.
```diff
- response = self.request_handler.execute(HttpMethod.GET, f"{self.settings.... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -52,8 +63,8 @@ def get_items_from_rss(self) -> list[str]:
rss_items: list[str] = []
for rss_url in self.rss_urls:
try:
- response = self.session.get(rss_url + "?format=json", timeout=60)
- for _item in response.json().get("items", []):
+ res... | _:hammer_and_wrench: Refactor suggestion_
**Improve response handling and error management.**
The current implementation has several areas for improvement:
1. The response handling assumes the existence of a 'get' method on response.data, which might not be safe with SIMPLE_NAMESPACE response type.
2. The generic Ex... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -77,7 +79,7 @@ def check_limit(self) -> bool:
"""Check if the user has exceeded the rate limit for the Orionoid API."""
url = f"{self.base_url}?keyapp={KEY_APP}&keyuser={self.settings.api_key}&mode=user&action=retrieve"
try:
- response = get(self.session, url)
+ respo... | _:hammer_and_wrench: Refactor suggestion_
**Maintain consistency in request handler parameters.**
The request execution is missing timeout and retry parameters that are used in other similar methods.
```diff
- response = self.request_handler.execute(HttpMethod.GET, url)
+ response = self.reque... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -10,13 +10,22 @@
from program.media.stream import Stream
from program.settings.manager import settings_manager
from program.settings.versions import models
+from program.utils.request import BaseRequestHandler, Session, ResponseType, ResponseObject, HttpMethod
enable_aliases = settings_manager.settings.scrapin... | _:bulb: Codebase verification_
**Consider enhancing `ScraperRequestHandler` with common scraping patterns**
Based on the analysis of the codebase, the current implementation can be improved to better achieve standardization. Common patterns found across scrapers include:
1. Consistent error handling for:
- Rate l... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -18,6 +27,8 @@ def __init__(self):
self.key = "trakt"
self.settings = settings_manager.settings.content.trakt
self.api = TraktAPI(self.settings.api_key)
+ session = create_service_session()
+ self.oauth_request_handler = TraktOAuthRequestHandler(session) | _:hammer_and_wrench: Refactor suggestion_
**Add error handling for session creation.**
The session creation and request handler initialization should include error handling to gracefully handle potential connection or configuration issues.
```diff
- session = create_service_session()
- self.oauth_reque... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -7,32 +7,38 @@
from program.apis.trakt_api import TraktAPI
from program.media.item import MediaItem
from program.settings.manager import settings_manager
-from program.utils.request import delete, get, ping, post, get_rate_limit_params, create_service_session
+from program.utils.request import BaseRequestHandler,... | _:hammer_and_wrench: Refactor suggestion_
**Potential performance issue with high `take` value**
Requesting `take=10000` records may lead to performance bottlenecks or API timeouts. Consider implementing pagination or fetching a reasonable number of records per request.
<!-- This is an auto-generated comment by Code... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -1,82 +1,52 @@
import json
+from enum import Enum
from types import SimpleNamespace
-from typing import Optional, Dict, Union, Type, Any, Tuple
+from typing import Dict, Type, Optional
from requests import Session
from lxml import etree
-from requests.adapters import HTTPAdapter
-from requests.exceptions import ... | _:hammer_and_wrench: Refactor suggestion_
**Adjust the return type annotation of `to_dict` method in `BaseRequestParameters`**
The `to_dict` method returns a dictionary of attribute values that may not all be of type `Optional[str]`. To accurately represent the possible types of the values, consider changing the retu... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -242,8 +244,8 @@ def _get_indexer_from_xml(self, xml_content: str) -> list[JackettIndexer]:
def _fetch_results(self, url: str, params: Dict[str, str], indexer_title: str, search_type: str) -> List[Tuple[str, str]]:
"""Fetch results from the given indexer"""
try:
- response = get(ses... | _:warning: Potential issue_
**Handle `RateLimitExceeded` exception in `_fetch_results`**
While updating `_fetch_results` to use `self.request_handler.execute`, it's important to handle exceptions that may be raised by this method, such as `RateLimitExceeded`. Currently, this exception is not being caught, which could... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -69,7 +71,7 @@ def scrape(self, item: MediaItem) -> tuple[Dict[str, str], int]:
query_params = self._build_query_params(item)
url = f"{self.base_url}/torrents/{query_params}?metadata=false"
- response = get(self.session, url, timeout=self.timeout)
+ response = self.request_handler.e... | _:warning: Potential issue_
**Ensure proper validation before accessing nested response attributes**
Accessing `response.data.data.torrents` assumes that all nested attributes are present. To prevent potential `AttributeError`, add checks to verify that `response.data` and `response.data.data` are not `None` before a... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -30,7 +32,7 @@
logger.error("TorBox timeout is not set or invalid.")
return False
try:
- response = ping(self.session, f"{self.base_url}/torrents/imdb:tt0944947?metadata=false&season=1&episode=1", timeout=self.timeout)
+ response = self.request_handler.execute... | _:hammer_and_wrench: Refactor suggestion_
**Catch specific exceptions instead of the broad `Exception`**
Catching the base `Exception` class can obscure unexpected errors and make debugging harder. It's better to catch more specific exceptions related to HTTP requests, such as `RequestException`.
Apply this diff t... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -31,10 +41,11 @@ def __init__(self, api_key: Optional[str] = None, rate_limit: bool = True):
"trakt-api-key": self.api_key or self.CLIENT_ID,
"trakt-api-version": "2"
}
- self.session.headers.update(self.headers)
+ session.headers.update(self.headers)
+ self.re... | _:hammer_and_wrench: Refactor suggestion_
**Avoid updating session headers directly; pass headers per request instead**
Updating the session headers with `session.headers.update(self.headers)` can lead to unintended side effects, especially if the session is shared across multiple requests or threads. It's safer to p... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -1,37 +1,42 @@
-from program.utils.request import get_rate_limit_params, create_service_session, get, ping
+from program.utils.request import get_rate_limit_params, create_service_session, BaseRequestHandler, Session, ResponseType, ResponseObject, HttpMethod
+
+
+class MdblistAPIError(Exception):
+ """Base exce... | _:warning: Potential issue_
**Add URL validation in list_items_by_url method.**
The method manipulates URLs without proper validation, which could lead to unexpected behavior with malformed URLs.
Consider adding URL validation:
```diff
def list_items_by_url(self, url: str):
+ from urllib.parse import ur... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -33,9 +43,9 @@ def get_items_from_Listrr(self, content_type, content_lists) -> list[MediaItem]
page, total_pages = 1, 1
while page <= total_pages:
try:
- url = f"{self.BASE_URL}/api/List/{content_type}/{list_id}/ReleaseDate/Descending/{page}"
- ... | _:hammer_and_wrench: Refactor suggestion_
**Enhance error handling and data validation.**
While the URL construction is correct, consider these improvements:
1. Add specific error handling for response data access:
```diff
- data = response.data
+ if not hasattr(response, 'data'... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -1,19 +1,29 @@
"""Jellyfin Updater module"""
from types import SimpleNamespace
-from typing import Generator
+from typing import Generator, Type, Optional
from loguru import logger
from program.media.item import MediaItem
from program.settings.manager import settings_manager
-from program.utils.request impo... | _:hammer_and_wrench: Refactor suggestion_
**Add error handling for session creation.**
The session creation could fail, but there's no error handling. Consider wrapping it in a try-catch block.
```diff
- session = create_service_session()
- self.request_handler = JellyfinRequestHandler(session)
+ ... |
riven | github_2023 | python | 848 | rivenmedia | coderabbitai[bot] | @@ -242,10 +244,13 @@ def _get_indexer_from_xml(self, xml_content: str) -> list[JackettIndexer]:
def _fetch_results(self, url: str, params: Dict[str, str], indexer_title: str, search_type: str) -> List[Tuple[str, str]]:
"""Fetch results from the given indexer"""
try:
- response = get(s... | _:warning: Potential issue_
**Reorder exception handling to correctly handle `RateLimitExceeded`**
Currently, the `RateLimitExceeded` exception is being caught after the more general exceptions `(HTTPError, ConnectionError, Timeout)`. If `RateLimitExceeded` is a subclass of any of these exceptions, it might be caught... |
riven | github_2023 | python | 847 | rivenmedia | coderabbitai[bot] | @@ -26,7 +26,7 @@ def validate(self):
logger.error("Plex token is not set!")
return False
try:
- self.api.validate()
+ self.api.validate_account() | _:bulb: Codebase verification_
**Inconsistent API method naming detected across services**
The validation method is inconsistently named across different service modules:
- `validate_account()` in `plex_watchlist.py`
- `validate()` in:
- `listrr.py`
- `trakt.py`
- `mdblist.py`
- `overseerr.py`
<details>
<s... |
riven | github_2023 | python | 847 | rivenmedia | coderabbitai[bot] | @@ -179,7 +177,7 @@ def _make_request(
finally:
session.close()
- return ResponseObject(response, response_type)
+ return ResponseObject(response) | _:warning: Potential issue_
**Fix inconsistent response handling in error cases.**
There's a potential bug in the error handling logic of `_make_request`. When an exception occurs, `_handle_request_exception()` returns a `ResponseObject`, but in the success path, we're assigning the raw `response`. This creates incon... |
riven | github_2023 | python | 785 | rivenmedia | filiptrplan | @@ -230,6 +231,43 @@ async def add_items(request: Request, imdb_ids: str = None) -> MessageResponse:
return {"message": f"Added {len(valid_ids)} item(s) to the queue"}
+@router.post(
+ "/add-manually",
+ summary="Add Media Items Manually",
+ description="Add media item manually with a magnet link or i... | We should also check if the torrent is cached on RD before we add an item. |
riven | github_2023 | python | 785 | rivenmedia | filiptrplan | @@ -230,6 +231,43 @@ async def add_items(request: Request, imdb_ids: str = None) -> MessageResponse:
return {"message": f"Added {len(valid_ids)} item(s) to the queue"}
+@router.post(
+ "/add-manually",
+ summary="Add Media Items Manually",
+ description="Add media item manually with a magnet link or i... | @dreulavelle I'm not that familiar with the backend. In order for a stream to download should it be added to `streams` or to `active_stream`? |
riven | github_2023 | python | 785 | rivenmedia | dreulavelle | @@ -230,6 +232,77 @@ async def add_items(request: Request, imdb_ids: str = None) -> MessageResponse:
return {"message": f"Added {len(valid_ids)} item(s) to the queue"}
+@router.post(
+ "/add-manually",
+ summary="Add Media Items Manually",
+ description="Add media item manually with a magnet link or i... | we handle by id's now, so when the id_handling branch is done this will need to change to `item._id` |
riven | github_2023 | python | 785 | rivenmedia | the-eversio | @@ -385,7 +458,8 @@ class SetTorrentRDResponse(BaseModel):
def add_torrent(request: Request, id: int, magnet: str) -> SetTorrentRDResponse:
torrent_id = ""
try:
- torrent_id = add_torrent_magnet(magnet)
+ _, infohash = get_type_and_infohash(magnet)
+ torrent_id = add_torrent(infohash) | This will fail for AllDebrid :/ |
riven | github_2023 | python | 777 | rivenmedia | dreulavelle | @@ -73,18 +76,33 @@ def missing(self):
logger.log("TRAKT", "Trending fetching is disabled.")
if not self.settings.fetch_popular:
logger.log("TRAKT", "Popular fetching is disabled.")
+ if not self.settings.fetch_most_watched:
+ logger.log("TRAKT", "Most watched fetchi... | I was thinking a class attr, like `self.last_update` lol. I always though `global` was gross 😅 |
riven | github_2023 | python | 777 | rivenmedia | dreulavelle | @@ -73,18 +76,33 @@ def missing(self):
logger.log("TRAKT", "Trending fetching is disabled.")
if not self.settings.fetch_popular:
logger.log("TRAKT", "Popular fetching is disabled.")
+ if not self.settings.fetch_most_watched:
+ logger.log("TRAKT", "Most watched fetchi... | I was thinking to just add this to those functions instead, but this works too 😁 |
riven | github_2023 | python | 777 | rivenmedia | dreulavelle | @@ -13,6 +14,8 @@
from utils.ratelimiter import RateLimiter
from utils.request import get, post
+# Global variable to track the last update time
+last_update = None | you can get rid of this one |
riven | github_2023 | python | 777 | rivenmedia | dreulavelle | @@ -174,6 +174,9 @@ class TraktModel(Updatable):
trending_count: int = 10
fetch_popular: bool = False
popular_count: int = 10
+ fetch_most_watched: bool = False
+ most_watched_period: str = "weekly" | do we want to set daily by default? |
riven | github_2023 | python | 777 | rivenmedia | dreulavelle | @@ -73,18 +77,31 @@ def missing(self):
logger.log("TRAKT", "Trending fetching is disabled.")
if not self.settings.fetch_popular:
logger.log("TRAKT", "Popular fetching is disabled.")
+ if not self.settings.fetch_most_watched:
+ logger.log("TRAKT", "Most watched fetchi... | Honestly, we can ditch these 3 log messages, as they dont really provide any value to the user. I used to use them before as a way to show users whats available.. we can remove these 3 log messages though 👌 |
riven | github_2023 | python | 817 | rivenmedia | dreulavelle | @@ -321,20 +325,20 @@ def get_aliases(self) -> dict:
def __hash__(self):
return hash(self._id)
- def reset(self, soft_reset: bool = False):
+ def reset(self):
"""Reset item attributes."""
if self.type == "show":
for season in self.seasons:
for episod... | might be dangerous here to go Indexed on a reset, should we check first if the item has a title, then if so use Indexed, otherwise, requested? |
riven | github_2023 | python | 816 | rivenmedia | dreulavelle | @@ -308,15 +308,18 @@ class RetryResponse(BaseModel):
async def retry_items(request: Request, ids: str) -> RetryResponse:
"""Re-add items to the queue"""
ids = handle_ids(ids)
- try:
- media_items_generator = get_media_items_by_ids(ids)
- for media_item in media_items_generator:
- ... | do we want to go back to 0 here, or possibly set to 1 ? |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -45,7 +45,10 @@
def handle_ids(ids: str) -> list[int]:
- ids = [int(id) for id in ids.split(",")] if "," in ids else [int(ids)]
+ if isinstance(ids, int): | ids cant be int here |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -282,13 +285,13 @@ class ResetResponse(BaseModel):
description="Reset media items with bases on item IDs",
operation_id="reset_items",
)
-async def reset_items(request: Request, ids: str) -> ResetResponse:
+async def reset_items(request: Request, ids: int) -> ResetResponse: | is this type definition correct? we cant have multiple ids in one int |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -492,7 +496,7 @@ def set_torrent_rd(request: Request, id: int, torrent_id: str) -> SetTorrentRDRe
session.commit()
- request.app.program.em.add_event(Event("Symlinker", item))
+ request.app.program.em.add_event(Event("Symlinker", item._)) | ? |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -354,38 +281,57 @@ def _get_item_ids(session, item):
)
related_ids = season_ids + episode_ids
- return show_id, related_ids
+ return item_id, related_ids
| Can you return at the bottom of the method? Makes it easier to follow the code. |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -321,27 +259,16 @@ def load_streams_in_pages(session: Session, media_item_id: int, page_number: int
stream = session.query(Stream).get(stream_id)
yield stream_id, infohash, stream
-def _get_item_ids(session, item):
- from program.media.item import Episode, Season
-
- if item.type == "... | Would it be beneficial to load_only item with seasons and episodes instead of looking for seasons and episodes with parent_id? Im not sure:
https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -354,38 +281,57 @@ def _get_item_ids(session, item):
)
related_ids = season_ids + episode_ids
- return show_id, related_ids
+ return item_id, related_ids
- elif item.type == "season":
- season_id = item._id
+ elif item_type == "season":
+ # Fetch e... | import at top level if possible |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -403,74 +349,66 @@ def _get_item_type_from_db(item: "MediaItem") -> str:
from program.media.item import MediaItem
with db.Session() as session:
if item._id is None:
- return session.execute(select(MediaItem.type).where((MediaItem.imdb_id==item.imdb_id) & (MediaItem.type.in_(["show", ... | Isnt this the same as store_or_update_item? Make it return bool and use it |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -23,7 +23,7 @@ class MediaItem(db.Model):
"""MediaItem class"""
__tablename__ = "MediaItem"
_id: Mapped[int] = mapped_column(primary_key=True)
- item_id: Mapped[str] = mapped_column(sqlalchemy.String, nullable=False)
+ # item_id: Mapped[str] = mapped_column(sqlalchemy.String, nullable=True) | Removed commentend lines from this file |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -425,13 +425,13 @@ def __init__(self, item):
self.type = "show"
self.locations = item.get("locations", [])
self.seasons: list[Season] = item.get("seasons", [])
- self.item_id = item.get("imdb_id")
+ # self.item_id = item.get("imdb_id")
self.propagate_attributes_to_ch... | use "item_id" argument name here like in db functions else. |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -602,10 +602,10 @@ def fill_in_missing_children(self, other: Self):
if e.number not in existing_episodes:
self.add_episode(e)
- def get_episode_index_by_id(self, item_id):
- """Find the index of an episode by its item_id."""
+ def get_episode_index_by_id(self, _id): | use "item_id" argument name here like in db functions else. |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -172,83 +173,50 @@ def start(self):
ws_manager.send_health_update("running")
self.initialized = True
- # def _retry_library(self) -> None:
- # count = 0
- # with db.Session() as session:
- # count = session.execute(
- # select(func.count(MediaItem._id))
... | is batching necessary as the memory required is dramatically decreased with these changes? |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -304,6 +272,8 @@ def _schedule_services(self) -> None:
logger.debug(f"Scheduled {service_cls.__name__} to run every {update_interval} seconds.")
def display_top_allocators(self, snapshot, key_type="lineno", limit=10):
+ import psutil | top level import please |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -403,74 +349,66 @@ def _get_item_type_from_db(item: "MediaItem") -> str:
from program.media.item import MediaItem
with db.Session() as session:
if item._id is None:
- return session.execute(select(MediaItem.type).where((MediaItem.imdb_id==item.imdb_id) & (MediaItem.type.in_(["show", ... | The method isnt callable without item_id, this is redundant |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -490,16 +428,18 @@ def _run_thread_with_db_item(fn, service, program, input_item: "MediaItem" = Non
for i in fn(input_item):
if isinstance(i, (MediaItem)):
with db.Session() as session:
- _check_for_and_run_insertion_require... | We cant just blindly add the item, this will result in duplicates. Look through the database for existing items with the same imdb_id first and if found then merge in this method. |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -78,27 +78,23 @@ def _process_future(self, future, service):
item, timestamp = result
else:
item, timestamp = result, datetime.now()
+ if item and not hasattr(item, "_id"):
+ store_or_update_item(item) | Isnt this already done in the _run_thread_with_db_item method? |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -217,35 +210,12 @@ def cancel_job(self, item, suppress_logs=False):
self._futures.remove(future)
# Clear from queued and running events
- with self.mutex:
- self._remove_id_queue.append(item._id)
- self._queued_events = [event for event in self._queued_events ... | remove this as its not needed? |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -288,33 +258,9 @@ def _id_in_running_events(self, _id):
Returns:
bool: True if the item is in the running events, False otherwise.
"""
- return any(event.item._id == _id for event in self._running_events)
-
- def _imdb_id_in_queue(self, imdb_id):
- """
- Checks ... | log_message is redundant, we already have info and debug levels for logging. |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -326,43 +272,54 @@ def add_event(self, event):
"""
# Check if the event's item is a show and its seasons or episodes are in the queue or running
with db.Session() as session:
- item_id, related_ids = _get_item_ids(session, event.item)
+ item_id, related_ids = _get_ite... | remove commented out lines |
riven | github_2023 | python | 787 | rivenmedia | Gaisberg | @@ -326,43 +272,54 @@ def add_event(self, event):
"""
# Check if the event's item is a show and its seasons or episodes are in the queue or running
with db.Session() as session:
- item_id, related_ids = _get_item_ids(session, event.item)
+ item_id, related_ids = _get_ite... | Use the cool new method store or update item in db |
riven | github_2023 | python | 762 | rivenmedia | dreulavelle | @@ -2,7 +2,7 @@
from program.media.item import MediaItem
from program.settings.manager import settings_manager
-from utils.logger import logger
+from loguru import logger | `from utils.logger import logger` is the logger to use. We instantiate it there and handle the configuration of it.. then use that logger throughout the app.. |
riven | github_2023 | python | 782 | rivenmedia | dreulavelle | @@ -15,11 +15,12 @@ def __init__(self):
self.key = "downloader"
self.initialized = False
self.speed_mode = settings_manager.settings.downloaders.prefer_speed_over_quality
- self.service = next((service for service in [
- RealDebridDownloader(),
- AllDebridDownload... | what does this fix? |
riven | github_2023 | others | 757 | rivenmedia | the-eversio | @@ -76,7 +76,16 @@ echo "Container Initialization complete."
echo "Starting Riven (Backend)..."
if [ "$PUID" = "0" ]; then
- cd /riven/src && poetry run python3 main.py
+ if [ "${DEBUG}" != "" ]; then # check if DEBUG is set to a truthy value
+ cd /riven/src && poetry add debugpy && poetry run python3... | Do we really want to open a debugger to the world when running as root? |
riven | github_2023 | python | 743 | rivenmedia | dreulavelle | @@ -51,594 +34,185 @@ def validate(self) -> bool:
if not self.settings.api_key:
logger.warning("All-Debrid API key is not set")
return False
- if not isinstance(self.download_settings.movie_filesize_min, int) or self.download_settings.movie_filesize_min < -1:
- logge... | the run func should stay as its used everywhere |
riven | github_2023 | python | 743 | rivenmedia | dreulavelle | @@ -0,0 +1,162 @@
+import json
+
+import pytest
+from program.downloaders import alldebrid
+from program.downloaders.alldebrid import (
+ AllDebridDownloader,
+ add_torrent,
+ get_instant_availability,
+ get_status,
+ get_torrents,
+)
+from program.settings.manager import settings_manager as settings
+
+... | We are going to have to mock other api calls elsewhere anyways as the whole app needs to have testing.. but it changes so frequently that its hard to stay on top of. Appreciate the unit test! |
riven | github_2023 | python | 743 | rivenmedia | dreulavelle | @@ -51,594 +34,185 @@ def validate(self) -> bool:
if not self.settings.api_key:
logger.warning("All-Debrid API key is not set")
return False
- if not isinstance(self.download_settings.movie_filesize_min, int) or self.download_settings.movie_filesize_min < -1:
- logge... | RD's titles can have alternates, its used when trying to symlink so that we can keep track if we cant symlink 1 filename, then we try the other |
riven | github_2023 | python | 743 | rivenmedia | dreulavelle | @@ -51,594 +34,185 @@ def validate(self) -> bool:
if not self.settings.api_key:
logger.warning("All-Debrid API key is not set")
return False
- if not isinstance(self.download_settings.movie_filesize_min, int) or self.download_settings.movie_filesize_min < -1:
- logge... | here is one example of a cached container on RD via the `instantAvailability` endpoint.
- `/torrents/instantAvailability/47E4B344A13485BED48798A2A42C74FDFF14F3F0`
```json
{
"47e4b344a13485bed48798a2a42c74fdff14f3f0": {
"rd": [
{
"4": {
"filename": "... |
riven | github_2023 | python | 733 | rivenmedia | dreulavelle | @@ -265,6 +272,96 @@ async def remove_item(request: Request, ids: str):
return {"success": True, "message": f"Removed items with ids {ids}"}
+@router.post("/{id}/set_torrent_rd_magnet", description="Set a torrent for a media item using a magnet link.")
+def add_torrent(request: Request, id: int, magnet: str):
... | theres a reset somewhere else already |
riven | github_2023 | others | 670 | rivenmedia | iPromKnight | @@ -34,6 +33,7 @@ alembic = "^1.13.2"
psycopg2-binary = "^2.9.9"
apprise = "^1.8.1"
subliminal = "^2.2.1"
+rank-torrent-name = {path = "/home/spoked/projects/rtn"} | cough cough 😛 |
riven | github_2023 | others | 447 | rivenmedia | dreulavelle | @@ -82,5 +82,12 @@ jobs:
run: pnpm install
working-directory: ./frontend
- - run: pnpm lint
- working-directory: ./frontend
+ - uses: dorny/paths-filter@v2 | what is this? @Gaisberg |
riven | github_2023 | python | 575 | rivenmedia | dreulavelle | @@ -27,6 +27,13 @@ def process_event(existing_item: MediaItem | None, emitted_by: Service, item: Me
if existing_item and not TraktIndexer.should_submit(existing_item):
return no_further_processing
return None, next_service, [item]
+
+ elif item.state == States.Indexed and len(item.... | this section needs to go |
riven | github_2023 | python | 575 | rivenmedia | dreulavelle | @@ -95,13 +95,6 @@ def _make_request(
if retry_if_failed:
session.mount("http://", _adapter)
session.mount("https://", _adapter)
- headers = {
| what made you get rid of this? Just curious |
riven | github_2023 | python | 590 | rivenmedia | github-advanced-security[bot] | @@ -134,4 +135,23 @@
payload["incomplete_retries"] = incomplete_retries
payload["states"] = states
- return {"success": True, "data": payload}
+ return {"success": True, "data": payload}
+
+@router.get("/logs")
+async def get_logs():
+ log_file_path = None
+ for handler i... | ## Information exposure through an exception
[Stack trace information](1) flows to this location and may be exposed to an external user.
[Show more details](https://github.com/rivenmedia/riven/security/code-scanning/2) |
riven | github_2023 | python | 621 | rivenmedia | Gaisberg | @@ -44,6 +42,7 @@ class Program(threading.Thread):
def __init__(self):
super().__init__(name="Riven")
self.initialized = False
+ self.running = False | Whats this? |
riven | github_2023 | others | 621 | rivenmedia | Gaisberg | @@ -33,6 +33,7 @@ alembic = "^1.13.2"
psycopg2-binary = "^2.9.9"
apprise = "^1.8.1"
subliminal = "^2.2.1"
+websocket-client = "^1.8.0" | Whats this? |
riven | github_2023 | python | 364 | rivenmedia | dreulavelle | @@ -19,32 +21,52 @@ def __init__(self, hash_cache):
self.settings = settings_manager.settings.scraping
self.hash_cache = hash_cache
self.services = {
- Annatar: Annatar(self.hash_cache),
- Torrentio: Torrentio(self.hash_cache),
- Knightcrawler: Knightcraw... | use the class as the key |
riven | github_2023 | python | 507 | rivenmedia | dreulavelle | @@ -63,7 +63,11 @@ def validate(self) -> bool:
try:
response = ping(f"{RD_BASE_URL}/user", additional_headers=self.auth_headers, proxies=self.proxy)
if response.ok:
- user_info = response.json()
+ try:
+ user_info = response.json()
+ ... | do you have an example of when this happens? |
riven | github_2023 | python | 507 | rivenmedia | Gaisberg | @@ -63,7 +63,11 @@ def validate(self) -> bool:
try:
response = ping(f"{RD_BASE_URL}/user", additional_headers=self.auth_headers, proxies=self.proxy)
if response.ok:
- user_info = response.json()
+ try: | Please remove this try and except the exception in the existing try except |
riven | github_2023 | others | 556 | rivenmedia | dreulavelle | @@ -0,0 +1,61 @@
+---
+services:
+ riven-frontend:
+ image: spoked/riven-frontend:latest
+ container_name: riven-frontend
+ restart: unless-stopped
+ ports:
+ - "3000:3000"
+ tty: true
+ environment:
+ - PUID=1000
+ - PGID=1000
+ - ORIGIN=http://localhost:3000
+ - BACKEND_URL... | there doesn't need to be 3 composes for this. Just add a comment at the end of the line for `RIVEN_DATABASE_HOST` with the example of the sqlite database. Which should be set to `sqlite:////riven/data/media.db` |
riven | github_2023 | python | 541 | rivenmedia | dreulavelle | @@ -237,25 +237,36 @@ def _schedule_services(self) -> None:
coalesce=False,
)
logger.log("PROGRAM", f"Scheduled {service_cls.__name__} to run every {update_interval} seconds.")
-
+ def _id_in_queue(self, id):
+ for i in self.queued_items:
+ if i._id == id:... | you have a bad habit of not putting newlines between functions lol |
riven | github_2023 | python | 512 | rivenmedia | dreulavelle | @@ -16,16 +16,19 @@
from RTN.parser import parse
from RTN.patterns import extract_episodes
from utils.logger import logger
-from utils.request import get, ping, post
+from utils.request import get, ping, post, RateLimiter
WANTED_FORMATS = {".mkv", ".mp4", ".avi"}
RD_BASE_URL = "https://api.real-debrid.com/rest/1... | I might be being picky here, but we should add a comment for the unit of measurement here |
riven | github_2023 | python | 466 | rivenmedia | dreulavelle | @@ -65,59 +73,55 @@ def should_submit(item: MediaItem) -> bool:
interval = timedelta(seconds=settings.update_interval)
return datetime.now() - item.indexed_at > interval
except Exception:
- logger.error(f"Failed to parse date: {item.indexed_at} with format: {interval}")
... | why get rid of validation? |
riven | github_2023 | python | 466 | rivenmedia | dreulavelle | @@ -116,6 +118,18 @@ def _determine_state(self):
return States.Requested
return States.Unknown
+ def clean_title(self, title: Optional[str]) -> Optional[str]: | This is not needed as metadata we get is from Trakt. We dont need to sanitize it |
riven | github_2023 | python | 466 | rivenmedia | dreulavelle | @@ -163,19 +170,21 @@ def _search_movie_indexer(self, item: MediaItem, indexer: JackettIndexer) -> Lis
"cat": "2000",
"q": item.title,
}
- if indexer.movie_search_capabilities and "year" in indexer.movie_search_capabilities:
- if hasattr(item.aired_at, "year") an... | I'm super reluctant to use year queries with show scraping as its normal for shows to not have years in their torrent names.. Movies usually do, but its fairly uncommon for shows to have a year in the title |
riven | github_2023 | python | 475 | rivenmedia | dreulavelle | @@ -82,7 +82,7 @@ def scrape(self, item: MediaItem) -> Dict[str, str]:
def api_scrape(self, item: MediaItem) -> tuple[Dict[str, str], int]:
"""Wrapper for `Zilean` scrape method"""
- query_text = item.title if isinstance(item, (Movie, Season, Episode)) else ""
+ query_text = item.get_top_t... | this will get tidied up a little more as I'm moving some of the generic stremio stuff out of the scrapers and into the scraper init instead. I'll accept it for now, but it will change 😅 |
riven | github_2023 | python | 418 | rivenmedia | dreulavelle | @@ -29,6 +29,8 @@ def __setattr__(self, name, value):
class DebridModel(Observable):
enabled: bool = False
api_key: str = ""
+ proxy_enabled: bool = False
+ proxy_url: str = "" | as far as I'm aware, there is no proxy? RD goes down all the time it seems, but it comes back. It's working for me atm? |
riven | github_2023 | python | 406 | rivenmedia | dreulavelle | @@ -77,17 +77,27 @@ def _add_seasons_to_show(show: Show, imdb_id: str):
def _map_item_from_data(data, item_type: str, show_genres: List[str] = None) -> Optional[MediaItem]:
- """Map trakt.tv API data to MediaItemContainer."""
+ """Map trakt.tv API data to MediaItemContainer.
+
+ If the year is f... | I agree that this function needs improvement, but this isn't the way to do it |
riven | github_2023 | python | 403 | rivenmedia | Gaisberg | @@ -62,7 +64,7 @@ def check_update_interval(cls, v):
class PlexLibraryModel(Updatable):
update_interval: int = 120
token: str = ""
- url: str = "http://localhost:32400"
+ url: str = "http://plex:32400" if is_elfhosted else "http://localhost:32400" | Instead of having these scattered around should they be gathered into one method that changes the variables on startup or an override of the models. This way it wont get so clustered |
riven | github_2023 | python | 403 | rivenmedia | dreulavelle | @@ -155,19 +157,19 @@ class OrionoidConfig(Observable):
class JackettConfig(Observable):
enabled: bool = False
- url: str = "http://localhost:9117"
+ url: str = "http://jackett:9117" if is_elfhosted else "http://localhost:9117"
api_key: str = ""
class ProwlarrConfig(Observable):
enabled: bo... | I'm still unsure about these.. think a new private repo would be best? |
riven | github_2023 | python | 243 | rivenmedia | Gaisberg | @@ -0,0 +1,70 @@
+from copy import deepcopy
+from datetime import datetime
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+from program.media import Show, Season, Episode, Movie
+from program.state_transition import process_event
+from program.libaries import SymlinkLibrary
+from program.se... | I would stick to given, when, then format for writing tests. It gives the test structure and actual tells the reader whats going on. Now all im seeing is a bunch of asserts against a test fixture. |
riven | github_2023 | python | 243 | rivenmedia | Gaisberg | @@ -0,0 +1,70 @@
+from copy import deepcopy
+from datetime import datetime
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+from program.media import Show, Season, Episode, Movie
+from program.state_transition import process_event
+from program.libaries import SymlinkLibrary
+from program.se... | What are we really testing here? Split this up and rename the tests to something more meaningful. |
riven | github_2023 | python | 349 | rivenmedia | dreulavelle | @@ -86,59 +103,204 @@ def scrape(self, item: MediaItem) -> MediaItem:
def api_scrape(self, item: MediaItem) -> tuple[Dict[str, Torrent], int]:
"""Wrapper for `Jackett` scrape method"""
- with self.minute_limiter:
- query = ""
+
+ indexers = self._get_indexers()
| what happens if this is empty? |
riven | github_2023 | others | 348 | rivenmedia | AyushSehrawat | @@ -25,6 +28,17 @@
}
export let actionUrl: string = '?/default';
+
+ const downloadersEnabledFieldData: FormGroupCheckboxFieldType[] = [
+ {
+ field_name: 'realdebrid_enabled',
+ label_name: 'Real Debrid'
+ },
+ {
+ field_name: 'torbox_enabled',
+ label_name: 'Torbox'
+ },
+ ];
| Fixed |
riven | github_2023 | others | 348 | rivenmedia | AyushSehrawat | @@ -11,6 +12,8 @@
import type { SuperValidated } from 'sveltekit-superforms';
import FormTextField from './components/form-text-field.svelte';
import FormCheckboxField from './components/form-checkbox-field.svelte';
+ import FormGroupCheckboxField from './components/form-group-checkbox-field.svelte';
+ import... | Fixed |
riven | github_2023 | others | 348 | rivenmedia | AyushSehrawat | @@ -1,4 +1,5 @@
<script lang="ts">
+ import { slide } from 'svelte/transition';
| Fixed |
riven | github_2023 | others | 348 | rivenmedia | AyushSehrawat | @@ -68,15 +82,38 @@
errors={$errors.library_path}
/>
- <FormTextField
+ <FormGroupCheckboxField
{config}
- fieldName="realdebrid_api_key"
- isProtected={true}
- fieldValue={$form.realdebrid_api_key}
- labelName="Real Debrid API Key"
- errors={$errors.realdebrid_api_key}
+ fieldTitl... | already fixed |
riven | github_2023 | python | 256 | rivenmedia | Gaisberg | @@ -1,85 +1,94 @@
import os
import re
+from pathlib import Path
from typing import Generator
-from utils.logger import logger
+from program.media.item import Episode, MediaItem, Movie, Season, Show
from program.settings.manager import settings_manager
-from program.media.item import (
- MediaItem,
- Movie,
... | Why not? |
riven | github_2023 | python | 256 | rivenmedia | Gaisberg | @@ -1,85 +1,94 @@
import os
import re
+from pathlib import Path
from typing import Generator
-from utils.logger import logger
+from program.media.item import Episode, MediaItem, Movie, Season, Show
from program.settings.manager import settings_manager
-from program.media.item import (
- MediaItem,
- Movie,
... | "Can't extract **movie** imdb_id at path %s" |
riven | github_2023 | python | 256 | rivenmedia | Gaisberg | @@ -1,85 +1,94 @@
import os
import re
+from pathlib import Path
from typing import Generator
-from utils.logger import logger
+from program.media.item import Episode, MediaItem, Movie, Season, Show
from program.settings.manager import settings_manager
-from program.media.item import (
- MediaItem,
- Movie,
... | season number |
riven | github_2023 | python | 256 | rivenmedia | Gaisberg | @@ -32,6 +37,7 @@ def validate(self) -> bool:
self.api_key = self.settings.api_key
try:
url = f"{self.settings.url}/api/v2.0/indexers/!status:failing,test:passed/results/torznab?apikey={self.api_key}&cat=2000&t=movie&q=test"
+ self.ranking_model = models.get(... | Will this keep the reference to the settings_manager object? ie. if you change settings on the fly what happens? |
riven | github_2023 | others | 256 | rivenmedia | Gaisberg | @@ -1 +1 @@
-0.4.6
\ No newline at end of file
+0.4.7 | this PR deservers a minor increase |
riven | github_2023 | python | 256 | rivenmedia | Gaisberg | @@ -0,0 +1,303 @@
+import re
+from typing import Dict, List
+
+import PTN
+from program.versions.rank_models import DefaultRanking
+from program.versions.ranks import (
+ CUSTOM_RANKS,
+ SETTINGS,
+ BaseRankingModel,
+ calculate_ranking,
+)
+from pydantic import BaseModel, Field
+from thefuzz im... | A better name would be set |
riven | github_2023 | python | 256 | rivenmedia | Gaisberg | @@ -1,68 +1,151 @@
import pytest
-from utils.parser import Parser
-
-
-@pytest.fixture
-def parser():
- return Parser()
-
-
-# Test parser
-def test_fetch_with_movie(parser):
- # Use mocked movie item in parser test
- parsed_data = parser.parse(item=None, string="Inception 2010 1080p BluRay x264")
- assert... | If this is the case then parse_episodes is broken, please fix it. |
riven | github_2023 | typescript | 256 | rivenmedia | Gaisberg | @@ -2,7 +2,7 @@ import { type SuperValidated } from 'sveltekit-superforms';
import { z } from 'zod';
/**
- * Sets the settings in memory in the backend.
+ * Sets the settings in memory in the
| Whats happened here? |
riven | github_2023 | others | 256 | rivenmedia | AyushSehrawat | @@ -168,6 +169,16 @@ Pull requests are welcome. For major changes, please open an issue first to disc
We use Black for backend and Prettier for frontend. Please make sure to run the formatters before submitting a pull request. Also use CRLF line endings unless it is a shell script or something that requires LF line ... | Probably link https://python-poetry.org/docs/#installation too |
riven | github_2023 | python | 242 | rivenmedia | dreulavelle | @@ -19,7 +19,21 @@ def __init__(self):
self.last_fetch_times = {}
self.settings = settings_manager.settings.symlink
self.initialized = True
-
+ self.initialized = self.validate()
+ if not self.initialized:
+ logger.error("SymlinkLibrary initialization failed due to in... | You probably noticed by now, but we dont technically use the anime dir's just yet. I added a `is_anime` attr that we can use to populate those 2 dirs though.
Just gotta add sorting to this module to handle |
riven | github_2023 | python | 242 | rivenmedia | dreulavelle | @@ -19,7 +19,21 @@ def __init__(self):
self.last_fetch_times = {}
self.settings = settings_manager.settings.symlink
self.initialized = True
-
+ self.initialized = self.validate()
+ if not self.initialized:
+ logger.error("SymlinkLibrary initialization failed due to in... | heh.. lol nice save |
riven | github_2023 | python | 239 | rivenmedia | Gaisberg | @@ -63,8 +63,8 @@ def run(self, item):
if item is None or not self.initialized:
return
try:
- self._scrape_item(item)
- except RateLimitExceeded:
+ yield self._scrape_item(item)
+ except RateLimitExceeded as e:
| Declared variable is never used |
riven | github_2023 | python | 224 | rivenmedia | Gaisberg | @@ -38,16 +38,11 @@ async def get_rd_user():
@router.get("/services")
async def get_services(request: Request):
data = {}
- if hasattr(request.app.program, "core_manager"):
- for service in request.app.program.core_manager.services:
+ if hasattr(request.app.program, "services"):
+ for s... | hasattr would make more sense here |
riven | github_2023 | python | 224 | rivenmedia | Gaisberg | @@ -24,47 +46,209 @@ def __init__(self, args):
self.running = False
self.startup_args = args
logger.configure_logger(
- debug=settings_manager.settings.debug, log=settings_manager.settings.log
+ debug=settings_manager.settings.debug,
+ log=settings_manag... | This seems redundant;
future = self.executor.submit(func, item) if item is not None else self.executor.submit(func) |
riven | github_2023 | python | 224 | rivenmedia | Gaisberg | @@ -24,47 +46,209 @@ def __init__(self, args):
self.running = False
self.startup_args = args
logger.configure_logger(
- debug=settings_manager.settings.debug, log=settings_manager.settings.log
+ debug=settings_manager.settings.debug,
+ log=settings_manag... | im not sure what i think about this, should metadata have an attribute or something? We might need to update existing items that are not fully released etc. |
riven | github_2023 | python | 224 | rivenmedia | Gaisberg | @@ -24,47 +46,209 @@ def __init__(self, args):
self.running = False
self.startup_args = args
logger.configure_logger(
- debug=settings_manager.settings.debug, log=settings_manager.settings.log
+ debug=settings_manager.settings.debug,
+ log=settings_manag... | As we are still relying on plex I guess we should handle the plex updating part here? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.