feat!: migrate to OpenAI native tool calls and fix circular deps (#fuck-gemini)
- Fix circular dependencies in agent/tools - Migrate from custom JSON to OpenAI tool calls format - Add async streaming (step_stream, complete_stream) - Simplify prompt system and remove token counting - Add 5 new API endpoints (/health, /v1/models, /api/memory/*) - Add 3 new tools (get_torrent_by_index, add_torrent_by_index, set_language) - Fix all 500 tests and add coverage config (80% threshold) - Add comprehensive docs (README, pytest guide) BREAKING: LLM interface changed, memory injection via get_memory()
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
"""Movies domain - Business logic for movie management."""
|
||||
|
||||
from .entities import Movie
|
||||
from .value_objects import MovieTitle, ReleaseYear, Quality
|
||||
from .exceptions import MovieNotFound, InvalidMovieData
|
||||
from .exceptions import InvalidMovieData, MovieNotFound
|
||||
from .services import MovieService
|
||||
from .value_objects import MovieTitle, Quality, ReleaseYear
|
||||
|
||||
__all__ = [
|
||||
"Movie",
|
||||
|
||||
+30
-28
@@ -1,86 +1,88 @@
|
||||
"""Movie domain entities."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
from ..shared.value_objects import ImdbId, FilePath, FileSize
|
||||
from .value_objects import MovieTitle, ReleaseYear, Quality
|
||||
from ..shared.value_objects import FilePath, FileSize, ImdbId
|
||||
from .value_objects import MovieTitle, Quality, ReleaseYear
|
||||
|
||||
|
||||
@dataclass
|
||||
class Movie:
|
||||
"""
|
||||
Movie entity representing a movie in the media library.
|
||||
|
||||
|
||||
This is the main aggregate root for the movies domain.
|
||||
"""
|
||||
|
||||
imdb_id: ImdbId
|
||||
title: MovieTitle
|
||||
release_year: Optional[ReleaseYear] = None
|
||||
release_year: ReleaseYear | None = None
|
||||
quality: Quality = Quality.UNKNOWN
|
||||
file_path: Optional[FilePath] = None
|
||||
file_size: Optional[FileSize] = None
|
||||
tmdb_id: Optional[int] = None
|
||||
overview: Optional[str] = None
|
||||
poster_path: Optional[str] = None
|
||||
vote_average: Optional[float] = None
|
||||
file_path: FilePath | None = None
|
||||
file_size: FileSize | None = None
|
||||
tmdb_id: int | None = None
|
||||
added_at: datetime = field(default_factory=datetime.now)
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate movie entity."""
|
||||
# Ensure ImdbId is actually an ImdbId instance
|
||||
if not isinstance(self.imdb_id, ImdbId):
|
||||
if isinstance(self.imdb_id, str):
|
||||
object.__setattr__(self, 'imdb_id', ImdbId(self.imdb_id))
|
||||
object.__setattr__(self, "imdb_id", ImdbId(self.imdb_id))
|
||||
else:
|
||||
raise ValueError(f"imdb_id must be ImdbId or str, got {type(self.imdb_id)}")
|
||||
|
||||
raise ValueError(
|
||||
f"imdb_id must be ImdbId or str, got {type(self.imdb_id)}"
|
||||
)
|
||||
|
||||
# Ensure MovieTitle is actually a MovieTitle instance
|
||||
if not isinstance(self.title, MovieTitle):
|
||||
if isinstance(self.title, str):
|
||||
object.__setattr__(self, 'title', MovieTitle(self.title))
|
||||
object.__setattr__(self, "title", MovieTitle(self.title))
|
||||
else:
|
||||
raise ValueError(f"title must be MovieTitle or str, got {type(self.title)}")
|
||||
|
||||
raise ValueError(
|
||||
f"title must be MovieTitle or str, got {type(self.title)}"
|
||||
)
|
||||
|
||||
def has_file(self) -> bool:
|
||||
"""Check if the movie has an associated file."""
|
||||
return self.file_path is not None and self.file_path.exists()
|
||||
|
||||
|
||||
def is_downloaded(self) -> bool:
|
||||
"""Check if the movie is downloaded (has a file)."""
|
||||
return self.has_file()
|
||||
|
||||
|
||||
def get_folder_name(self) -> str:
|
||||
"""
|
||||
Get the folder name for this movie.
|
||||
|
||||
|
||||
Format: "Title (Year)"
|
||||
Example: "Inception (2010)"
|
||||
"""
|
||||
if self.release_year:
|
||||
return f"{self.title.value} ({self.release_year.value})"
|
||||
return self.title.value
|
||||
|
||||
|
||||
def get_filename(self) -> str:
|
||||
"""
|
||||
Get the suggested filename for this movie.
|
||||
|
||||
|
||||
Format: "Title.Year.Quality.ext"
|
||||
Example: "Inception.2010.1080p.mkv"
|
||||
"""
|
||||
parts = [self.title.normalized()]
|
||||
|
||||
|
||||
if self.release_year:
|
||||
parts.append(str(self.release_year.value))
|
||||
|
||||
|
||||
if self.quality != Quality.UNKNOWN:
|
||||
parts.append(self.quality.value)
|
||||
|
||||
|
||||
# Extension will be added based on actual file
|
||||
return ".".join(parts)
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.title.value} ({self.release_year.value if self.release_year else 'Unknown'})"
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Movie(imdb_id={self.imdb_id}, title='{self.title.value}')"
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
"""Movie domain exceptions."""
|
||||
|
||||
from ..shared.exceptions import DomainException, NotFoundError
|
||||
|
||||
|
||||
class MovieNotFound(NotFoundError):
|
||||
"""Raised when a movie is not found."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class InvalidMovieData(DomainException):
|
||||
"""Raised when movie data is invalid."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class MovieAlreadyExists(DomainException):
|
||||
"""Raised when trying to add a movie that already exists."""
|
||||
|
||||
pass
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Movie repository interfaces (abstract)."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import List, Optional
|
||||
|
||||
from ..shared.value_objects import ImdbId
|
||||
from .entities import Movie
|
||||
@@ -9,64 +9,64 @@ from .entities import Movie
|
||||
class MovieRepository(ABC):
|
||||
"""
|
||||
Abstract repository for movie persistence.
|
||||
|
||||
|
||||
This defines the interface that infrastructure implementations must follow.
|
||||
"""
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def save(self, movie: Movie) -> None:
|
||||
"""
|
||||
Save a movie to the repository.
|
||||
|
||||
|
||||
Args:
|
||||
movie: Movie entity to save
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_by_imdb_id(self, imdb_id: ImdbId) -> Optional[Movie]:
|
||||
def find_by_imdb_id(self, imdb_id: ImdbId) -> Movie | None:
|
||||
"""
|
||||
Find a movie by its IMDb ID.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID to search for
|
||||
|
||||
|
||||
Returns:
|
||||
Movie if found, None otherwise
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_all(self) -> List[Movie]:
|
||||
def find_all(self) -> list[Movie]:
|
||||
"""
|
||||
Get all movies in the repository.
|
||||
|
||||
|
||||
Returns:
|
||||
List of all movies
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, imdb_id: ImdbId) -> bool:
|
||||
"""
|
||||
Delete a movie from the repository.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the movie to delete
|
||||
|
||||
|
||||
Returns:
|
||||
True if deleted, False if not found
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def exists(self, imdb_id: ImdbId) -> bool:
|
||||
"""
|
||||
Check if a movie exists in the repository.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID to check
|
||||
|
||||
|
||||
Returns:
|
||||
True if exists, False otherwise
|
||||
"""
|
||||
|
||||
+58
-54
@@ -1,13 +1,13 @@
|
||||
"""Movie domain services - Business logic."""
|
||||
|
||||
import logging
|
||||
from typing import Optional, List
|
||||
import re
|
||||
|
||||
from ..shared.value_objects import ImdbId, FilePath
|
||||
from ..shared.value_objects import FilePath, ImdbId
|
||||
from .entities import Movie
|
||||
from .value_objects import Quality
|
||||
from .exceptions import MovieAlreadyExists, MovieNotFound
|
||||
from .repositories import MovieRepository
|
||||
from .exceptions import MovieNotFound, MovieAlreadyExists
|
||||
from .value_objects import Quality
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -15,46 +15,48 @@ logger = logging.getLogger(__name__)
|
||||
class MovieService:
|
||||
"""
|
||||
Domain service for movie-related business logic.
|
||||
|
||||
|
||||
This service contains business rules that don't naturally fit
|
||||
within a single entity.
|
||||
"""
|
||||
|
||||
|
||||
def __init__(self, repository: MovieRepository):
|
||||
"""
|
||||
Initialize movie service.
|
||||
|
||||
|
||||
Args:
|
||||
repository: Movie repository for persistence
|
||||
"""
|
||||
self.repository = repository
|
||||
|
||||
|
||||
def add_movie(self, movie: Movie) -> None:
|
||||
"""
|
||||
Add a new movie to the library.
|
||||
|
||||
|
||||
Args:
|
||||
movie: Movie entity to add
|
||||
|
||||
|
||||
Raises:
|
||||
MovieAlreadyExists: If movie with same IMDb ID already exists
|
||||
"""
|
||||
if self.repository.exists(movie.imdb_id):
|
||||
raise MovieAlreadyExists(f"Movie with IMDb ID {movie.imdb_id} already exists")
|
||||
|
||||
raise MovieAlreadyExists(
|
||||
f"Movie with IMDb ID {movie.imdb_id} already exists"
|
||||
)
|
||||
|
||||
self.repository.save(movie)
|
||||
logger.info(f"Added movie: {movie.title.value} ({movie.imdb_id})")
|
||||
|
||||
|
||||
def get_movie(self, imdb_id: ImdbId) -> Movie:
|
||||
"""
|
||||
Get a movie by IMDb ID.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the movie
|
||||
|
||||
|
||||
Returns:
|
||||
Movie entity
|
||||
|
||||
|
||||
Raises:
|
||||
MovieNotFound: If movie not found
|
||||
"""
|
||||
@@ -62,89 +64,89 @@ class MovieService:
|
||||
if not movie:
|
||||
raise MovieNotFound(f"Movie with IMDb ID {imdb_id} not found")
|
||||
return movie
|
||||
|
||||
def get_all_movies(self) -> List[Movie]:
|
||||
|
||||
def get_all_movies(self) -> list[Movie]:
|
||||
"""
|
||||
Get all movies in the library.
|
||||
|
||||
|
||||
Returns:
|
||||
List of all movies
|
||||
"""
|
||||
return self.repository.find_all()
|
||||
|
||||
|
||||
def update_movie(self, movie: Movie) -> None:
|
||||
"""
|
||||
Update an existing movie.
|
||||
|
||||
|
||||
Args:
|
||||
movie: Movie entity with updated data
|
||||
|
||||
|
||||
Raises:
|
||||
MovieNotFound: If movie doesn't exist
|
||||
"""
|
||||
if not self.repository.exists(movie.imdb_id):
|
||||
raise MovieNotFound(f"Movie with IMDb ID {movie.imdb_id} not found")
|
||||
|
||||
|
||||
self.repository.save(movie)
|
||||
logger.info(f"Updated movie: {movie.title.value} ({movie.imdb_id})")
|
||||
|
||||
|
||||
def remove_movie(self, imdb_id: ImdbId) -> None:
|
||||
"""
|
||||
Remove a movie from the library.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the movie to remove
|
||||
|
||||
|
||||
Raises:
|
||||
MovieNotFound: If movie not found
|
||||
"""
|
||||
if not self.repository.delete(imdb_id):
|
||||
raise MovieNotFound(f"Movie with IMDb ID {imdb_id} not found")
|
||||
|
||||
|
||||
logger.info(f"Removed movie with IMDb ID: {imdb_id}")
|
||||
|
||||
|
||||
def detect_quality_from_filename(self, filename: str) -> Quality:
|
||||
"""
|
||||
Detect video quality from filename.
|
||||
|
||||
|
||||
Args:
|
||||
filename: Filename to analyze
|
||||
|
||||
|
||||
Returns:
|
||||
Detected quality or UNKNOWN
|
||||
"""
|
||||
filename_lower = filename.lower()
|
||||
|
||||
|
||||
# Check for quality indicators
|
||||
if '2160p' in filename_lower or '4k' in filename_lower:
|
||||
if "2160p" in filename_lower or "4k" in filename_lower:
|
||||
return Quality.UHD_4K
|
||||
elif '1080p' in filename_lower:
|
||||
elif "1080p" in filename_lower:
|
||||
return Quality.FULL_HD
|
||||
elif '720p' in filename_lower:
|
||||
elif "720p" in filename_lower:
|
||||
return Quality.HD
|
||||
elif '480p' in filename_lower:
|
||||
elif "480p" in filename_lower:
|
||||
return Quality.SD
|
||||
|
||||
|
||||
return Quality.UNKNOWN
|
||||
|
||||
def extract_year_from_filename(self, filename: str) -> Optional[int]:
|
||||
|
||||
def extract_year_from_filename(self, filename: str) -> int | None:
|
||||
"""
|
||||
Extract release year from filename.
|
||||
|
||||
|
||||
Args:
|
||||
filename: Filename to analyze
|
||||
|
||||
|
||||
Returns:
|
||||
Year if found, None otherwise
|
||||
"""
|
||||
# Look for 4-digit year in parentheses or standalone
|
||||
# Examples: "Movie (2010)", "Movie.2010.1080p"
|
||||
patterns = [
|
||||
r'\((\d{4})\)', # (2010)
|
||||
r'\.(\d{4})\.', # .2010.
|
||||
r'\s(\d{4})\s', # 2010
|
||||
r"\((\d{4})\)", # (2010)
|
||||
r"\.(\d{4})\.", # .2010.
|
||||
r"\s(\d{4})\s", # 2010
|
||||
]
|
||||
|
||||
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, filename)
|
||||
if match:
|
||||
@@ -152,37 +154,39 @@ class MovieService:
|
||||
# Validate year is reasonable
|
||||
if 1888 <= year <= 2100:
|
||||
return year
|
||||
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def validate_movie_file(self, file_path: FilePath) -> bool:
|
||||
"""
|
||||
Validate that a file is a valid movie file.
|
||||
|
||||
|
||||
Args:
|
||||
file_path: Path to the file
|
||||
|
||||
|
||||
Returns:
|
||||
True if valid movie file, False otherwise
|
||||
"""
|
||||
if not file_path.exists():
|
||||
logger.warning(f"File does not exist: {file_path}")
|
||||
return False
|
||||
|
||||
|
||||
if not file_path.is_file():
|
||||
logger.warning(f"Path is not a file: {file_path}")
|
||||
return False
|
||||
|
||||
|
||||
# Check file extension
|
||||
valid_extensions = {'.mkv', '.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm'}
|
||||
valid_extensions = {".mkv", ".mp4", ".avi", ".mov", ".wmv", ".flv", ".webm"}
|
||||
if file_path.value.suffix.lower() not in valid_extensions:
|
||||
logger.warning(f"Invalid file extension: {file_path.value.suffix}")
|
||||
return False
|
||||
|
||||
|
||||
# Check file size (should be at least 100 MB for a movie)
|
||||
min_size = 100 * 1024 * 1024 # 100 MB
|
||||
if file_path.value.stat().st_size < min_size:
|
||||
logger.warning(f"File too small to be a movie: {file_path.value.stat().st_size} bytes")
|
||||
logger.warning(
|
||||
f"File too small to be a movie: {file_path.value.stat().st_size} bytes"
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
return True
|
||||
|
||||
@@ -1,27 +1,28 @@
|
||||
"""Movie domain value objects."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
from ..shared.exceptions import ValidationError
|
||||
|
||||
|
||||
class Quality(Enum):
|
||||
"""Video quality levels."""
|
||||
|
||||
SD = "480p"
|
||||
HD = "720p"
|
||||
FULL_HD = "1080p"
|
||||
UHD_4K = "2160p"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
@classmethod
|
||||
def from_string(cls, quality_str: str) -> "Quality":
|
||||
"""
|
||||
Parse quality from string.
|
||||
|
||||
|
||||
Args:
|
||||
quality_str: Quality string (e.g., "1080p", "720p")
|
||||
|
||||
|
||||
Returns:
|
||||
Quality enum value
|
||||
"""
|
||||
@@ -38,38 +39,44 @@ class Quality(Enum):
|
||||
class MovieTitle:
|
||||
"""
|
||||
Value object representing a movie title.
|
||||
|
||||
|
||||
Ensures the title is valid and normalized.
|
||||
"""
|
||||
|
||||
value: str
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate movie title."""
|
||||
if not self.value:
|
||||
raise ValidationError("Movie title cannot be empty")
|
||||
|
||||
|
||||
if not isinstance(self.value, str):
|
||||
raise ValidationError(f"Movie title must be a string, got {type(self.value)}")
|
||||
|
||||
raise ValidationError(
|
||||
f"Movie title must be a string, got {type(self.value)}"
|
||||
)
|
||||
|
||||
if len(self.value) > 500:
|
||||
raise ValidationError(f"Movie title too long: {len(self.value)} characters (max 500)")
|
||||
|
||||
raise ValidationError(
|
||||
f"Movie title too long: {len(self.value)} characters (max 500)"
|
||||
)
|
||||
|
||||
def normalized(self) -> str:
|
||||
"""
|
||||
Return normalized title for file system usage.
|
||||
|
||||
|
||||
Removes special characters and replaces spaces with dots.
|
||||
"""
|
||||
import re
|
||||
|
||||
# Remove special characters except spaces, dots, and hyphens
|
||||
cleaned = re.sub(r'[^\w\s\.\-]', '', self.value)
|
||||
cleaned = re.sub(r"[^\w\s\.\-]", "", self.value)
|
||||
# Replace spaces with dots
|
||||
normalized = cleaned.replace(' ', '.')
|
||||
normalized = cleaned.replace(" ", ".")
|
||||
return normalized
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"MovieTitle('{self.value}')"
|
||||
|
||||
@@ -78,22 +85,25 @@ class MovieTitle:
|
||||
class ReleaseYear:
|
||||
"""
|
||||
Value object representing a movie release year.
|
||||
|
||||
|
||||
Validates that the year is reasonable.
|
||||
"""
|
||||
|
||||
value: int
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate release year."""
|
||||
if not isinstance(self.value, int):
|
||||
raise ValidationError(f"Release year must be an integer, got {type(self.value)}")
|
||||
|
||||
raise ValidationError(
|
||||
f"Release year must be an integer, got {type(self.value)}"
|
||||
)
|
||||
|
||||
# Movies started around 1888, and we shouldn't have movies from the future
|
||||
if self.value < 1888 or self.value > 2100:
|
||||
raise ValidationError(f"Invalid release year: {self.value}")
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self.value)
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"ReleaseYear({self.value})"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Shared kernel - Common domain concepts used across subdomains."""
|
||||
|
||||
from .exceptions import DomainException, ValidationError
|
||||
from .value_objects import ImdbId, FilePath, FileSize
|
||||
from .value_objects import FilePath, FileSize, ImdbId
|
||||
|
||||
__all__ = [
|
||||
"DomainException",
|
||||
|
||||
@@ -3,19 +3,23 @@
|
||||
|
||||
class DomainException(Exception):
|
||||
"""Base exception for all domain-related errors."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ValidationError(DomainException):
|
||||
"""Raised when domain validation fails."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class NotFoundError(DomainException):
|
||||
"""Raised when a domain entity is not found."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class AlreadyExistsError(DomainException):
|
||||
"""Raised when trying to create an entity that already exists."""
|
||||
|
||||
pass
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Shared value objects used across multiple domains."""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Union
|
||||
import re
|
||||
|
||||
from .exceptions import ValidationError
|
||||
|
||||
@@ -11,30 +11,31 @@ from .exceptions import ValidationError
|
||||
class ImdbId:
|
||||
"""
|
||||
Value object representing an IMDb ID.
|
||||
|
||||
|
||||
IMDb IDs follow the format: tt followed by 7-8 digits (e.g., tt1375666)
|
||||
"""
|
||||
|
||||
value: str
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate IMDb ID format."""
|
||||
if not self.value:
|
||||
raise ValidationError("IMDb ID cannot be empty")
|
||||
|
||||
|
||||
if not isinstance(self.value, str):
|
||||
raise ValidationError(f"IMDb ID must be a string, got {type(self.value)}")
|
||||
|
||||
|
||||
# IMDb ID format: tt + 7-8 digits
|
||||
pattern = r'^tt\d{7,8}$'
|
||||
pattern = r"^tt\d{7,8}$"
|
||||
if not re.match(pattern, self.value):
|
||||
raise ValidationError(
|
||||
f"Invalid IMDb ID format: {self.value}. "
|
||||
"Expected format: tt followed by 7-8 digits (e.g., tt1375666)"
|
||||
)
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"ImdbId('{self.value}')"
|
||||
|
||||
@@ -43,15 +44,16 @@ class ImdbId:
|
||||
class FilePath:
|
||||
"""
|
||||
Value object representing a file path with validation.
|
||||
|
||||
|
||||
Ensures the path is valid and optionally checks existence.
|
||||
"""
|
||||
|
||||
value: Path
|
||||
|
||||
def __init__(self, path: Union[str, Path]):
|
||||
|
||||
def __init__(self, path: str | Path):
|
||||
"""
|
||||
Initialize FilePath.
|
||||
|
||||
|
||||
Args:
|
||||
path: String or Path object representing the file path
|
||||
"""
|
||||
@@ -61,25 +63,25 @@ class FilePath:
|
||||
path_obj = path
|
||||
else:
|
||||
raise ValidationError(f"Path must be str or Path, got {type(path)}")
|
||||
|
||||
|
||||
# Use object.__setattr__ because dataclass is frozen
|
||||
object.__setattr__(self, 'value', path_obj)
|
||||
|
||||
object.__setattr__(self, "value", path_obj)
|
||||
|
||||
def exists(self) -> bool:
|
||||
"""Check if the path exists."""
|
||||
return self.value.exists()
|
||||
|
||||
|
||||
def is_file(self) -> bool:
|
||||
"""Check if the path is a file."""
|
||||
return self.value.is_file()
|
||||
|
||||
|
||||
def is_dir(self) -> bool:
|
||||
"""Check if the path is a directory."""
|
||||
return self.value.is_dir()
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self.value)
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"FilePath('{self.value}')"
|
||||
|
||||
@@ -88,41 +90,44 @@ class FilePath:
|
||||
class FileSize:
|
||||
"""
|
||||
Value object representing a file size in bytes.
|
||||
|
||||
|
||||
Provides human-readable formatting.
|
||||
"""
|
||||
|
||||
bytes: int
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate file size."""
|
||||
if not isinstance(self.bytes, int):
|
||||
raise ValidationError(f"File size must be an integer, got {type(self.bytes)}")
|
||||
|
||||
raise ValidationError(
|
||||
f"File size must be an integer, got {type(self.bytes)}"
|
||||
)
|
||||
|
||||
if self.bytes < 0:
|
||||
raise ValidationError(f"File size cannot be negative: {self.bytes}")
|
||||
|
||||
|
||||
def to_human_readable(self) -> str:
|
||||
"""
|
||||
Convert bytes to human-readable format.
|
||||
|
||||
|
||||
Returns:
|
||||
String like "1.5 GB", "500 MB", etc.
|
||||
"""
|
||||
units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
units = ["B", "KB", "MB", "GB", "TB"]
|
||||
size = float(self.bytes)
|
||||
unit_index = 0
|
||||
|
||||
|
||||
while size >= 1024 and unit_index < len(units) - 1:
|
||||
size /= 1024
|
||||
unit_index += 1
|
||||
|
||||
|
||||
if unit_index == 0:
|
||||
return f"{int(size)} {units[unit_index]}"
|
||||
else:
|
||||
return f"{size:.2f} {units[unit_index]}"
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.to_human_readable()
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"FileSize({self.bytes})"
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Subtitles domain - Business logic for subtitle management (shared across movies and TV shows)."""
|
||||
|
||||
from .entities import Subtitle
|
||||
from .value_objects import Language, SubtitleFormat
|
||||
from .exceptions import SubtitleNotFound
|
||||
from .services import SubtitleService
|
||||
from .value_objects import Language, SubtitleFormat
|
||||
|
||||
__all__ = [
|
||||
"Subtitle",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Subtitle domain entities."""
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from ..shared.value_objects import ImdbId, FilePath
|
||||
from dataclasses import dataclass
|
||||
|
||||
from ..shared.value_objects import FilePath, ImdbId
|
||||
from .value_objects import Language, SubtitleFormat, TimingOffset
|
||||
|
||||
|
||||
@@ -10,62 +10,65 @@ from .value_objects import Language, SubtitleFormat, TimingOffset
|
||||
class Subtitle:
|
||||
"""
|
||||
Subtitle entity representing a subtitle file.
|
||||
|
||||
|
||||
Can be associated with either a movie or a TV show episode.
|
||||
"""
|
||||
|
||||
media_imdb_id: ImdbId
|
||||
language: Language
|
||||
format: SubtitleFormat
|
||||
file_path: FilePath
|
||||
|
||||
|
||||
# Optional: for TV shows
|
||||
season_number: Optional[int] = None
|
||||
episode_number: Optional[int] = None
|
||||
|
||||
season_number: int | None = None
|
||||
episode_number: int | None = None
|
||||
|
||||
# Subtitle metadata
|
||||
timing_offset: TimingOffset = TimingOffset(0)
|
||||
hearing_impaired: bool = False
|
||||
forced: bool = False # Forced subtitles (for foreign language parts)
|
||||
|
||||
|
||||
# Source information
|
||||
source: Optional[str] = None # e.g., "OpenSubtitles", "Subscene"
|
||||
uploader: Optional[str] = None
|
||||
download_count: Optional[int] = None
|
||||
rating: Optional[float] = None
|
||||
|
||||
source: str | None = None # e.g., "OpenSubtitles", "Subscene"
|
||||
uploader: str | None = None
|
||||
download_count: int | None = None
|
||||
rating: float | None = None
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate subtitle entity."""
|
||||
# Ensure ImdbId is actually an ImdbId instance
|
||||
if not isinstance(self.media_imdb_id, ImdbId):
|
||||
if isinstance(self.media_imdb_id, str):
|
||||
object.__setattr__(self, 'media_imdb_id', ImdbId(self.media_imdb_id))
|
||||
|
||||
object.__setattr__(self, "media_imdb_id", ImdbId(self.media_imdb_id))
|
||||
|
||||
# Ensure Language is actually a Language instance
|
||||
if not isinstance(self.language, Language):
|
||||
if isinstance(self.language, str):
|
||||
object.__setattr__(self, 'language', Language.from_code(self.language))
|
||||
|
||||
object.__setattr__(self, "language", Language.from_code(self.language))
|
||||
|
||||
# Ensure SubtitleFormat is actually a SubtitleFormat instance
|
||||
if not isinstance(self.format, SubtitleFormat):
|
||||
if isinstance(self.format, str):
|
||||
object.__setattr__(self, 'format', SubtitleFormat.from_extension(self.format))
|
||||
|
||||
object.__setattr__(
|
||||
self, "format", SubtitleFormat.from_extension(self.format)
|
||||
)
|
||||
|
||||
# Ensure FilePath is actually a FilePath instance
|
||||
if not isinstance(self.file_path, FilePath):
|
||||
object.__setattr__(self, 'file_path', FilePath(self.file_path))
|
||||
|
||||
object.__setattr__(self, "file_path", FilePath(self.file_path))
|
||||
|
||||
def is_for_movie(self) -> bool:
|
||||
"""Check if this subtitle is for a movie."""
|
||||
return self.season_number is None and self.episode_number is None
|
||||
|
||||
|
||||
def is_for_episode(self) -> bool:
|
||||
"""Check if this subtitle is for a TV show episode."""
|
||||
return self.season_number is not None and self.episode_number is not None
|
||||
|
||||
|
||||
def get_filename(self) -> str:
|
||||
"""
|
||||
Get the suggested filename for this subtitle.
|
||||
|
||||
|
||||
Format for movies: "Movie.Title.{lang}.{format}"
|
||||
Format for episodes: "S01E05.{lang}.{format}"
|
||||
"""
|
||||
@@ -74,20 +77,20 @@ class Subtitle:
|
||||
else:
|
||||
# For movies, use the file path stem
|
||||
base = self.file_path.value.stem
|
||||
|
||||
|
||||
parts = [base, self.language.value]
|
||||
|
||||
|
||||
if self.hearing_impaired:
|
||||
parts.append("hi")
|
||||
if self.forced:
|
||||
parts.append("forced")
|
||||
|
||||
|
||||
return f"{'.'.join(parts)}.{self.format.value}"
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.is_for_episode():
|
||||
return f"Subtitle S{self.season_number:02d}E{self.episode_number:02d} ({self.language.value})"
|
||||
return f"Subtitle ({self.language.value})"
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Subtitle(media={self.media_imdb_id}, lang={self.language.value})"
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Subtitle domain exceptions."""
|
||||
|
||||
from ..shared.exceptions import DomainException, NotFoundError
|
||||
|
||||
|
||||
class SubtitleNotFound(NotFoundError):
|
||||
"""Raised when a subtitle is not found."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class InvalidSubtitleFormat(DomainException):
|
||||
"""Raised when subtitle format is invalid."""
|
||||
|
||||
pass
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Subtitle repository interfaces (abstract)."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import List, Optional
|
||||
|
||||
from ..shared.value_objects import ImdbId
|
||||
from .entities import Subtitle
|
||||
@@ -10,50 +10,50 @@ from .value_objects import Language
|
||||
class SubtitleRepository(ABC):
|
||||
"""
|
||||
Abstract repository for subtitle persistence.
|
||||
|
||||
|
||||
This defines the interface that infrastructure implementations must follow.
|
||||
"""
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def save(self, subtitle: Subtitle) -> None:
|
||||
"""
|
||||
Save a subtitle to the repository.
|
||||
|
||||
|
||||
Args:
|
||||
subtitle: Subtitle entity to save
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_by_media(
|
||||
self,
|
||||
media_imdb_id: ImdbId,
|
||||
language: Optional[Language] = None,
|
||||
season: Optional[int] = None,
|
||||
episode: Optional[int] = None
|
||||
) -> List[Subtitle]:
|
||||
language: Language | None = None,
|
||||
season: int | None = None,
|
||||
episode: int | None = None,
|
||||
) -> list[Subtitle]:
|
||||
"""
|
||||
Find subtitles for a media item.
|
||||
|
||||
|
||||
Args:
|
||||
media_imdb_id: IMDb ID of the media
|
||||
language: Optional language filter
|
||||
season: Optional season number (for TV shows)
|
||||
episode: Optional episode number (for TV shows)
|
||||
|
||||
|
||||
Returns:
|
||||
List of matching subtitles
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, subtitle: Subtitle) -> bool:
|
||||
"""
|
||||
Delete a subtitle from the repository.
|
||||
|
||||
|
||||
Args:
|
||||
subtitle: Subtitle to delete
|
||||
|
||||
|
||||
Returns:
|
||||
True if deleted, False if not found
|
||||
"""
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
"""Subtitle domain services - Business logic."""
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
|
||||
from ..shared.value_objects import ImdbId, FilePath
|
||||
import logging
|
||||
|
||||
from ..shared.value_objects import FilePath, ImdbId
|
||||
from .entities import Subtitle
|
||||
from .value_objects import Language, SubtitleFormat
|
||||
from .repositories import SubtitleRepository
|
||||
from .exceptions import SubtitleNotFound
|
||||
from .repositories import SubtitleRepository
|
||||
from .value_objects import Language, SubtitleFormat
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -14,42 +14,42 @@ logger = logging.getLogger(__name__)
|
||||
class SubtitleService:
|
||||
"""
|
||||
Domain service for subtitle-related business logic.
|
||||
|
||||
|
||||
This service is SHARED between movies and TV shows domains.
|
||||
Both can use this service to manage subtitles.
|
||||
"""
|
||||
|
||||
|
||||
def __init__(self, repository: SubtitleRepository):
|
||||
"""
|
||||
Initialize subtitle service.
|
||||
|
||||
|
||||
Args:
|
||||
repository: Subtitle repository for persistence
|
||||
"""
|
||||
self.repository = repository
|
||||
|
||||
|
||||
def add_subtitle(self, subtitle: Subtitle) -> None:
|
||||
"""
|
||||
Add a subtitle to the library.
|
||||
|
||||
|
||||
Args:
|
||||
subtitle: Subtitle entity to add
|
||||
"""
|
||||
self.repository.save(subtitle)
|
||||
logger.info(f"Added subtitle: {subtitle.language.value} for {subtitle.media_imdb_id}")
|
||||
|
||||
logger.info(
|
||||
f"Added subtitle: {subtitle.language.value} for {subtitle.media_imdb_id}"
|
||||
)
|
||||
|
||||
def find_subtitles_for_movie(
|
||||
self,
|
||||
imdb_id: ImdbId,
|
||||
languages: Optional[List[Language]] = None
|
||||
) -> List[Subtitle]:
|
||||
self, imdb_id: ImdbId, languages: list[Language] | None = None
|
||||
) -> list[Subtitle]:
|
||||
"""
|
||||
Find subtitles for a movie.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the movie
|
||||
languages: Optional list of languages to filter by
|
||||
|
||||
|
||||
Returns:
|
||||
List of matching subtitles
|
||||
"""
|
||||
@@ -61,23 +61,23 @@ class SubtitleService:
|
||||
return all_subtitles
|
||||
else:
|
||||
return self.repository.find_by_media(imdb_id)
|
||||
|
||||
|
||||
def find_subtitles_for_episode(
|
||||
self,
|
||||
imdb_id: ImdbId,
|
||||
season: int,
|
||||
episode: int,
|
||||
languages: Optional[List[Language]] = None
|
||||
) -> List[Subtitle]:
|
||||
languages: list[Language] | None = None,
|
||||
) -> list[Subtitle]:
|
||||
"""
|
||||
Find subtitles for a TV show episode.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the TV show
|
||||
season: Season number
|
||||
episode: Episode number
|
||||
languages: Optional list of languages to filter by
|
||||
|
||||
|
||||
Returns:
|
||||
List of matching subtitles
|
||||
"""
|
||||
@@ -85,66 +85,61 @@ class SubtitleService:
|
||||
all_subtitles = []
|
||||
for lang in languages:
|
||||
subs = self.repository.find_by_media(
|
||||
imdb_id,
|
||||
language=lang,
|
||||
season=season,
|
||||
episode=episode
|
||||
imdb_id, language=lang, season=season, episode=episode
|
||||
)
|
||||
all_subtitles.extend(subs)
|
||||
return all_subtitles
|
||||
else:
|
||||
return self.repository.find_by_media(
|
||||
imdb_id,
|
||||
season=season,
|
||||
episode=episode
|
||||
imdb_id, season=season, episode=episode
|
||||
)
|
||||
|
||||
|
||||
def remove_subtitle(self, subtitle: Subtitle) -> None:
|
||||
"""
|
||||
Remove a subtitle from the library.
|
||||
|
||||
|
||||
Args:
|
||||
subtitle: Subtitle to remove
|
||||
|
||||
|
||||
Raises:
|
||||
SubtitleNotFound: If subtitle not found
|
||||
"""
|
||||
if not self.repository.delete(subtitle):
|
||||
raise SubtitleNotFound(f"Subtitle not found: {subtitle}")
|
||||
|
||||
|
||||
logger.info(f"Removed subtitle: {subtitle}")
|
||||
|
||||
|
||||
def detect_format_from_file(self, file_path: FilePath) -> SubtitleFormat:
|
||||
"""
|
||||
Detect subtitle format from file extension.
|
||||
|
||||
|
||||
Args:
|
||||
file_path: Path to subtitle file
|
||||
|
||||
|
||||
Returns:
|
||||
Detected subtitle format
|
||||
"""
|
||||
extension = file_path.value.suffix
|
||||
return SubtitleFormat.from_extension(extension)
|
||||
|
||||
|
||||
def validate_subtitle_file(self, file_path: FilePath) -> bool:
|
||||
"""
|
||||
Validate that a file is a valid subtitle file.
|
||||
|
||||
|
||||
Args:
|
||||
file_path: Path to the file
|
||||
|
||||
|
||||
Returns:
|
||||
True if valid subtitle file, False otherwise
|
||||
"""
|
||||
if not file_path.exists():
|
||||
logger.warning(f"File does not exist: {file_path}")
|
||||
return False
|
||||
|
||||
|
||||
if not file_path.is_file():
|
||||
logger.warning(f"Path is not a file: {file_path}")
|
||||
return False
|
||||
|
||||
|
||||
# Check file extension
|
||||
try:
|
||||
self.detect_format_from_file(file_path)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Subtitle domain value objects."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
@@ -7,29 +8,21 @@ from ..shared.exceptions import ValidationError
|
||||
|
||||
class Language(Enum):
|
||||
"""Supported subtitle languages."""
|
||||
|
||||
ENGLISH = "en"
|
||||
FRENCH = "fr"
|
||||
SPANISH = "es"
|
||||
GERMAN = "de"
|
||||
ITALIAN = "it"
|
||||
PORTUGUESE = "pt"
|
||||
RUSSIAN = "ru"
|
||||
JAPANESE = "ja"
|
||||
KOREAN = "ko"
|
||||
CHINESE = "zh"
|
||||
ARABIC = "ar"
|
||||
|
||||
|
||||
@classmethod
|
||||
def from_code(cls, code: str) -> "Language":
|
||||
"""
|
||||
Get language from ISO 639-1 code.
|
||||
|
||||
|
||||
Args:
|
||||
code: Two-letter language code
|
||||
|
||||
|
||||
Returns:
|
||||
Language enum value
|
||||
|
||||
|
||||
Raises:
|
||||
ValidationError: If code is not supported
|
||||
"""
|
||||
@@ -42,27 +35,28 @@ class Language(Enum):
|
||||
|
||||
class SubtitleFormat(Enum):
|
||||
"""Supported subtitle formats."""
|
||||
|
||||
SRT = "srt" # SubRip
|
||||
ASS = "ass" # Advanced SubStation Alpha
|
||||
SSA = "ssa" # SubStation Alpha
|
||||
VTT = "vtt" # WebVTT
|
||||
SUB = "sub" # MicroDVD
|
||||
|
||||
|
||||
@classmethod
|
||||
def from_extension(cls, extension: str) -> "SubtitleFormat":
|
||||
"""
|
||||
Get format from file extension.
|
||||
|
||||
|
||||
Args:
|
||||
extension: File extension (with or without dot)
|
||||
|
||||
|
||||
Returns:
|
||||
SubtitleFormat enum value
|
||||
|
||||
|
||||
Raises:
|
||||
ValidationError: If extension is not supported
|
||||
"""
|
||||
ext = extension.lower().lstrip('.')
|
||||
ext = extension.lower().lstrip(".")
|
||||
for fmt in cls:
|
||||
if fmt.value == ext:
|
||||
return fmt
|
||||
@@ -73,22 +67,25 @@ class SubtitleFormat(Enum):
|
||||
class TimingOffset:
|
||||
"""
|
||||
Value object representing subtitle timing offset in milliseconds.
|
||||
|
||||
|
||||
Used for synchronizing subtitles with video.
|
||||
"""
|
||||
|
||||
milliseconds: int
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate timing offset."""
|
||||
if not isinstance(self.milliseconds, int):
|
||||
raise ValidationError(f"Timing offset must be an integer, got {type(self.milliseconds)}")
|
||||
|
||||
raise ValidationError(
|
||||
f"Timing offset must be an integer, got {type(self.milliseconds)}"
|
||||
)
|
||||
|
||||
def to_seconds(self) -> float:
|
||||
"""Convert to seconds."""
|
||||
return self.milliseconds / 1000.0
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.milliseconds}ms"
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"TimingOffset({self.milliseconds})"
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""TV Shows domain - Business logic for TV show management."""
|
||||
from .entities import TVShow, Season, Episode
|
||||
from .value_objects import ShowStatus, SeasonNumber, EpisodeNumber
|
||||
from .exceptions import TVShowNotFound, InvalidEpisode, SeasonNotFound
|
||||
|
||||
from .entities import Episode, Season, TVShow
|
||||
from .exceptions import InvalidEpisode, SeasonNotFound, TVShowNotFound
|
||||
from .services import TVShowService
|
||||
from .value_objects import EpisodeNumber, SeasonNumber, ShowStatus
|
||||
|
||||
__all__ = [
|
||||
"TVShow",
|
||||
|
||||
+79
-63
@@ -1,74 +1,79 @@
|
||||
"""TV Show domain entities."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional, List
|
||||
from datetime import datetime
|
||||
|
||||
from ..shared.value_objects import ImdbId, FilePath, FileSize
|
||||
from .value_objects import ShowStatus, SeasonNumber, EpisodeNumber
|
||||
from ..shared.value_objects import FilePath, FileSize, ImdbId
|
||||
from .value_objects import EpisodeNumber, SeasonNumber, ShowStatus
|
||||
|
||||
|
||||
@dataclass
|
||||
class TVShow:
|
||||
"""
|
||||
TV Show entity representing a TV show in the media library.
|
||||
|
||||
|
||||
This is the main aggregate root for the TV shows domain.
|
||||
Migrated from agent/models/tv_show.py
|
||||
"""
|
||||
|
||||
imdb_id: ImdbId
|
||||
title: str
|
||||
seasons_count: int
|
||||
status: ShowStatus
|
||||
tmdb_id: Optional[int] = None
|
||||
overview: Optional[str] = None
|
||||
poster_path: Optional[str] = None
|
||||
first_air_date: Optional[str] = None
|
||||
vote_average: Optional[float] = None
|
||||
tmdb_id: int | None = None
|
||||
first_air_date: str | None = None
|
||||
added_at: datetime = field(default_factory=datetime.now)
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate TV show entity."""
|
||||
# Ensure ImdbId is actually an ImdbId instance
|
||||
if not isinstance(self.imdb_id, ImdbId):
|
||||
if isinstance(self.imdb_id, str):
|
||||
object.__setattr__(self, 'imdb_id', ImdbId(self.imdb_id))
|
||||
object.__setattr__(self, "imdb_id", ImdbId(self.imdb_id))
|
||||
else:
|
||||
raise ValueError(f"imdb_id must be ImdbId or str, got {type(self.imdb_id)}")
|
||||
|
||||
raise ValueError(
|
||||
f"imdb_id must be ImdbId or str, got {type(self.imdb_id)}"
|
||||
)
|
||||
|
||||
# Ensure ShowStatus is actually a ShowStatus instance
|
||||
if not isinstance(self.status, ShowStatus):
|
||||
if isinstance(self.status, str):
|
||||
object.__setattr__(self, 'status', ShowStatus.from_string(self.status))
|
||||
object.__setattr__(self, "status", ShowStatus.from_string(self.status))
|
||||
else:
|
||||
raise ValueError(f"status must be ShowStatus or str, got {type(self.status)}")
|
||||
|
||||
raise ValueError(
|
||||
f"status must be ShowStatus or str, got {type(self.status)}"
|
||||
)
|
||||
|
||||
# Validate seasons_count
|
||||
if not isinstance(self.seasons_count, int) or self.seasons_count < 0:
|
||||
raise ValueError(f"seasons_count must be a non-negative integer, got {self.seasons_count}")
|
||||
|
||||
raise ValueError(
|
||||
f"seasons_count must be a non-negative integer, got {self.seasons_count}"
|
||||
)
|
||||
|
||||
def is_ongoing(self) -> bool:
|
||||
"""Check if the show is still ongoing."""
|
||||
return self.status == ShowStatus.ONGOING
|
||||
|
||||
|
||||
def is_ended(self) -> bool:
|
||||
"""Check if the show has ended."""
|
||||
return self.status == ShowStatus.ENDED
|
||||
|
||||
|
||||
def get_folder_name(self) -> str:
|
||||
"""
|
||||
Get the folder name for this TV show.
|
||||
|
||||
|
||||
Format: "Title"
|
||||
Example: "Breaking.Bad"
|
||||
"""
|
||||
import re
|
||||
|
||||
# Remove special characters and replace spaces with dots
|
||||
cleaned = re.sub(r'[^\w\s\.\-]', '', self.title)
|
||||
return cleaned.replace(' ', '.')
|
||||
|
||||
cleaned = re.sub(r"[^\w\s\.\-]", "", self.title)
|
||||
return cleaned.replace(" ", ".")
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.title} ({self.status.value}, {self.seasons_count} seasons)"
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"TVShow(imdb_id={self.imdb_id}, title='{self.title}')"
|
||||
|
||||
@@ -78,49 +83,54 @@ class Season:
|
||||
"""
|
||||
Season entity representing a season of a TV show.
|
||||
"""
|
||||
|
||||
show_imdb_id: ImdbId
|
||||
season_number: SeasonNumber
|
||||
episode_count: int
|
||||
name: Optional[str] = None
|
||||
overview: Optional[str] = None
|
||||
air_date: Optional[str] = None
|
||||
poster_path: Optional[str] = None
|
||||
|
||||
name: str | None = None
|
||||
overview: str | None = None
|
||||
air_date: str | None = None
|
||||
poster_path: str | None = None
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate season entity."""
|
||||
# Ensure ImdbId is actually an ImdbId instance
|
||||
if not isinstance(self.show_imdb_id, ImdbId):
|
||||
if isinstance(self.show_imdb_id, str):
|
||||
object.__setattr__(self, 'show_imdb_id', ImdbId(self.show_imdb_id))
|
||||
|
||||
object.__setattr__(self, "show_imdb_id", ImdbId(self.show_imdb_id))
|
||||
|
||||
# Ensure SeasonNumber is actually a SeasonNumber instance
|
||||
if not isinstance(self.season_number, SeasonNumber):
|
||||
if isinstance(self.season_number, int):
|
||||
object.__setattr__(self, 'season_number', SeasonNumber(self.season_number))
|
||||
|
||||
object.__setattr__(
|
||||
self, "season_number", SeasonNumber(self.season_number)
|
||||
)
|
||||
|
||||
# Validate episode_count
|
||||
if not isinstance(self.episode_count, int) or self.episode_count < 0:
|
||||
raise ValueError(f"episode_count must be a non-negative integer, got {self.episode_count}")
|
||||
|
||||
raise ValueError(
|
||||
f"episode_count must be a non-negative integer, got {self.episode_count}"
|
||||
)
|
||||
|
||||
def is_special(self) -> bool:
|
||||
"""Check if this is the specials season."""
|
||||
return self.season_number.is_special()
|
||||
|
||||
|
||||
def get_folder_name(self) -> str:
|
||||
"""
|
||||
Get the folder name for this season.
|
||||
|
||||
|
||||
Format: "Season 01" or "Specials" for season 0
|
||||
"""
|
||||
if self.is_special():
|
||||
return "Specials"
|
||||
return f"Season {self.season_number.value:02d}"
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.name:
|
||||
return f"Season {self.season_number.value}: {self.name}"
|
||||
return f"Season {self.season_number.value}"
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Season(show={self.show_imdb_id}, number={self.season_number.value})"
|
||||
|
||||
@@ -130,62 +140,68 @@ class Episode:
|
||||
"""
|
||||
Episode entity representing an episode of a TV show.
|
||||
"""
|
||||
|
||||
show_imdb_id: ImdbId
|
||||
season_number: SeasonNumber
|
||||
episode_number: EpisodeNumber
|
||||
title: str
|
||||
file_path: Optional[FilePath] = None
|
||||
file_size: Optional[FileSize] = None
|
||||
overview: Optional[str] = None
|
||||
air_date: Optional[str] = None
|
||||
still_path: Optional[str] = None
|
||||
vote_average: Optional[float] = None
|
||||
runtime: Optional[int] = None # in minutes
|
||||
|
||||
file_path: FilePath | None = None
|
||||
file_size: FileSize | None = None
|
||||
overview: str | None = None
|
||||
air_date: str | None = None
|
||||
still_path: str | None = None
|
||||
vote_average: float | None = None
|
||||
runtime: int | None = None # in minutes
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate episode entity."""
|
||||
# Ensure ImdbId is actually an ImdbId instance
|
||||
if not isinstance(self.show_imdb_id, ImdbId):
|
||||
if isinstance(self.show_imdb_id, str):
|
||||
object.__setattr__(self, 'show_imdb_id', ImdbId(self.show_imdb_id))
|
||||
|
||||
object.__setattr__(self, "show_imdb_id", ImdbId(self.show_imdb_id))
|
||||
|
||||
# Ensure SeasonNumber is actually a SeasonNumber instance
|
||||
if not isinstance(self.season_number, SeasonNumber):
|
||||
if isinstance(self.season_number, int):
|
||||
object.__setattr__(self, 'season_number', SeasonNumber(self.season_number))
|
||||
|
||||
object.__setattr__(
|
||||
self, "season_number", SeasonNumber(self.season_number)
|
||||
)
|
||||
|
||||
# Ensure EpisodeNumber is actually an EpisodeNumber instance
|
||||
if not isinstance(self.episode_number, EpisodeNumber):
|
||||
if isinstance(self.episode_number, int):
|
||||
object.__setattr__(self, 'episode_number', EpisodeNumber(self.episode_number))
|
||||
|
||||
object.__setattr__(
|
||||
self, "episode_number", EpisodeNumber(self.episode_number)
|
||||
)
|
||||
|
||||
def has_file(self) -> bool:
|
||||
"""Check if the episode has an associated file."""
|
||||
return self.file_path is not None and self.file_path.exists()
|
||||
|
||||
|
||||
def is_downloaded(self) -> bool:
|
||||
"""Check if the episode is downloaded."""
|
||||
return self.has_file()
|
||||
|
||||
|
||||
def get_filename(self) -> str:
|
||||
"""
|
||||
Get the suggested filename for this episode.
|
||||
|
||||
|
||||
Format: "S01E01 - Episode Title.ext"
|
||||
Example: "S01E05 - Pilot.mkv"
|
||||
"""
|
||||
season_str = f"S{self.season_number.value:02d}"
|
||||
episode_str = f"E{self.episode_number.value:02d}"
|
||||
|
||||
|
||||
# Clean title for filename
|
||||
import re
|
||||
clean_title = re.sub(r'[^\w\s\-]', '', self.title)
|
||||
clean_title = clean_title.replace(' ', '.')
|
||||
|
||||
|
||||
clean_title = re.sub(r"[^\w\s\-]", "", self.title)
|
||||
clean_title = clean_title.replace(" ", ".")
|
||||
|
||||
return f"{season_str}{episode_str}.{clean_title}"
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"S{self.season_number.value:02d}E{self.episode_number.value:02d} - {self.title}"
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Episode(show={self.show_imdb_id}, S{self.season_number.value:02d}E{self.episode_number.value:02d})"
|
||||
|
||||
@@ -1,27 +1,33 @@
|
||||
"""TV Show domain exceptions."""
|
||||
|
||||
from ..shared.exceptions import DomainException, NotFoundError
|
||||
|
||||
|
||||
class TVShowNotFound(NotFoundError):
|
||||
"""Raised when a TV show is not found."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class SeasonNotFound(NotFoundError):
|
||||
"""Raised when a season is not found."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class EpisodeNotFound(NotFoundError):
|
||||
"""Raised when an episode is not found."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class InvalidEpisode(DomainException):
|
||||
"""Raised when episode data is invalid."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TVShowAlreadyExists(DomainException):
|
||||
"""Raised when trying to add a TV show that already exists."""
|
||||
|
||||
pass
|
||||
|
||||
@@ -1,73 +1,73 @@
|
||||
"""TV Show repository interfaces (abstract)."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import List, Optional
|
||||
|
||||
from ..shared.value_objects import ImdbId
|
||||
from .entities import TVShow, Season, Episode
|
||||
from .value_objects import SeasonNumber, EpisodeNumber
|
||||
from .entities import Episode, Season, TVShow
|
||||
from .value_objects import EpisodeNumber, SeasonNumber
|
||||
|
||||
|
||||
class TVShowRepository(ABC):
|
||||
"""
|
||||
Abstract repository for TV show persistence.
|
||||
|
||||
|
||||
This defines the interface that infrastructure implementations must follow.
|
||||
"""
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def save(self, show: TVShow) -> None:
|
||||
"""
|
||||
Save a TV show to the repository.
|
||||
|
||||
|
||||
Args:
|
||||
show: TVShow entity to save
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_by_imdb_id(self, imdb_id: ImdbId) -> Optional[TVShow]:
|
||||
def find_by_imdb_id(self, imdb_id: ImdbId) -> TVShow | None:
|
||||
"""
|
||||
Find a TV show by its IMDb ID.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID to search for
|
||||
|
||||
|
||||
Returns:
|
||||
TVShow if found, None otherwise
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_all(self) -> List[TVShow]:
|
||||
def find_all(self) -> list[TVShow]:
|
||||
"""
|
||||
Get all TV shows in the repository.
|
||||
|
||||
|
||||
Returns:
|
||||
List of all TV shows
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, imdb_id: ImdbId) -> bool:
|
||||
"""
|
||||
Delete a TV show from the repository.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the show to delete
|
||||
|
||||
|
||||
Returns:
|
||||
True if deleted, False if not found
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def exists(self, imdb_id: ImdbId) -> bool:
|
||||
"""
|
||||
Check if a TV show exists in the repository.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID to check
|
||||
|
||||
|
||||
Returns:
|
||||
True if exists, False otherwise
|
||||
"""
|
||||
@@ -76,55 +76,51 @@ class TVShowRepository(ABC):
|
||||
|
||||
class SeasonRepository(ABC):
|
||||
"""Abstract repository for season persistence."""
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def save(self, season: Season) -> None:
|
||||
"""Save a season."""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_by_show_and_number(
|
||||
self,
|
||||
show_imdb_id: ImdbId,
|
||||
season_number: SeasonNumber
|
||||
) -> Optional[Season]:
|
||||
self, show_imdb_id: ImdbId, season_number: SeasonNumber
|
||||
) -> Season | None:
|
||||
"""Find a season by show and season number."""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_all_by_show(self, show_imdb_id: ImdbId) -> List[Season]:
|
||||
def find_all_by_show(self, show_imdb_id: ImdbId) -> list[Season]:
|
||||
"""Get all seasons for a show."""
|
||||
pass
|
||||
|
||||
|
||||
class EpisodeRepository(ABC):
|
||||
"""Abstract repository for episode persistence."""
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def save(self, episode: Episode) -> None:
|
||||
"""Save an episode."""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_by_show_season_episode(
|
||||
self,
|
||||
show_imdb_id: ImdbId,
|
||||
season_number: SeasonNumber,
|
||||
episode_number: EpisodeNumber
|
||||
) -> Optional[Episode]:
|
||||
episode_number: EpisodeNumber,
|
||||
) -> Episode | None:
|
||||
"""Find an episode by show, season, and episode number."""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_all_by_season(
|
||||
self,
|
||||
show_imdb_id: ImdbId,
|
||||
season_number: SeasonNumber
|
||||
) -> List[Episode]:
|
||||
self, show_imdb_id: ImdbId, season_number: SeasonNumber
|
||||
) -> list[Episode]:
|
||||
"""Get all episodes for a season."""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def find_all_by_show(self, show_imdb_id: ImdbId) -> List[Episode]:
|
||||
def find_all_by_show(self, show_imdb_id: ImdbId) -> list[Episode]:
|
||||
"""Get all episodes for a show."""
|
||||
pass
|
||||
|
||||
+70
-64
@@ -1,13 +1,15 @@
|
||||
"""TV Show domain services - Business logic."""
|
||||
|
||||
import logging
|
||||
from typing import Optional, List
|
||||
import re
|
||||
|
||||
from ..shared.value_objects import ImdbId
|
||||
from .entities import TVShow, Season, Episode
|
||||
from .value_objects import SeasonNumber, EpisodeNumber
|
||||
from .repositories import TVShowRepository, SeasonRepository, EpisodeRepository
|
||||
from .exceptions import TVShowNotFound, TVShowAlreadyExists, SeasonNotFound, EpisodeNotFound
|
||||
from .entities import TVShow
|
||||
from .exceptions import (
|
||||
TVShowAlreadyExists,
|
||||
TVShowNotFound,
|
||||
)
|
||||
from .repositories import EpisodeRepository, SeasonRepository, TVShowRepository
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -15,20 +17,20 @@ logger = logging.getLogger(__name__)
|
||||
class TVShowService:
|
||||
"""
|
||||
Domain service for TV show-related business logic.
|
||||
|
||||
|
||||
This service contains business rules that don't naturally fit
|
||||
within a single entity.
|
||||
"""
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
show_repository: TVShowRepository,
|
||||
season_repository: Optional[SeasonRepository] = None,
|
||||
episode_repository: Optional[EpisodeRepository] = None
|
||||
season_repository: SeasonRepository | None = None,
|
||||
episode_repository: EpisodeRepository | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize TV show service.
|
||||
|
||||
|
||||
Args:
|
||||
show_repository: TV show repository for persistence
|
||||
season_repository: Optional season repository
|
||||
@@ -37,33 +39,35 @@ class TVShowService:
|
||||
self.show_repository = show_repository
|
||||
self.season_repository = season_repository
|
||||
self.episode_repository = episode_repository
|
||||
|
||||
|
||||
def track_show(self, show: TVShow) -> None:
|
||||
"""
|
||||
Start tracking a TV show.
|
||||
|
||||
|
||||
Args:
|
||||
show: TVShow entity to track
|
||||
|
||||
|
||||
Raises:
|
||||
TVShowAlreadyExists: If show is already being tracked
|
||||
"""
|
||||
if self.show_repository.exists(show.imdb_id):
|
||||
raise TVShowAlreadyExists(f"TV show with IMDb ID {show.imdb_id} is already tracked")
|
||||
|
||||
raise TVShowAlreadyExists(
|
||||
f"TV show with IMDb ID {show.imdb_id} is already tracked"
|
||||
)
|
||||
|
||||
self.show_repository.save(show)
|
||||
logger.info(f"Started tracking TV show: {show.title} ({show.imdb_id})")
|
||||
|
||||
|
||||
def get_show(self, imdb_id: ImdbId) -> TVShow:
|
||||
"""
|
||||
Get a TV show by IMDb ID.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the show
|
||||
|
||||
|
||||
Returns:
|
||||
TVShow entity
|
||||
|
||||
|
||||
Raises:
|
||||
TVShowNotFound: If show not found
|
||||
"""
|
||||
@@ -71,158 +75,160 @@ class TVShowService:
|
||||
if not show:
|
||||
raise TVShowNotFound(f"TV show with IMDb ID {imdb_id} not found")
|
||||
return show
|
||||
|
||||
def get_all_shows(self) -> List[TVShow]:
|
||||
|
||||
def get_all_shows(self) -> list[TVShow]:
|
||||
"""
|
||||
Get all tracked TV shows.
|
||||
|
||||
|
||||
Returns:
|
||||
List of all TV shows
|
||||
"""
|
||||
return self.show_repository.find_all()
|
||||
|
||||
def get_ongoing_shows(self) -> List[TVShow]:
|
||||
|
||||
def get_ongoing_shows(self) -> list[TVShow]:
|
||||
"""
|
||||
Get all ongoing TV shows.
|
||||
|
||||
|
||||
Returns:
|
||||
List of ongoing TV shows
|
||||
"""
|
||||
all_shows = self.show_repository.find_all()
|
||||
return [show for show in all_shows if show.is_ongoing()]
|
||||
|
||||
def get_ended_shows(self) -> List[TVShow]:
|
||||
|
||||
def get_ended_shows(self) -> list[TVShow]:
|
||||
"""
|
||||
Get all ended TV shows.
|
||||
|
||||
|
||||
Returns:
|
||||
List of ended TV shows
|
||||
"""
|
||||
all_shows = self.show_repository.find_all()
|
||||
return [show for show in all_shows if show.is_ended()]
|
||||
|
||||
|
||||
def update_show(self, show: TVShow) -> None:
|
||||
"""
|
||||
Update an existing TV show.
|
||||
|
||||
|
||||
Args:
|
||||
show: TVShow entity with updated data
|
||||
|
||||
|
||||
Raises:
|
||||
TVShowNotFound: If show doesn't exist
|
||||
"""
|
||||
if not self.show_repository.exists(show.imdb_id):
|
||||
raise TVShowNotFound(f"TV show with IMDb ID {show.imdb_id} not found")
|
||||
|
||||
|
||||
self.show_repository.save(show)
|
||||
logger.info(f"Updated TV show: {show.title} ({show.imdb_id})")
|
||||
|
||||
|
||||
def untrack_show(self, imdb_id: ImdbId) -> None:
|
||||
"""
|
||||
Stop tracking a TV show.
|
||||
|
||||
|
||||
Args:
|
||||
imdb_id: IMDb ID of the show to untrack
|
||||
|
||||
|
||||
Raises:
|
||||
TVShowNotFound: If show not found
|
||||
"""
|
||||
if not self.show_repository.delete(imdb_id):
|
||||
raise TVShowNotFound(f"TV show with IMDb ID {imdb_id} not found")
|
||||
|
||||
|
||||
logger.info(f"Stopped tracking TV show with IMDb ID: {imdb_id}")
|
||||
|
||||
def parse_episode_from_filename(self, filename: str) -> Optional[tuple[int, int]]:
|
||||
|
||||
def parse_episode_from_filename(self, filename: str) -> tuple[int, int] | None:
|
||||
"""
|
||||
Parse season and episode numbers from filename.
|
||||
|
||||
|
||||
Supports formats:
|
||||
- S01E05
|
||||
- 1x05
|
||||
- Season 1 Episode 5
|
||||
|
||||
|
||||
Args:
|
||||
filename: Filename to parse
|
||||
|
||||
|
||||
Returns:
|
||||
Tuple of (season, episode) if found, None otherwise
|
||||
"""
|
||||
filename_lower = filename.lower()
|
||||
|
||||
|
||||
# Pattern 1: S01E05
|
||||
pattern1 = r's(\d{1,2})e(\d{1,2})'
|
||||
pattern1 = r"s(\d{1,2})e(\d{1,2})"
|
||||
match = re.search(pattern1, filename_lower)
|
||||
if match:
|
||||
return (int(match.group(1)), int(match.group(2)))
|
||||
|
||||
|
||||
# Pattern 2: 1x05
|
||||
pattern2 = r'(\d{1,2})x(\d{1,2})'
|
||||
pattern2 = r"(\d{1,2})x(\d{1,2})"
|
||||
match = re.search(pattern2, filename_lower)
|
||||
if match:
|
||||
return (int(match.group(1)), int(match.group(2)))
|
||||
|
||||
|
||||
# Pattern 3: Season 1 Episode 5
|
||||
pattern3 = r'season\s*(\d{1,2})\s*episode\s*(\d{1,2})'
|
||||
pattern3 = r"season\s*(\d{1,2})\s*episode\s*(\d{1,2})"
|
||||
match = re.search(pattern3, filename_lower)
|
||||
if match:
|
||||
return (int(match.group(1)), int(match.group(2)))
|
||||
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def validate_episode_file(self, filename: str) -> bool:
|
||||
"""
|
||||
Validate that a file is a valid episode file.
|
||||
|
||||
|
||||
Args:
|
||||
filename: Filename to validate
|
||||
|
||||
|
||||
Returns:
|
||||
True if valid episode file, False otherwise
|
||||
"""
|
||||
# Check file extension
|
||||
valid_extensions = {'.mkv', '.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm'}
|
||||
extension = filename[filename.rfind('.'):].lower() if '.' in filename else ''
|
||||
|
||||
valid_extensions = {".mkv", ".mp4", ".avi", ".mov", ".wmv", ".flv", ".webm"}
|
||||
extension = filename[filename.rfind(".") :].lower() if "." in filename else ""
|
||||
|
||||
if extension not in valid_extensions:
|
||||
logger.warning(f"Invalid file extension: {extension}")
|
||||
return False
|
||||
|
||||
|
||||
# Check if we can parse episode info
|
||||
episode_info = self.parse_episode_from_filename(filename)
|
||||
if not episode_info:
|
||||
logger.warning(f"Could not parse episode info from filename: {filename}")
|
||||
return False
|
||||
|
||||
|
||||
return True
|
||||
|
||||
def find_next_episode(self, show: TVShow, last_season: int, last_episode: int) -> Optional[tuple[int, int]]:
|
||||
|
||||
def find_next_episode(
|
||||
self, show: TVShow, last_season: int, last_episode: int
|
||||
) -> tuple[int, int] | None:
|
||||
"""
|
||||
Find the next episode to download for a show.
|
||||
|
||||
|
||||
Args:
|
||||
show: TVShow entity
|
||||
last_season: Last downloaded season number
|
||||
last_episode: Last downloaded episode number
|
||||
|
||||
|
||||
Returns:
|
||||
Tuple of (season, episode) for next episode, or None if show is complete
|
||||
"""
|
||||
# If show has ended and we've watched all seasons, no next episode
|
||||
if show.is_ended() and last_season >= show.seasons_count:
|
||||
return None
|
||||
|
||||
|
||||
# Simple logic: next episode in same season, or first episode of next season
|
||||
# This could be enhanced with actual episode counts per season
|
||||
next_episode = last_episode + 1
|
||||
next_season = last_season
|
||||
|
||||
|
||||
# Assume max 50 episodes per season (could be improved with actual data)
|
||||
if next_episode > 50:
|
||||
next_season += 1
|
||||
next_episode = 1
|
||||
|
||||
|
||||
# Don't go beyond known seasons
|
||||
if next_season > show.seasons_count:
|
||||
return None
|
||||
|
||||
|
||||
return (next_season, next_episode)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""TV Show domain value objects."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
@@ -7,18 +8,19 @@ from ..shared.exceptions import ValidationError
|
||||
|
||||
class ShowStatus(Enum):
|
||||
"""Status of a TV show - whether it's still airing or has ended."""
|
||||
|
||||
ONGOING = "ongoing"
|
||||
ENDED = "ended"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
@classmethod
|
||||
def from_string(cls, status_str: str) -> "ShowStatus":
|
||||
"""
|
||||
Parse status from string.
|
||||
|
||||
|
||||
Args:
|
||||
status_str: Status string (e.g., "ongoing", "ended")
|
||||
|
||||
|
||||
Returns:
|
||||
ShowStatus enum value
|
||||
"""
|
||||
@@ -33,34 +35,37 @@ class ShowStatus(Enum):
|
||||
class SeasonNumber:
|
||||
"""
|
||||
Value object representing a season number.
|
||||
|
||||
|
||||
Validates that the season number is valid (>= 0).
|
||||
Season 0 is used for specials.
|
||||
"""
|
||||
|
||||
value: int
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate season number."""
|
||||
if not isinstance(self.value, int):
|
||||
raise ValidationError(f"Season number must be an integer, got {type(self.value)}")
|
||||
|
||||
raise ValidationError(
|
||||
f"Season number must be an integer, got {type(self.value)}"
|
||||
)
|
||||
|
||||
if self.value < 0:
|
||||
raise ValidationError(f"Season number cannot be negative: {self.value}")
|
||||
|
||||
|
||||
# Reasonable upper limit
|
||||
if self.value > 100:
|
||||
raise ValidationError(f"Season number too high: {self.value}")
|
||||
|
||||
|
||||
def is_special(self) -> bool:
|
||||
"""Check if this is the specials season (season 0)."""
|
||||
return self.value == 0
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self.value)
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"SeasonNumber({self.value})"
|
||||
|
||||
|
||||
def __int__(self) -> int:
|
||||
return self.value
|
||||
|
||||
@@ -69,28 +74,31 @@ class SeasonNumber:
|
||||
class EpisodeNumber:
|
||||
"""
|
||||
Value object representing an episode number.
|
||||
|
||||
|
||||
Validates that the episode number is valid (>= 1).
|
||||
"""
|
||||
|
||||
value: int
|
||||
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate episode number."""
|
||||
if not isinstance(self.value, int):
|
||||
raise ValidationError(f"Episode number must be an integer, got {type(self.value)}")
|
||||
|
||||
raise ValidationError(
|
||||
f"Episode number must be an integer, got {type(self.value)}"
|
||||
)
|
||||
|
||||
if self.value < 1:
|
||||
raise ValidationError(f"Episode number must be >= 1, got {self.value}")
|
||||
|
||||
|
||||
# Reasonable upper limit
|
||||
if self.value > 1000:
|
||||
raise ValidationError(f"Episode number too high: {self.value}")
|
||||
|
||||
|
||||
def __str__(self) -> str:
|
||||
return str(self.value)
|
||||
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"EpisodeNumber({self.value})"
|
||||
|
||||
|
||||
def __int__(self) -> int:
|
||||
return self.value
|
||||
|
||||
Reference in New Issue
Block a user