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 | 977 | rivenmedia | coderabbitai[bot] | @@ -1,24 +1,205 @@
+from dataclasses import dataclass
+from datetime import datetime
import os
import shutil
from threading import Event
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, List, Optional, Union
from loguru import logger
-from sqlalchemy import delete, exists, insert, ins... | _:hammer_and_wrench: Refactor suggestion_
**Fix None comparisons as per static analysis.**
The static analyzer correctly identified improper None comparisons. These should use `is` instead of `==` for better readability and performance.
```diff
if filter.has_file is not None:
- if filter.has_file:
- stmt ... |
riven | github_2023 | python | 977 | rivenmedia | coderabbitai[bot] | @@ -1,24 +1,205 @@
+from dataclasses import dataclass
+from datetime import datetime
import os
import shutil
from threading import Event
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, List, Optional, Union
from loguru import logger
-from sqlalchemy import delete, exists, insert, ins... | _:warning: Potential issue_
**Fix reversed logic in file and folder existence checks.**
The conditions for `has_file` and `has_folder` are reversed from what their names suggest:
- When `has_file` is True, it checks for `file is None`
- When `has_folder` is True, it checks for `folder is not None`
Apply this diff to... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -0,0 +1,39 @@
+"""add_pause_functionality
+
+Revision ID: [generate a new revision ID] | _:warning: Potential issue_
**Replace placeholder revision ID with an actual unique identifier.**
The revision ID needs to be replaced with a valid unique identifier. Alembic typically uses a UUID-like string for this purpose.
Apply this change:
```diff
-Revision ID: [generate a new revision ID]
+Revision ID: c99239... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -0,0 +1,39 @@
+"""add_pause_functionality
+
+Revision ID: [generate a new revision ID]
+Revises: c99709e3648f
+Create Date: 2024-11-14 16:00:00.000000
+
+"""
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = '[generat... | _:warning: Potential issue_
**Improve column definitions for data consistency.**
The `is_paused` column should not be nullable since it has a default value. Additionally, consider adding a server_default to handle existing rows.
Apply these changes:
```diff
- sa.Column('is_paused', sa.Boolean(), nullable=True... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -77,6 +77,10 @@ class MediaItem(db.Model):
last_state: Mapped[Optional[States]] = mapped_column(sqlalchemy.Enum(States), default=States.Unknown)
subtitles: Mapped[list[Subtitle]] = relationship(Subtitle, back_populates="parent", lazy="selectin", cascade="all, delete-orphan")
+ # Pause related fields
+... | _:warning: Potential issue_
**Add index for `is_paused` column**
The PR objectives mention an index on the `is_paused` column, but it's missing in the code. Since this column will be used for filtering paused items, an index should be added to improve query performance.
Add the index definition to `__table_args__`:
... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -407,6 +413,24 @@
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
+ logger.debug(f"Pausing {self.id}")
+ self.is_paused = True
+ self.paused_at = datetime.now()
+ logger.info(f"{self.log_st... | _:warning: Potential issue_
**Improve transaction handling and logging consistency**
Several issues need to be addressed in the pause/unpause methods:
1. Inconsistent transaction handling: `pause()` flushes but `unpause()` doesn't
2. Missing transaction management: changes could be lost if an error occurs
3. Inconsi... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,136 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{ids}/pause", response_model=PauseResponse, operation_id="pause_i... | _:hammer_and_wrench: Refactor suggestion_
**Avoid catching broad exceptions and handle specific exceptions instead**
Catching the base `Exception` class can mask other unexpected errors and make debugging more difficult. It's better to catch specific exceptions that you anticipate might occur.
Apply this diff to c... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,136 @@
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
+ }
+
+@router.post("/{ids}/pause", response_model=PauseResponse, operation_id="pause_items")
+async def pause_items(request: Request, ids: str = None, db: Session = Depends(get_db)):
+ """Paus... | _:hammer_and_wrench: Refactor suggestion_
**Add exception handling for database commit operations**
The `db.commit()` calls lack exception handling. If a commit fails, it may leave the session in an inconsistent state. It's important to handle exceptions and rollback transactions if necessary.
Consider wrapping th... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,136 @@
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
+ }
+
+@router.post("/{ids}/pause", response_model=PauseResponse, operation_id="pause_items")
+async def pause_items(request: Request, ids: str = None, db: Session = Depends(get_db)):
+ """Paus... | _:warning: Potential issue_
**Use SQLAlchemy queries instead of raw SQL to prevent SQL injection**
Concatenating user input directly into SQL statements can lead to SQL injection vulnerabilities. Even though there's input validation, it's safer and more maintainable to use SQLAlchemy's query builder methods.
Apply... |
riven | github_2023 | python | 886 | rivenmedia | Gaisberg | @@ -407,6 +413,24 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
+ logger.debug(f"Pausing {self.id}")
+ self.is_paused = True
+ self.paused_at = datetime.now()
+ logger.i... | Clean up the log string, the latter attribute logs can be debug level if needed |
riven | github_2023 | python | 886 | rivenmedia | Gaisberg | @@ -17,45 +17,62 @@ def process_event(emitted_by: Service, existing_item: MediaItem | None = None, c
no_further_processing: ProcessedEvent = (None, [])
items_to_submit = []
-#TODO - Reindex non-released badly indexed items here
+ # Skip processing if item is paused | This (lines: 20-25) is the only state_transition modification needed, remove the rest. |
riven | github_2023 | python | 886 | rivenmedia | Gaisberg | @@ -12,18 +12,58 @@
from program.db import db_functions
from program.db.db import db, get_db
-from program.media.item import MediaItem
+from program.media.item import MediaItem, MediaType # Import MediaType from item module
from program.media.state import States
from program.services.content import Overseerr
fr... | Thank you for seperating these! |
riven | github_2023 | python | 886 | rivenmedia | Gaisberg | @@ -432,4 +443,136 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{ids}/pause", response_model=PauseResponse, operation_id="pause_i... | use query parameters if you want to supply multiple ids, path parameters should only provide one. |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,148 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{ids}/pause", response_model=PauseResponse, operation_id="pause_i... | _:warning: Potential issue_
**Fix indentation and improve error handling.**
The try-except block has incorrect indentation and should be more specific about the exceptions it catches.
Apply this diff:
```diff
try:
- for item in items:
- item.pause() # or item.unpause()
- db.commit()
-except Except... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,148 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{ids}/pause", response_model=PauseResponse, operation_id="pause_i... | _:hammer_and_wrench: Refactor suggestion_
**Use query parameters for multiple IDs.**
The path parameter should be used for single ID operations. For multiple IDs, use query parameters instead.
Apply this diff:
```diff
-@router.post("/{ids}/pause", response_model=PauseResponse, operation_id="pause_items")
+@router.p... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,148 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{ids}/pause", response_model=PauseResponse, operation_id="pause_i... | _:warning: Potential issue_
**Add error handling and use query parameters.**
Similar to the pause endpoint, this endpoint needs proper error handling and should use query parameters for multiple IDs.
Apply this diff:
```diff
-@router.post("/{ids}/unpause", response_model=PauseResponse, operation_id="unpause_items")... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -407,6 +414,46 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
+ if self.is_paused:
+ logger.debug(f"{self.log_string} is already paused")
+ return
+
+ logge... | _:warning: Potential issue_
**Fix indentation issues in pause/unpause methods**
The methods have inconsistent indentation that needs to be fixed to match the class level.
Apply this diff to fix the indentation:
```diff
def pause(self) -> None:
"""Pause processing of this media item"""
- if self... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Improve error handling in pause operation.**
The pause operation should use specific SQLAlchemyError instead of generic Exception, similar to the unpause operation.
Apply this diff:
```diff
+from sqlalchemy.exc import SQLAlchemyError # Add at top with other imports
- ... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -407,6 +414,47 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
++ if self.is_paused:
++ logger.debug(f"{self.log_string} is already paused")
++ return
+
+ ... | _:warning: Potential issue_
**Fix indentation issues in pause/unpause methods.**
The methods have inconsistent indentation that needs to be fixed.
Apply this diff to fix the indentation:
```diff
def pause(self) -> None:
"""Pause processing of this media item"""
- if self.is_paused:
- ... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -407,6 +414,47 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
+ if self.is_paused:
+ logger.debug(f"{self.log_string} is already paused")
+ return
+
+ logg... | _:warning: Potential issue_
**Fix indentation in pause/unpause methods.**
The methods have inconsistent indentation that needs to be fixed.
Apply this diff to fix the indentation:
```diff
def pause(self) -> None:
"""Pause processing of this media item"""
- if self.is_paused:
- logg... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -407,6 +414,54 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
+
+ if self.is_paused:
+ logger.debug(f"{self.log_string} is already paused")
+ return
+
+
+ logg... | _:warning: Potential issue_
**Fix indentation in pause method.**
The method has inconsistent indentation that should be fixed.
```diff
def pause(self) -> None:
"""Pause processing of this media item"""
-
if self.is_paused:
logger.debug(f"{self.log_string} is already paused")
... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -407,6 +414,54 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
+
+ if self.is_paused:
+ logger.debug(f"{self.log_string} is already paused")
+ return
+
+
+ logg... | _:warning: Potential issue_
**Fix indentation and improve logging in unpause method.**
The method has indentation issues and inconsistent logging compared to the pause method.
```diff
def unpause(self) -> None:
- """Resume processing of this media item"""
+ """Resume processing of this media item... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -18,67 +18,10 @@ def process_event(emitted_by: Service, existing_item: MediaItem | None = None, c
no_further_processing: ProcessedEvent = (None, [])
items_to_submit = []
-#TODO - Reindex non-released badly indexed items here
- if content_item or (existing_item is not None and existing_item.last_state ... | _:warning: Potential issue_
**Fix the return statement to use no_further_processing.**
The current return statement uses uninitialized variables. Since we're not processing anything further, we should return the predefined `no_further_processing` tuple.
Apply this diff:
```diff
- return next_service, items_to_su... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -61,6 +61,10 @@ class MediaItem(db.Model):
last_state: Mapped[Optional[States]] = mapped_column(sqlalchemy.Enum(States), default=States.Unknown)
subtitles: Mapped[list[Subtitle]] = relationship(Subtitle, back_populates="parent", lazy="selectin", cascade="all, delete-orphan")
+ # Pause related fields
+... | _:warning: Potential issue_
**Add missing paused_by column.**
The PR objectives mention a `paused_by` column, but it's not implemented in the model.
Add the following column definition:
```diff
# Pause related fields
is_paused: Mapped[Optional[bool]] = mapped_column(sqlalchemy.Boolean, default=False)
... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -391,6 +398,47 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
+ if self.is_paused:
+ logger.debug(f"{self.log_string} is already paused")
+ return
+
+ logger.d... | _:hammer_and_wrench: Refactor suggestion_
**Improve pause method implementation.**
The pause method has several areas for improvement:
1. Consider adding the `paused_by` field mentioned in PR objectives
2. Remove extra blank lines for better readability
3. Consider moving session handling to a separate method
Apply ... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Use exception chaining when re-raising exceptions**
When raising an exception in an `except` block, use `from e` to maintain the original traceback information.
Apply this diff:
```diff
- raise HTTPException(status_code=500, detail="Failed to unpause items")
+ ... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Use exception chaining when re-raising exceptions**
When raising an exception inside an `except` block, use `from e` to preserve the original traceback and provide better context.
Apply this diff:
```diff
- raise HTTPException(status_code=500, detail="Failed to u... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Avoid function calls in default argument values**
Using `Depends(get_db)` in function defaults is discouraged. Obtain the database session within the function body.
Apply this diff:
```diff
-async def unpause_items(request: Request, ids: str = None, db: Session = Depend... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Avoid function calls in default argument values**
Using `Depends(get_db)` in default arguments can lead to unexpected behavior. It's better to obtain the database session inside the function.
Apply this diff:
```diff
-async def get_pause_state(request: Request, id: str,... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Avoid function calls in default argument values**
Using `Depends(get_db)` as a default argument is not recommended. Acquire the database session within the function body instead.
Apply this diff:
```diff
-async def get_all_paused(
- request: Request,
- type: Opti... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Avoid function calls in default argument values**
Using `Depends(get_db)` in function argument defaults can lead to unexpected behavior. It's recommended to obtain the database session inside the function body.
Apply this diff:
```diff
-async def pause_items(request: Re... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -0,0 +1,43 @@
+"""add_pause_functionality
+
+Revision ID: c99239e3445f
+revision: str = 'c99239e3445f'
+Revises: c99709e3648f
+Create Date: 2024-11-14 16:00:00.000000
+
+"""
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision:... | _:hammer_and_wrench: Refactor suggestion_
**Add length constraint to the `paused_by` String column.**
Unbounded string columns can lead to storage issues. Consider adding a reasonable length constraint that aligns with your user ID or username field lengths.
```diff
- sa.Column('paused_by', sa.String(), nulla... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Add error handling for database operations.**
The endpoint should handle potential database errors and use proper dependency injection.
Apply this diff:
```diff
-async def get_pause_state(request: Request, id: str, db: Session = Depends(get_db)):
+async def get_pause_stat... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Fix dependency injection and exception handling.**
Several improvements needed:
1. Move database session acquisition into the function body
2. Add exception chaining
3. Import SQLAlchemyError
Apply this diff:
```diff
+from sqlalchemy.exc import SQLAlchemyError
+
-async de... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +443,154 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+@router.post("/{id}/pause", response_model=PauseResponse, operation_id="pause_it... | _:hammer_and_wrench: Refactor suggestion_
**Add error handling and improve logging security.**
1. Add error handling for database operations
2. Avoid logging raw SQL queries as they might contain sensitive data
Apply this diff:
```diff
if type:
valid_types = [t.value for t in MediaType]
if ty... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -241,6 +248,9 @@ def to_dict(self):
"requested_by": self.requested_by,
"scraped_at": str(self.scraped_at),
"scraped_times": self.scraped_times,
+ "is_paused": self.is_paused,
+ "paused_at": str(self.paused_at) if self.paused_at else None,
+ "unp... | _:warning: Potential issue_
**Add missing paused_by field to dictionary representation.**
The paused_by field is defined in the model but not included in the to_dict() method.
Add the following line:
```diff
"is_paused": self.is_paused,
"paused_at": str(self.paused_at) if self.paused_at else None,
"un... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +434,260 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+# Pause-related endpoints (must come before generic /{id} routes)
+@router.get("... | _:hammer_and_wrench: Refactor suggestion_
**Fix dependency injection pattern**
Don't use function calls in default arguments. Move the dependency injection into the function body.
Example fix for one of the functions:
```diff
-async def get_all_paused(
- type: Optional[str] = None,
- session: Session = Depends... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -432,4 +434,260 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+# Pause-related endpoints (must come before generic /{id} routes)
+@router.get("... | _:hammer_and_wrench: Refactor suggestion_
**Reduce debug logging to prevent sensitive data exposure**
The current debug logging includes raw SQL queries and object dumps which might expose sensitive data.
```diff
- logger.debug(f"Executing query: {query}")
- logger.debug(f"Query parameters: {query.compile().pa... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -61,6 +67,12 @@ class MediaItem(db.Model):
last_state: Mapped[Optional[States]] = mapped_column(sqlalchemy.Enum(States), default=States.Unknown)
subtitles: Mapped[list[Subtitle]] = relationship(Subtitle, back_populates="parent", lazy="selectin", cascade="all, delete-orphan")
+ # Pause related fields
+... | _:hammer_and_wrench: Refactor suggestion_
**Remove duplicate index definition.**
The `is_paused` column has an index defined both at the column level (`index=True`) and in `__table_args__`. This is redundant and could cause confusion. Remove the column-level index since the table-level index provides more control and... |
riven | github_2023 | python | 886 | rivenmedia | coderabbitai[bot] | @@ -391,6 +407,49 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
+ if self.is_paused:
+ logger.debug(f"{self.log_string} is already paused")
+ return
+
+ logger.d... | _:hammer_and_wrench: Refactor suggestion_
**Improve pause method implementation.**
Several improvements needed:
1. Add paused_by parameter to track who initiated the pause
2. Add type hints to docstring
3. Remove extra blank lines
4. Make logging consistent with unpause method
```diff
- def pause(self) -> None:
+... |
riven | github_2023 | python | 886 | rivenmedia | Gaisberg | @@ -391,6 +407,49 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def pause(self) -> None:
+ """Pause processing of this media item"""
+ if self.is_paused:
+ logger.debug(f"{self.log_string} is already paused")
+ return
+
+ logger.d... | Lets add a more identifyin log string here |
riven | github_2023 | python | 886 | rivenmedia | Gaisberg | @@ -239,24 +249,26 @@ async def get_item(_: Request, id: str, use_tmdb_id: Optional[bool] = False) ->
description="Fetch media items by IMDb IDs",
operation_id="get_items_by_imdb_ids",
)
-async def get_items_by_imdb_ids(request: Request, imdb_ids: str) -> list[dict]:
- ids = imdb_ids.split(",")
- with ... | This was extended before |
riven | github_2023 | python | 886 | rivenmedia | Gaisberg | @@ -432,4 +434,260 @@ async def unblacklist_stream(_: Request, item_id: str, stream_id: int, db: Sessi
return {
"message": f"Unblacklisted stream {stream_id} for item {item_id}",
- }
\ No newline at end of file
+ }
+
+# Pause-related endpoints (must come before generic /{id} routes)
+@router.get("... | are all these outerjoins needed? |
riven | github_2023 | python | 979 | rivenmedia | coderabbitai[bot] | @@ -55,13 +55,13 @@ def get_items_from_Listrr(self, content_type, content_lists) -> list[MediaItem]
url = f"api/List/{content_type}/{list_id}/ReleaseDate/Descending/{page}"
response = self.request_handler.execute(HttpMethod.GET, url)
data = response.data
- ... | _:hammer_and_wrench: Refactor suggestion_
**Use direct attribute access with proper error handling.**
Since we're working with SimpleNamespace objects, we should use direct attribute access with proper error handling to catch potential AttributeError exceptions.
```diff
- imdb_id = getattr(item,"imDbId")
- ... |
riven | github_2023 | python | 979 | rivenmedia | coderabbitai[bot] | @@ -55,15 +55,26 @@ def get_items_from_Listrr(self, content_type, content_lists) -> list[MediaItem]
url = f"api/List/{content_type}/{list_id}/ReleaseDate/Descending/{page}"
response = self.request_handler.execute(HttpMethod.GET, url)
data = response.data
- ... | _:hammer_and_wrench: Refactor suggestion_
**Use direct attribute access instead of `getattr`.**
Using `getattr` with constant attribute values is not safer than direct attribute access. The static analysis tool also flags this as B009.
Apply this diff to use direct attribute access:
```diff
- tot... |
riven | github_2023 | python | 979 | rivenmedia | dreulavelle | @@ -55,15 +55,26 @@ def get_items_from_Listrr(self, content_type, content_lists) -> list[MediaItem]
url = f"api/List/{content_type}/{list_id}/ReleaseDate/Descending/{page}"
response = self.request_handler.execute(HttpMethod.GET, url)
data = response.data
- ... | we can remove this log message as its going to hit this quite a lot anyways by default? |
riven | github_2023 | python | 924 | rivenmedia | coderabbitai[bot] | @@ -357,7 +359,7 @@ async def manual_update_attributes(request: Request, session_id, data: Union[Con
item.reset()
item.file = data.filename
item.folder = data.filename
- item.alternative_folder = session.torrent_info["original_filename"]
+ item.alternative_fo... | _:warning: Potential issue_
**Ensure `alternative_filename` key exists in `session.torrent_info`**
At lines 362 and 382, you're accessing `session.torrent_info["alternative_filename"]`. Please verify that `alternative_filename` is a valid key in `session.torrent_info`. If this key does not exist, accessing it will ra... |
riven | github_2023 | others | 924 | rivenmedia | coderabbitai[bot] | @@ -77,15 +78,15 @@ echo "Container Initialization complete."
echo "Starting Riven (Backend)..."
if [ "$PUID" = "0" ]; then
if [ "${DEBUG}" != "" ]; then # check if DEBUG is set to a truthy value
- cd /riven/src && poetry add debugpy && poetry run python3 -m debugpy --listen 0.0.0.0:5678 main.py
+ ... | _:warning: Potential issue_
**Security: Restrict debug mode access**
Running debug mode as root and listening on all interfaces (0.0.0.0) poses security risks:
1. Root access combined with debug capabilities could be exploited
2. Exposing debug port on all interfaces makes it accessible from outside the container
Co... |
riven | github_2023 | others | 924 | rivenmedia | coderabbitai[bot] | @@ -77,15 +78,15 @@ echo "Container Initialization complete."
echo "Starting Riven (Backend)..."
if [ "$PUID" = "0" ]; then
if [ "${DEBUG}" != "" ]; then # check if DEBUG is set to a truthy value
- cd /riven/src && poetry add debugpy && poetry run python3 -m debugpy --listen 0.0.0.0:5678 main.py
+ ... | _:hammer_and_wrench: Refactor suggestion_
**Consider using absolute paths and non-root user**
Running the application as root in production is not recommended. Additionally, using relative paths with `cd` could be unreliable.
```diff
- cd /riven/src && poetry run python3 main.py --port $PORT
+ echo "Ru... |
riven | github_2023 | python | 924 | rivenmedia | coderabbitai[bot] | @@ -140,6 +153,7 @@ def _parse_results(item: MediaItem, results: Dict[str, str], log_msg: bool = Tru
torrents_dict[torrent.infohash] = Stream(torrent)
logger.log("SCRAPER", f"Kept {len(torrents_dict)} streams for {item.log_string} after processing bucket limit")
return torrents_dict
+ ... | _:warning: Potential issue_
**Fix potential undefined variable reference**
The log message references `raw_title` which might be undefined at this point since it's only available within the loop scope. This could lead to a runtime error.
```diff
- logger.debug(f"No valid torrent remains after filtering for {item.... |
riven | github_2023 | others | 924 | rivenmedia | dreulavelle | @@ -77,15 +78,15 @@ echo "Container Initialization complete."
echo "Starting Riven (Backend)..."
if [ "$PUID" = "0" ]; then
if [ "${DEBUG}" != "" ]; then # check if DEBUG is set to a truthy value
- cd /riven/src && poetry add debugpy && poetry run python3 -m debugpy --listen 0.0.0.0:5678 main.py
+ ... | same with these 2, they can be removed a well.
if you're developing then I can understand the need to change the port, in which case you can just run it with a different port with `poetry run python main.py --port xxxx` |
riven | github_2023 | python | 924 | rivenmedia | dreulavelle | @@ -290,7 +292,7 @@ def get_info_hash(magnet: str) -> str:
"message": "Started manual scraping session",
"session_id": session.id,
"torrent_id": torrent_id,
- "torrent_info": torrent_info,
+ "torrent_info": torrent_info.dict(), | I fixed the api issues in pr #915
just waiting for it to get merged |
riven | github_2023 | python | 993 | rivenmedia | coderabbitai[bot] | @@ -110,4 +109,4 @@ def signal_handler(signum, frame):
logger.exception(traceback.format_exc())
finally:
logger.critical("Server has been stopped")
- sys.exit(0)
\ No newline at end of file
+ sys.exit(0)
| _:hammer_and_wrench: Refactor suggestion_
**Remove redundant `sys.exit(0)`.**
This `sys.exit(0)` call is redundant as the program would have already exited through the `signal_handler` function. The program will never reach this point.
```diff
- sys.exit(0)
```
<!-- suggestion_start -->
<details>
<summary>... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -15,6 +16,7 @@ def bootstrap_apis():
__setup_mdblist()
__setup_overseerr()
__setup_listrr()
+ __setup_tvmaze() | _:hammer_and_wrench: Refactor suggestion_
**Add configuration validation for TVMaze setup.**
Unlike other API setups, `__setup_tvmaze()` is called unconditionally. Consider adding configuration validation for consistency with other API initializations.
Example implementation:
```diff
def bootstrap_apis():
__set... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -74,6 +74,13 @@ def run_migrations_online() -> None:
poolclass=pool.NullPool,
)
+ # Set PostgreSQL to handle case-sensitive identifiers
+ @event.listens_for(connectable, "connect")
+ def set_postgresql_case_sensitive(dbapi_connection, connection_record):
+ cursor = dbapi_connection.cu... | _:hammer_and_wrench: Refactor suggestion_
**Add error handling to the PostgreSQL event listener.**
The event listener should handle potential database errors to prevent silent failures.
Consider wrapping the cursor operations in a try-finally block:
```diff
@event.listens_for(connectable, "connect")
def set_postg... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -115,13 +128,60 @@ def _add_seasons_to_show(self, show: Show, imdb_id: str):
continue
season_item = self.api.map_item_from_data(season, "season", show.genres)
if season_item:
+ # Set season's parent to show
+ season_item.parent = show
+ ... | _:warning: Potential issue_
**Potential incorrect handling of naive `aired_at` datetimes in episodes**
Similar to the seasons, directly setting the local timezone on a naive `aired_at` datetime for episodes may lead to incorrect times if the original datetime is not in the local timezone.
**Suggested Fix: Properly... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -22,6 +23,19 @@ def __init__(self):
self.settings = settings_manager.settings.indexer
self.failed_ids = set()
self.api = di[TraktAPI]
+ self.tvmaze_api = di[TVMazeAPI]
+
+ # Get timezone by comparing local time with UTC
+ local_time = datetime.now()
+ ut... | _:warning: Potential issue_
**Incorrect method for determining local timezone**
Calculating the local timezone by subtracting UTC time from local time using hours may lead to incorrect results, especially in regions with non-integer hour offsets or during daylight saving time changes. This approach is unreliable.
... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -115,13 +128,60 @@ def _add_seasons_to_show(self, show: Show, imdb_id: str):
continue
season_item = self.api.map_item_from_data(season, "season", show.genres)
if season_item:
+ # Set season's parent to show
+ season_item.parent = show
+ ... | _:warning: Potential issue_
**Potential incorrect handling of `tvmaze_time` when assigning timezone**
Directly setting the local timezone on a naive `tvmaze_time` datetime may lead to incorrect times if the original datetime is not in the local timezone.
**Suggested Fix: Properly localize `tvmaze_time`**
Assuming... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -115,13 +128,60 @@ def _add_seasons_to_show(self, show: Show, imdb_id: str):
continue
season_item = self.api.map_item_from_data(season, "season", show.genres)
if season_item:
+ # Set season's parent to show
+ season_item.parent = show
+ ... | _:warning: Potential issue_
**Potential incorrect handling of naive `aired_at` datetimes in seasons**
Assigning `self.local_tz` to a naive `aired_at` datetime using `replace(tzinfo=...)` assumes the original datetime is in the local timezone, which may not be accurate and could lead to incorrect times. If `aired_at` ... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -115,13 +128,60 @@ def _add_seasons_to_show(self, show: Show, imdb_id: str):
continue
season_item = self.api.map_item_from_data(season, "season", show.genres)
if season_item:
+ # Set season's parent to show
+ season_item.parent = show
+ ... | _:warning: Potential issue_
**Potential incorrect handling of `trakt_time` when assigning timezone**
Assigning the local timezone to a naive `trakt_time` datetime using `replace(tzinfo=...)` may result in incorrect time values if `trakt_time` is actually in UTC or another timezone.
**Suggested Fix: Properly locali... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -0,0 +1,206 @@
+"""TVMaze API client module"""
+
+from datetime import datetime, timedelta, timezone
+from typing import Optional
+
+from loguru import logger
+from requests import Session
+
+from program.media.item import Episode, MediaItem
+from program.utils.request import (
+ BaseRequestHandler,
+ HttpMeth... | _:hammer_and_wrench: Refactor suggestion_
**Avoid Redundant API Call in `get_show_by_imdb_id`**
The method makes two API calls: one to `/lookup/shows` and then another to `/shows/{id}`. If the initial response from `/lookup/shows` contains all the necessary show information, the second API call may be unnecessary. Ve... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -0,0 +1,206 @@
+"""TVMaze API client module"""
+
+from datetime import datetime, timedelta, timezone
+from typing import Optional
+
+from loguru import logger
+from requests import Session
+
+from program.media.item import Episode, MediaItem
+from program.utils.request import (
+ BaseRequestHandler,
+ HttpMeth... | _:warning: Potential issue_
**Fix Timezone Calculation Method**
The current method of calculating the timezone offset by subtracting hours is incorrect. This approach does not account for minute offsets (e.g., UTC+05:30) or daylight saving time changes. A more reliable method is to use `datetime.now().astimezone().tz... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -58,6 +61,18 @@ def __init__(self, settings: TraktModel):
}
session.headers.update(self.headers)
self.request_handler = TraktRequestHandler(session)
+
+ # Get timezone by comparing local time with UTC
+ local_time = datetime.now()
+ utc_time = datetime.now(time... | _:hammer_and_wrench: Refactor suggestion_
_:warning: Potential issue_
**Use `tzlocal.get_localzone()` for accurate local timezone detection.**
Manually calculating the timezone offset by comparing hours can lead to incorrect timezone handling, especially across daylight saving time changes or in timezones with minut... |
riven | github_2023 | python | 923 | rivenmedia | dreulavelle | @@ -391,6 +400,9 @@ def _reset(self):
def log_string(self):
return self.title or self.id
+ def __repr__(self): | remove this, its not needed as item.log_string already does it for us |
riven | github_2023 | python | 923 | rivenmedia | dreulavelle | @@ -0,0 +1,196 @@
+"""TVMaze API client module"""
+
+from datetime import datetime, timedelta, timezone
+from typing import Optional
+
+from loguru import logger
+from requests import Session
+
+from program.media.item import Episode, MediaItem
+from program.utils.request import (
+ BaseRequestHandler,
+ HttpMeth... | instead of all the `if not item.parent.parent` stuff, you can check the type by doing `if item.type == "episode"`
doing it like it is now can cause errors to popup when an item doesn't have the nested `parent` attributes |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -210,39 +211,67 @@ def _retry_library(self) -> None:
result = session.execute(items_query)
for item_id in result.scalars():
- self.em.add_event(Event(emitted_by="RetryLibrary", item_id=item_id))
+ self.em.add_event(Event("RetryLibrary", item_id=item_id))
... | _:warning: Potential issue_
**Handle potential `NoneType` errors when accessing `parent` attributes**
When determining the `show` object, accessing `item.parent` or `item.parent.parent` without checking for `None` may raise an `AttributeError` if any parent is missing. To prevent potential runtime errors, add checks ... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -0,0 +1,167 @@
+"""TVMaze API client module"""
+
+from datetime import datetime, timedelta, timezone
+from typing import Optional
+
+from loguru import logger
+from requests import Session
+
+from program.media.item import Episode, MediaItem
+from program.utils.request import (
+ BaseRequestHandler,
+ HttpMeth... | _:hammer_and_wrench: Refactor suggestion_
**Enhance error handling for API calls**
The method should handle specific API exceptions similar to `get_show_by_imdb_id`.
```diff
def get_episode_by_number(self, show_id: int, season: int, episode: int) -> Optional[datetime]:
if not show_id or not season or not episo... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -142,8 +142,11 @@ 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) -> tuple[States, States]:
+ def store_state(self, given_state: States = None) -> tuple[States, States]... | _:hammer_and_wrench: Refactor suggestion_
**Reconsider early return in `store_state` to allow necessary state updates**
The early return in `store_state` when `self.last_state == States.Completed` prevents any further state updates. This might be problematic if you need to update the state after completion, such as i... |
riven | github_2023 | python | 923 | rivenmedia | coderabbitai[bot] | @@ -174,9 +177,18 @@ def blacklist_stream(self, stream: Stream):
@property
def is_released(self) -> bool:
"""Check if an item has been released."""
- if self.aired_at and self.aired_at <= datetime.now():
- return True
- return False
+ if not self.aired_at:
+ ... | _:warning: Potential issue_
**Properly handle naive `aired_at` datetime objects to ensure accurate timezone conversions**
Directly setting the timezone on a naive `datetime` object using `replace(tzinfo=...)` assumes that the original datetime is in the local timezone, which may not be accurate. This can lead to inco... |
riven | github_2023 | python | 915 | rivenmedia | Gaisberg | @@ -47,21 +47,37 @@ class DebridFile(BaseModel):
filesize: Optional[int] = Field(default=None)
@classmethod
- def create(cls, filename: str, filesize_bytes: int, filetype: Literal["movie", "episode"], file_id: Optional[int] = None) -> Optional["DebridFile"]:
+ def create(
+ cls,
+ filena... | get rid of this. |
riven | github_2023 | python | 915 | rivenmedia | Gaisberg | @@ -85,6 +101,15 @@ def file_ids(self) -> List[int]:
"""Get the file ids of the cached files"""
return [file.file_id for file in self.files if file.file_id is not None]
+ def to_dict(self) -> dict:
+ """Convert the TorrentContainer to a dictionary"""
+ return { | get rid of this |
riven | github_2023 | python | 915 | rivenmedia | Gaisberg | @@ -105,6 +130,9 @@ def size_mb(self) -> float:
"""Convert bytes to megabytes"""
return self.bytes / 1_000_000
+ def to_dict(self) -> dict: | get rid of this |
riven | github_2023 | python | 915 | rivenmedia | Gaisberg | @@ -290,8 +288,8 @@ def get_info_hash(magnet: str) -> str:
"message": "Started manual scraping session",
"session_id": session.id,
"torrent_id": torrent_id,
- "torrent_info": torrent_info,
- "containers": containers,
+ "torrent_info": torrent_info.to_dict(), | Use strong typing |
riven | github_2023 | python | 915 | rivenmedia | coderabbitai[bot] | @@ -278,23 +276,25 @@ def get_info_hash(magnet: str) -> str:
session = session_manager.create_session(item_id or imdb_id, info_hash)
try:
- torrent_id = downloader.add_torrent(info_hash)
- torrent_info = downloader.get_torrent_info(torrent_id)
- containers = downloader.get_instant_avail... | _:warning: Potential issue_
**Use exception chaining to preserve traceback**
When re-raising an exception within an `except` block, use exception chaining to maintain the original traceback information.
Apply this fix:
```diff
- raise HTTPException(status_code=500, detail=str(e))
+ raise HTTPException(status_code... |
riven | github_2023 | python | 915 | rivenmedia | coderabbitai[bot] | @@ -357,8 +357,8 @@ async def manual_update_attributes(request: Request, session_id, data: Union[Con
item.reset()
item.file = data.filename
item.folder = data.filename
- item.alternative_folder = session.torrent_info["original_filename"]
- item.active_stream ... | _:warning: Potential issue_
**Ensure `session.torrent_info` is not `None` before accessing attributes**
Accessing `session.torrent_info.alternative_filename` assumes that `session.torrent_info` is not `None`. Add a check to prevent potential `AttributeError`.
Apply this fix:
```diff
+ if session.torrent_info:
... |
riven | github_2023 | python | 915 | rivenmedia | coderabbitai[bot] | @@ -377,8 +377,8 @@ async def manual_update_attributes(request: Request, session_id, data: Union[Con
item_episode.reset()
item_episode.file = episode_data.filename
item_episode.folder = episode_data.filename
- item_episode... | _:warning: Potential issue_
**Add null check for `session.torrent_info` before accessing**
Same as previous comment, ensure `session.torrent_info` is not `None` when accessing its attributes in the loop for episodes.
Apply this fix:
```diff
+ if session.torrent_info:
item_episode.alternative_folder = session.... |
riven | github_2023 | python | 926 | rivenmedia | coderabbitai[bot] | @@ -107,7 +107,10 @@ def run(self, item: Union[Movie, Show, Season, Episode]):
def _calculate_next_attempt(self, item: Union[Movie, Show, Season, Episode]) -> datetime:
base_delay = timedelta(seconds=5)
- next_attempt_delay = base_delay * (2 ** item.symlinked_times)
+ if item.symlinked... | _:hammer_and_wrench: Refactor suggestion_
**Consider a more consistent retry strategy**
The current implementation switches between exponential backoff and fixed delay in a way that might be confusing:
- Attempts 1-4: Exponential backoff (10s, 20s, 40s, 80s)
- Attempt 5: Fixed 100s
- Attempt 6: Back to exponential (3... |
riven | github_2023 | python | 926 | rivenmedia | coderabbitai[bot] | @@ -105,9 +105,10 @@ def run(self, item: Union[Movie, Show, Season, Episode]):
logger.error(f"Exception thrown when creating symlink for {item.log_string}: {e}")
yield item
- def _calculate_next_attempt(self, item: Union[Movie, Show, Season, Episode]) -> datetime:
+ def _calculate_next_... | _:warning: Potential issue_
**Fix indentation**
The method has incorrect indentation which could cause syntax errors.
Apply this fix:
```diff
- def _calculate_next_attempt(self, item: Union[Movie, Show, Season, Episode]) -> datetime:
+ def _calculate_next_attempt(self, item: Union[Movie, Show, Season, Episode]... |
riven | github_2023 | python | 926 | rivenmedia | Gaisberg | @@ -107,7 +107,8 @@ def run(self, item: Union[Movie, Show, Season, Episode]):
def _calculate_next_attempt(self, item: Union[Movie, Show, Season, Episode]) -> datetime:
base_delay = timedelta(seconds=5)
- next_attempt_delay = base_delay * (2 ** item.symlinked_times)
+ delay_seconds = mi... | I don't like this change, if symlinks times == 1,
min(100, 5 * 1), remove the the changes to the calculation and the 6th attempt will be 5 * 2^6. If five minutes is too long we could modify the calculation to be base (5) * 2^symlinktimes /2 |
riven | github_2023 | python | 932 | rivenmedia | dreulavelle | @@ -57,39 +60,36 @@ def validate(self) -> bool:
logger.error("Mediafusion ratelimit must be a valid boolean.")
return False
- if self.app_settings.downloaders.real_debrid.enabled:
- self.api_key = self.app_settings.downloaders.real_debrid.api_key
- self.downloade... | @mhdzumair what is live search streams? |
riven | github_2023 | python | 932 | rivenmedia | dreulavelle | @@ -134,25 +138,37 @@ def scrape(self, item: MediaItem) -> tuple[Dict[str, str], int]:
if identifier:
url += identifier
- response = self.request_handler.execute(HttpMethod.GET, f"{url}.json", timeout=self.timeout)
+ response = self.request_handler.execute(
+ HttpMethod.... | hmm..
In previous updates I've been pretty back and forth on this one.. Do we want the torrent or do we want the file in these scenarios.. We would prefer the torrent I think because it would have more episodes that might be needed from that same torrent. |
riven | github_2023 | python | 887 | rivenmedia | coderabbitai[bot] | @@ -0,0 +1,33 @@
+from datetime import datetime, timedelta
+import sched
+import threading
+import time
+
+from program.media.item import MediaItem
+
+
+class _HiddenScheduler:
+ def __init__(self, program):
+ self.program = program
+ scheduler = sched.scheduler(time.time, time.sleep)
+ #next_ti... | _:hammer_and_wrench: Refactor suggestion_
**Add type hints and error handling**
The initialization lacks type hints and error handling. Consider adding:
1. Type hints for better code maintainability
2. Error handling for scheduler operations
3. A method to cleanly stop the scheduler
```diff
class _HiddenScheduler:
... |
riven | github_2023 | python | 887 | rivenmedia | coderabbitai[bot] | @@ -0,0 +1,89 @@
+from datetime import datetime, timedelta
+import sched
+import threading
+import time
+
+from program.media.item import MediaItem
+from program.utils.logging import logger
+
+
+from typing import Dict, List, Optional
+from dataclasses import dataclass
+
+@dataclass
+class SpecialEvent:
+ imdb_ids: ... | _:hammer_and_wrench: Refactor suggestion_
**Add exception handling to prevent silent thread failures**
The `_add_items` method runs in a separate thread but lacks exception handling. If an exception occurs, the thread may terminate silently, making debugging difficult.
Consider adding a try-except block to catch a... |
riven | github_2023 | python | 887 | rivenmedia | coderabbitai[bot] | @@ -0,0 +1,89 @@
+from datetime import datetime, timedelta
+import sched
+import threading
+import time
+
+from program.media.item import MediaItem
+from program.utils.logging import logger
+
+
+from typing import Dict, List, Optional
+from dataclasses import dataclass
+
+@dataclass
+class SpecialEvent:
+ imdb_ids: ... | _:warning: Potential issue_
**Ensure events are rescheduled after execution for recurring events**
Currently, each special event is scheduled to run only once. After the event is triggered, it is not rescheduled for future occurrences (e.g., the next year). This means that recurring events will not be automatically h... |
riven | github_2023 | python | 922 | rivenmedia | coderabbitai[bot] | @@ -5,37 +5,42 @@
from program.services.downloaders import alldebrid
from program.services.downloaders.alldebrid import (
AllDebridDownloader,
- add_torrent,
- get_instant_availability,
- get_status,
- get_torrents,
+ AllDebridRequestHandler,
+)
+from program.services.downloaders.models import (
+... | _:hammer_and_wrench: Refactor suggestion_
**Use `unittest.mock.patch` instead of monkey-patching methods**
Directly monkey-patching `AllDebridRequestHandler.execute` can lead to unexpected side effects, especially in parallel test runs. Using `unittest.mock.patch` is a safer and more maintainable approach.
Here's ... |
riven | github_2023 | python | 922 | rivenmedia | coderabbitai[bot] | @@ -46,91 +51,51 @@ def get(url, **params):
yield downloader
# tear down mock
- alldebrid.get = get
-
-
-## Downloader tests
-def test_process_hashes(downloader):
- hashes = downloader.process_hashes(["abc"], None, [False, True])
- assert len(hashes) == 1
-
-
-def test_download_cached(downloader):
... | _:hammer_and_wrench: Refactor suggestion_
**Remove unused variable `torrent_info`**
The variable `torrent_info` is assigned but never used.
Apply this diff to remove the unused assignment:
```diff
-def test_get_torrent_info(downloader):
- torrent_info = downloader.get_torrent_info(MAGNET_ID)
+def test_get_torr... |
riven | github_2023 | python | 922 | rivenmedia | coderabbitai[bot] | @@ -46,91 +51,51 @@ def get(url, **params):
yield downloader
# tear down mock
- alldebrid.get = get
-
-
-## Downloader tests
-def test_process_hashes(downloader):
- hashes = downloader.process_hashes(["abc"], None, [False, True])
- assert len(hashes) == 1
-
-
-def test_download_cached(downloader):
... | _:warning: Potential issue_
**Fix comparison to `None` and complete the test assertion**
The comparison to `None` should use `is None`. Additionally, the test contains a TODO comment indicating that an assertion is missing to confirm that the delete operation was called.
Apply this diff to fix the comparison:
``... |
riven | github_2023 | python | 657 | rivenmedia | dreulavelle | @@ -71,12 +73,12 @@ def initialize_services(self):
Symlinker: Symlinker(),
Updater: Updater(),
Downloader: Downloader(),
- # Depends on Symlinker having created the file structure so needs
- # to run after it
- SymlinkLibrary: SymlinkLibrary(),
+ ... | With the Library, it needs the `match_existing_content` to be enabled for the app to run. Don't think that was intentional, as you wanted that to be optional right?

|
riven | github_2023 | python | 916 | rivenmedia | coderabbitai[bot] | @@ -63,7 +63,7 @@ def run(self, item: MediaItem):
download_success = True
break
else:
- raise NoMatchingFilesException(f"No valid files found for stream {stream.infohash}")
+ raise NoMatchingFilesException(f"No valid files ... | _:hammer_and_wrench: Refactor suggestion_
**Reconsider removing contextual information from error message**
The simplified error message removes valuable debugging context (stream infohash) that could help identify which stream failed processing. Consider keeping this information to aid in troubleshooting.
Additiona... |
riven | github_2023 | python | 916 | rivenmedia | coderabbitai[bot] | @@ -132,8 +132,27 @@ def get_instant_availability(self, infohash: str, item_type: str) -> Optional[To
info = self.get_torrent_info(torrent_id)
if info.status == "Ready":
files = self.get_files_and_links(torrent_id)
- processed_files = [DebridFile.create(filename... | _:hammer_and_wrench: Refactor suggestion_
**Consider enhancing the process_entry function with type hints and recursion protection.**
The nested function effectively separates file and directory processing logic, but could benefit from some improvements:
1. Add type hints for better maintainability:
```diff
-def pro... |
riven | github_2023 | python | 906 | rivenmedia | coderabbitai[bot] | @@ -37,7 +37,7 @@ def __init__(self, api_key: str):
self.trakt_api = di[TraktAPI]
def validate(self):
- return self.request_handler.execute(HttpMethod.GET, self.BASE_URL)
+ return self.request_handler.execute(HttpMethod.GET, "")
def get_items_from_Listrr(self, content_type, content_... | _:warning: Potential issue_
**Type annotation appears inconsistent with implementation**
The method is annotated to return `list[MediaItem] | list[str]`, but the implementation only returns a list of IMDb ID strings (`list[str]`). There's no code path that returns `MediaItem` objects.
Consider one of these fixes:
`... |
riven | github_2023 | python | 914 | rivenmedia | coderabbitai[bot] | @@ -98,7 +98,7 @@ def validate(self) -> bool:
self.api = RealDebridAPI(
api_key=self.settings.api_key,
- proxy_url=self.settings.proxy_url if self.settings.proxy_enabled else None
+ proxy_url=self.PROXY_URL if self.PROXY_URL else None | _:bulb: Codebase verification_
**Migration path is already handled, but documentation needs attention**
Based on the verification results:
1. The code already has proper migration support:
- `test_settings_migration.py` shows that old proxy settings are correctly migrated
- The shared downloader base class pro... |
riven | github_2023 | python | 914 | rivenmedia | coderabbitai[bot] | @@ -43,31 +43,25 @@ def __exit__(self_, exc_type, exc_value, traceback):
class RealDebridModel(Observable):
enabled: bool = False
api_key: str = ""
- proxy_enabled: bool = False
- proxy_url: str = ""
class AllDebridModel(Observable):
enabled: bool = False
api_key: str = ""
- proxy_ena... | _:hammer_and_wrench: Refactor suggestion_
**Add validation for proxy_url format**
The `proxy_url` attribute should include validation to ensure it's a valid URL format when provided.
Consider adding a validator using Pydantic's field_validator:
```diff
class DownloadersModel(Observable):
video_extensions: Lis... |
riven | github_2023 | python | 903 | rivenmedia | dreulavelle | @@ -332,3 +332,264 @@
# response_type=dict,
# )
# return response.data["data"]
+
+import time
+from datetime import datetime
+from enum import Enum
+from typing import Dict, List, Optional, Union
+
+from loguru import logger
+from pydantic import BaseModel
+from requests import Session
+
... | 😁 |
riven | github_2023 | python | 903 | rivenmedia | coderabbitai[bot] | @@ -133,10 +134,11 @@ def _parse_results(item: MediaItem, results: Dict[str, str], log_msg: bool = Tru
if torrents:
logger.log("SCRAPER", f"Found {len(torrents)} streams for {item.log_string}")
- torrents = sort_torrents(torrents)
+ torrents = sort_torrents(torrents, bucket_limit=bucket_li... | _:hammer_and_wrench: Refactor suggestion_
**Document the purpose and impact of bucket_limit.**
The bucket_limit parameter is used to filter torrents, but its purpose and impact aren't documented. Additionally, consider validating the bucket_limit value before use.
```diff
- torrents = sort_torrents(torrents, ... |
riven | github_2023 | python | 903 | rivenmedia | coderabbitai[bot] | @@ -240,7 +240,15 @@ async def start_manual_session(
magnet: str
) -> StartSessionResponse:
session_manager.cleanup_expired(background_tasks)
- info_hash = hash_from_uri(magnet).lower()
+
+ def get_info_hash(magnet: str) -> str:
+ pattern = r"[A-Fa-f0-9]{40}"
+ match = re.search(pattern, ... | _:hammer_and_wrench: Refactor suggestion_
**Enhance robustness of info hash extraction**
The current implementation has potential issues with error handling and validation. Consider these improvements:
```diff
def get_info_hash(magnet: str) -> str:
- pattern = r"[A-Fa-f0-9]{40}"
- match = re.search(pattern, m... |
riven | github_2023 | python | 903 | rivenmedia | coderabbitai[bot] | @@ -126,6 +126,7 @@ def __init__(self, session: Session | LimiterSession, response_type: ResponseTyp
self.BASE_REQUEST_PARAMS = base_params or BaseRequestParameters()
self.custom_exception = custom_exception or Exception
self.request_logging = request_logging
+ self.timeout = 15 | _:hammer_and_wrench: Refactor suggestion_
**Make timeout configurable via constructor**
The hardcoded timeout value of 15 seconds might not be suitable for all use cases. Different endpoints or services may require different timeout values.
Consider making it configurable via the constructor:
```diff
def __ini... |
riven | github_2023 | python | 903 | rivenmedia | coderabbitai[bot] | @@ -448,7 +432,7 @@ class Show(MediaItem):
}
def __init__(self, item):
- self.type = ShowMediaType.Show.value
+ self.type = "show"
self.locations = item.get("locations", [])
self.seasons: list[Season] = item.get("seasons", [])
self.propagate_attributes_to_childs() | _:warning: Potential issue_
**Fix initialization order in Show constructor.**
The propagation of attributes to child elements occurs before the parent class initialization, which could lead to undefined behavior if the parent class initialization modifies any attributes used in the propagation.
```diff
def __init_... |
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... | _:hammer_and_wrench: Refactor suggestion_
**Add error handling in `parse_filename` function**
The `parse_filename` function uses the `parse` function from `RTN`, which may raise exceptions or return incomplete data if the filename cannot be parsed.
Consider adding error handling to manage potential exceptions and ... |
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... | _:hammer_and_wrench: Refactor suggestion_
**Ensure compatibility with Python version when using `int | None`**
The type hint `int | None` requires Python 3.10 or later. If the project supports earlier Python versions, this syntax will cause a `SyntaxError`.
If the project needs to support Python versions earlier t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.