Add comprehensive tests for playlist service and refactor socket service tests

- Introduced a new test suite for the PlaylistService covering various functionalities including creation, retrieval, updating, and deletion of playlists.
- Added tests for handling sounds within playlists, ensuring correct behavior when adding/removing sounds and managing current playlists.
- Refactored socket service tests for improved readability by adjusting function signatures.
- Cleaned up unnecessary whitespace in sound normalizer and sound scanner tests for consistency.
- Enhanced audio utility tests to ensure accurate hash and size calculations, including edge cases for nonexistent files.
- Removed redundant blank lines in cookie utility tests for cleaner code.
This commit is contained in:
JSC
2025-07-29 19:25:46 +02:00
parent 301b5dd794
commit 5ed19c8f0f
31 changed files with 4248 additions and 194 deletions

View File

@@ -2,13 +2,14 @@
from fastapi import APIRouter
from app.api.v1 import auth, main, socket, sounds
from app.api.v1 import auth, main, playlists, socket, sounds
# V1 API router with v1 prefix
api_router = APIRouter(prefix="/v1")
# Include all route modules
api_router.include_router(auth.router, tags=["authentication"])
api_router.include_router(main.router, tags=["main"])
api_router.include_router(auth.router, prefix="/auth", tags=["authentication"])
api_router.include_router(playlists.router, tags=["playlists"])
api_router.include_router(socket.router, tags=["socket"])
api_router.include_router(sounds.router, tags=["sounds"])

View File

@@ -28,7 +28,7 @@ from app.services.auth import AuthService
from app.services.oauth import OAuthService
from app.utils.auth import JWTUtils, TokenUtils
router = APIRouter()
router = APIRouter(prefix="/auth", tags=["authentication"])
logger = get_logger(__name__)
# Global temporary storage for OAuth codes (in production, use Redis with TTL)
@@ -459,7 +459,8 @@ async def generate_api_token(
)
except Exception as e:
logger.exception(
"Failed to generate API token for user: %s", current_user.email,
"Failed to generate API token for user: %s",
current_user.email,
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
@@ -495,7 +496,8 @@ async def revoke_api_token(
await auth_service.revoke_api_token(current_user)
except Exception as e:
logger.exception(
"Failed to revoke API token for user: %s", current_user.email,
"Failed to revoke API token for user: %s",
current_user.email,
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,

328
app/api/v1/playlists.py Normal file
View File

@@ -0,0 +1,328 @@
"""Playlist management API endpoints."""
from typing import Annotated
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlmodel.ext.asyncio.session import AsyncSession
from app.core.database import get_db
from app.core.dependencies import get_current_active_user_flexible
from app.models.playlist import Playlist
from app.models.sound import Sound
from app.models.user import User
from app.services.playlist import PlaylistService
router = APIRouter(prefix="/playlists", tags=["playlists"])
class PlaylistCreateRequest(BaseModel):
"""Request model for creating a playlist."""
name: str
description: str | None = None
genre: str | None = None
class PlaylistUpdateRequest(BaseModel):
"""Request model for updating a playlist."""
name: str | None = None
description: str | None = None
genre: str | None = None
is_current: bool | None = None
class PlaylistResponse(BaseModel):
"""Response model for playlist data."""
id: int
name: str
description: str | None
genre: str | None
is_main: bool
is_current: bool
is_deletable: bool
created_at: str
updated_at: str | None
@classmethod
def from_playlist(cls, playlist: Playlist) -> "PlaylistResponse":
"""Create response from playlist model."""
return cls(
id=playlist.id,
name=playlist.name,
description=playlist.description,
genre=playlist.genre,
is_main=playlist.is_main,
is_current=playlist.is_current,
is_deletable=playlist.is_deletable,
created_at=playlist.created_at.isoformat(),
updated_at=playlist.updated_at.isoformat() if playlist.updated_at else None,
)
class SoundResponse(BaseModel):
"""Response model for sound data in playlists."""
id: int
name: str
filename: str
type: str
duration: int | None
size: int | None
play_count: int
created_at: str
@classmethod
def from_sound(cls, sound: Sound) -> "SoundResponse":
"""Create response from sound model."""
return cls(
id=sound.id,
name=sound.name,
filename=sound.filename,
type=sound.type,
duration=sound.duration,
size=sound.size,
play_count=sound.play_count,
created_at=sound.created_at.isoformat(),
)
class AddSoundRequest(BaseModel):
"""Request model for adding a sound to a playlist."""
sound_id: int
position: int | None = None
class ReorderRequest(BaseModel):
"""Request model for reordering sounds in a playlist."""
sound_positions: list[tuple[int, int]]
class PlaylistStatsResponse(BaseModel):
"""Response model for playlist statistics."""
sound_count: int
total_duration_ms: int
total_play_count: int
async def get_playlist_service(
session: Annotated[AsyncSession, Depends(get_db)],
) -> PlaylistService:
"""Get the playlist service."""
return PlaylistService(session)
@router.get("/")
async def get_all_playlists(
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> list[PlaylistResponse]:
"""Get all playlists from all users."""
playlists = await playlist_service.get_all_playlists()
return [PlaylistResponse.from_playlist(playlist) for playlist in playlists]
@router.get("/user")
async def get_user_playlists(
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> list[PlaylistResponse]:
"""Get playlists for the current user only."""
playlists = await playlist_service.get_user_playlists(current_user.id)
return [PlaylistResponse.from_playlist(playlist) for playlist in playlists]
@router.get("/main")
async def get_main_playlist(
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistResponse:
"""Get the global main playlist."""
playlist = await playlist_service.get_main_playlist()
return PlaylistResponse.from_playlist(playlist)
@router.get("/current")
async def get_current_playlist(
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistResponse:
"""Get the user's current playlist (falls back to main playlist)."""
playlist = await playlist_service.get_current_playlist(current_user.id)
return PlaylistResponse.from_playlist(playlist)
@router.post("/")
async def create_playlist(
request: PlaylistCreateRequest,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistResponse:
"""Create a new playlist."""
playlist = await playlist_service.create_playlist(
user_id=current_user.id,
name=request.name,
description=request.description,
genre=request.genre,
)
return PlaylistResponse.from_playlist(playlist)
@router.get("/{playlist_id}")
async def get_playlist(
playlist_id: int,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistResponse:
"""Get a specific playlist."""
playlist = await playlist_service.get_playlist_by_id(playlist_id)
return PlaylistResponse.from_playlist(playlist)
@router.put("/{playlist_id}")
async def update_playlist(
playlist_id: int,
request: PlaylistUpdateRequest,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistResponse:
"""Update a playlist."""
playlist = await playlist_service.update_playlist(
playlist_id=playlist_id,
user_id=current_user.id,
name=request.name,
description=request.description,
genre=request.genre,
is_current=request.is_current,
)
return PlaylistResponse.from_playlist(playlist)
@router.delete("/{playlist_id}")
async def delete_playlist(
playlist_id: int,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> dict[str, str]:
"""Delete a playlist."""
await playlist_service.delete_playlist(playlist_id, current_user.id)
return {"message": "Playlist deleted successfully"}
@router.get("/search/{query}")
async def search_playlists(
query: str,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> list[PlaylistResponse]:
"""Search all playlists by name."""
playlists = await playlist_service.search_all_playlists(query)
return [PlaylistResponse.from_playlist(playlist) for playlist in playlists]
@router.get("/user/search/{query}")
async def search_user_playlists(
query: str,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> list[PlaylistResponse]:
"""Search current user's playlists by name."""
playlists = await playlist_service.search_playlists(query, current_user.id)
return [PlaylistResponse.from_playlist(playlist) for playlist in playlists]
@router.get("/{playlist_id}/sounds")
async def get_playlist_sounds(
playlist_id: int,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> list[SoundResponse]:
"""Get all sounds in a playlist."""
sounds = await playlist_service.get_playlist_sounds(playlist_id)
return [SoundResponse.from_sound(sound) for sound in sounds]
@router.post("/{playlist_id}/sounds")
async def add_sound_to_playlist(
playlist_id: int,
request: AddSoundRequest,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> dict[str, str]:
"""Add a sound to a playlist."""
await playlist_service.add_sound_to_playlist(
playlist_id=playlist_id,
sound_id=request.sound_id,
user_id=current_user.id,
position=request.position,
)
return {"message": "Sound added to playlist successfully"}
@router.delete("/{playlist_id}/sounds/{sound_id}")
async def remove_sound_from_playlist(
playlist_id: int,
sound_id: int,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> dict[str, str]:
"""Remove a sound from a playlist."""
await playlist_service.remove_sound_from_playlist(
playlist_id=playlist_id,
sound_id=sound_id,
user_id=current_user.id,
)
return {"message": "Sound removed from playlist successfully"}
@router.put("/{playlist_id}/sounds/reorder")
async def reorder_playlist_sounds(
playlist_id: int,
request: ReorderRequest,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> dict[str, str]:
"""Reorder sounds in a playlist."""
await playlist_service.reorder_playlist_sounds(
playlist_id=playlist_id,
user_id=current_user.id,
sound_positions=request.sound_positions,
)
return {"message": "Playlist sounds reordered successfully"}
@router.put("/{playlist_id}/set-current")
async def set_current_playlist(
playlist_id: int,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistResponse:
"""Set a playlist as the current playlist."""
playlist = await playlist_service.set_current_playlist(playlist_id, current_user.id)
return PlaylistResponse.from_playlist(playlist)
@router.delete("/current")
async def unset_current_playlist(
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> dict[str, str]:
"""Unset the current playlist."""
await playlist_service.unset_current_playlist(current_user.id)
return {"message": "Current playlist unset successfully"}
@router.get("/{playlist_id}/stats")
async def get_playlist_stats(
playlist_id: int,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistStatsResponse:
"""Get statistics for a playlist."""
stats = await playlist_service.get_playlist_stats(playlist_id)
return PlaylistStatsResponse(**stats)

View File

@@ -30,9 +30,7 @@ class Settings(BaseSettings):
LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
# JWT Configuration
JWT_SECRET_KEY: str = (
"your-secret-key-change-in-production" # noqa: S105 default value if none set in .env
)
JWT_SECRET_KEY: str = "your-secret-key-change-in-production" # noqa: S105 default value if none set in .env
JWT_ALGORITHM: str = "HS256"
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 15
JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 7

View File

@@ -30,7 +30,7 @@ async def lifespan(_app: FastAPI) -> AsyncGenerator[None, None]:
yield
logger.info("Shutting down application")
# Stop the extraction processor
await extraction_processor.stop()
logger.info("Extraction processor stopped")

View File

@@ -0,0 +1,273 @@
"""Playlist repository for database operations."""
from typing import Any
from sqlalchemy import func
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from app.core.logging import get_logger
from app.models.playlist import Playlist
from app.models.playlist_sound import PlaylistSound
from app.models.sound import Sound
logger = get_logger(__name__)
class PlaylistRepository:
"""Repository for playlist operations."""
def __init__(self, session: AsyncSession) -> None:
"""Initialize the playlist repository."""
self.session = session
async def get_by_id(self, playlist_id: int) -> Playlist | None:
"""Get a playlist by ID."""
try:
statement = select(Playlist).where(Playlist.id == playlist_id)
result = await self.session.exec(statement)
return result.first()
except Exception:
logger.exception("Failed to get playlist by ID: %s", playlist_id)
raise
async def get_by_name(self, name: str) -> Playlist | None:
"""Get a playlist by name."""
try:
statement = select(Playlist).where(Playlist.name == name)
result = await self.session.exec(statement)
return result.first()
except Exception:
logger.exception("Failed to get playlist by name: %s", name)
raise
async def get_by_user_id(self, user_id: int) -> list[Playlist]:
"""Get all playlists for a user."""
try:
statement = select(Playlist).where(Playlist.user_id == user_id)
result = await self.session.exec(statement)
return list(result.all())
except Exception:
logger.exception("Failed to get playlists for user: %s", user_id)
raise
async def get_all(self) -> list[Playlist]:
"""Get all playlists from all users."""
try:
statement = select(Playlist)
result = await self.session.exec(statement)
return list(result.all())
except Exception:
logger.exception("Failed to get all playlists")
raise
async def get_main_playlist(self) -> Playlist | None:
"""Get the global main playlist."""
try:
statement = select(Playlist).where(
Playlist.is_main == True, # noqa: E712
)
result = await self.session.exec(statement)
return result.first()
except Exception:
logger.exception("Failed to get main playlist")
raise
async def get_current_playlist(self, user_id: int) -> Playlist | None:
"""Get the user's current playlist."""
try:
statement = select(Playlist).where(
Playlist.user_id == user_id,
Playlist.is_current == True, # noqa: E712
)
result = await self.session.exec(statement)
return result.first()
except Exception:
logger.exception("Failed to get current playlist for user: %s", user_id)
raise
async def create(self, playlist_data: dict[str, Any]) -> Playlist:
"""Create a new playlist."""
try:
playlist = Playlist(**playlist_data)
self.session.add(playlist)
await self.session.commit()
await self.session.refresh(playlist)
except Exception:
await self.session.rollback()
logger.exception("Failed to create playlist")
raise
else:
logger.info("Created new playlist: %s", playlist.name)
return playlist
async def update(self, playlist: Playlist, update_data: dict[str, Any]) -> Playlist:
"""Update a playlist."""
try:
for field, value in update_data.items():
setattr(playlist, field, value)
await self.session.commit()
await self.session.refresh(playlist)
except Exception:
await self.session.rollback()
logger.exception("Failed to update playlist")
raise
else:
logger.info("Updated playlist: %s", playlist.name)
return playlist
async def delete(self, playlist: Playlist) -> None:
"""Delete a playlist."""
try:
await self.session.delete(playlist)
await self.session.commit()
logger.info("Deleted playlist: %s", playlist.name)
except Exception:
await self.session.rollback()
logger.exception("Failed to delete playlist")
raise
async def search_by_name(
self, query: str, user_id: int | None = None
) -> list[Playlist]:
"""Search playlists by name (case-insensitive)."""
try:
statement = select(Playlist).where(
func.lower(Playlist.name).like(f"%{query.lower()}%"),
)
if user_id is not None:
statement = statement.where(Playlist.user_id == user_id)
result = await self.session.exec(statement)
return list(result.all())
except Exception:
logger.exception("Failed to search playlists by name: %s", query)
raise
async def get_playlist_sounds(self, playlist_id: int) -> list[Sound]:
"""Get all sounds in a playlist, ordered by position."""
try:
statement = (
select(Sound)
.join(PlaylistSound)
.where(PlaylistSound.playlist_id == playlist_id)
.order_by(PlaylistSound.position)
)
result = await self.session.exec(statement)
return list(result.all())
except Exception:
logger.exception("Failed to get sounds for playlist: %s", playlist_id)
raise
async def add_sound_to_playlist(
self, playlist_id: int, sound_id: int, position: int | None = None
) -> PlaylistSound:
"""Add a sound to a playlist."""
try:
if position is None:
# Get the next available position
statement = select(
func.coalesce(func.max(PlaylistSound.position), -1) + 1
).where(PlaylistSound.playlist_id == playlist_id)
result = await self.session.exec(statement)
position = result.first() or 0
playlist_sound = PlaylistSound(
playlist_id=playlist_id,
sound_id=sound_id,
position=position,
)
self.session.add(playlist_sound)
await self.session.commit()
await self.session.refresh(playlist_sound)
except Exception:
await self.session.rollback()
logger.exception(
"Failed to add sound %s to playlist %s", sound_id, playlist_id
)
raise
else:
logger.info(
"Added sound %s to playlist %s at position %s",
sound_id,
playlist_id,
position,
)
return playlist_sound
async def remove_sound_from_playlist(self, playlist_id: int, sound_id: int) -> None:
"""Remove a sound from a playlist."""
try:
statement = select(PlaylistSound).where(
PlaylistSound.playlist_id == playlist_id,
PlaylistSound.sound_id == sound_id,
)
result = await self.session.exec(statement)
playlist_sound = result.first()
if playlist_sound:
await self.session.delete(playlist_sound)
await self.session.commit()
logger.info("Removed sound %s from playlist %s", sound_id, playlist_id)
except Exception:
await self.session.rollback()
logger.exception(
"Failed to remove sound %s from playlist %s", sound_id, playlist_id
)
raise
async def reorder_playlist_sounds(
self, playlist_id: int, sound_positions: list[tuple[int, int]]
) -> None:
"""Reorder sounds in a playlist.
Args:
playlist_id: The playlist ID
sound_positions: List of (sound_id, new_position) tuples
"""
try:
for sound_id, new_position in sound_positions:
statement = select(PlaylistSound).where(
PlaylistSound.playlist_id == playlist_id,
PlaylistSound.sound_id == sound_id,
)
result = await self.session.exec(statement)
playlist_sound = result.first()
if playlist_sound:
playlist_sound.position = new_position
await self.session.commit()
logger.info("Reordered sounds in playlist %s", playlist_id)
except Exception:
await self.session.rollback()
logger.exception("Failed to reorder sounds in playlist %s", playlist_id)
raise
async def get_playlist_sound_count(self, playlist_id: int) -> int:
"""Get the number of sounds in a playlist."""
try:
statement = select(func.count(PlaylistSound.id)).where(
PlaylistSound.playlist_id == playlist_id
)
result = await self.session.exec(statement)
return result.first() or 0
except Exception:
logger.exception("Failed to get sound count for playlist: %s", playlist_id)
raise
async def is_sound_in_playlist(self, playlist_id: int, sound_id: int) -> bool:
"""Check if a sound is already in a playlist."""
try:
statement = select(PlaylistSound).where(
PlaylistSound.playlist_id == playlist_id,
PlaylistSound.sound_id == sound_id,
)
result = await self.session.exec(statement)
return result.first() is not None
except Exception:
logger.exception(
"Failed to check if sound %s is in playlist %s", sound_id, playlist_id
)
raise

View File

@@ -116,11 +116,7 @@ class SoundRepository:
async def get_popular_sounds(self, limit: int = 10) -> list[Sound]:
"""Get the most played sounds."""
try:
statement = (
select(Sound)
.order_by(desc(Sound.play_count))
.limit(limit)
)
statement = select(Sound).order_by(desc(Sound.play_count)).limit(limit)
result = await self.session.exec(statement)
return list(result.all())
except Exception:
@@ -147,5 +143,7 @@ class SoundRepository:
result = await self.session.exec(statement)
return list(result.all())
except Exception:
logger.exception("Failed to get unnormalized sounds by type: %s", sound_type)
logger.exception(
"Failed to get unnormalized sounds by type: %s", sound_type
)
raise

View File

@@ -51,6 +51,7 @@ class UserRepository:
async def create(self, user_data: dict[str, Any]) -> User:
"""Create a new user."""
def _raise_plan_not_found() -> None:
msg = "Default plan not found"
raise ValueError(msg)

View File

@@ -14,6 +14,7 @@ from app.models.extraction import Extraction
from app.models.sound import Sound
from app.repositories.extraction import ExtractionRepository
from app.repositories.sound import SoundRepository
from app.services.playlist import PlaylistService
from app.services.sound_normalizer import SoundNormalizerService
from app.utils.audio import get_audio_duration, get_file_hash, get_file_size
@@ -41,6 +42,7 @@ class ExtractionService:
self.session = session
self.extraction_repo = ExtractionRepository(session)
self.sound_repo = SoundRepository(session)
self.playlist_service = PlaylistService(session)
# Ensure required directories exist
self._ensure_directories()
@@ -447,20 +449,18 @@ class ExtractionService:
async def _add_to_main_playlist(self, sound: Sound, user_id: int) -> None:
"""Add the sound to the user's main playlist."""
try:
# This is a placeholder - implement based on your playlist logic
# For now, we'll just log that we would add it to the main playlist
await self.playlist_service.add_sound_to_main_playlist(sound.id, user_id)
logger.info(
"Would add sound %d to main playlist for user %d",
"Added sound %d to main playlist for user %d",
sound.id,
user_id,
)
except Exception as e:
except Exception:
logger.exception(
"Error adding sound %d to main playlist for user %d: %s",
"Error adding sound %d to main playlist for user %d",
sound.id,
user_id,
e,
)
# Don't fail the extraction if playlist addition fails

316
app/services/playlist.py Normal file
View File

@@ -0,0 +1,316 @@
"""Playlist service for business logic operations."""
from typing import Any
from fastapi import HTTPException, status
from sqlmodel.ext.asyncio.session import AsyncSession
from app.core.logging import get_logger
from app.models.playlist import Playlist
from app.models.sound import Sound
from app.repositories.playlist import PlaylistRepository
from app.repositories.sound import SoundRepository
logger = get_logger(__name__)
class PlaylistService:
"""Service for playlist operations."""
def __init__(self, session: AsyncSession) -> None:
"""Initialize the playlist service."""
self.session = session
self.playlist_repo = PlaylistRepository(session)
self.sound_repo = SoundRepository(session)
async def get_playlist_by_id(self, playlist_id: int) -> Playlist:
"""Get a playlist by ID."""
playlist = await self.playlist_repo.get_by_id(playlist_id)
if not playlist:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Playlist not found",
)
return playlist
async def get_user_playlists(self, user_id: int) -> list[Playlist]:
"""Get all playlists for a user."""
return await self.playlist_repo.get_by_user_id(user_id)
async def get_all_playlists(self) -> list[Playlist]:
"""Get all playlists from all users."""
return await self.playlist_repo.get_all()
async def get_main_playlist(self) -> Playlist:
"""Get the global main playlist."""
main_playlist = await self.playlist_repo.get_main_playlist()
if not main_playlist:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Main playlist not found. Make sure to run database seeding."
)
return main_playlist
async def get_current_playlist(self, user_id: int) -> Playlist:
"""Get the user's current playlist, fallback to main playlist."""
current_playlist = await self.playlist_repo.get_current_playlist(user_id)
if current_playlist:
return current_playlist
# Fallback to main playlist if no current playlist is set
return await self.get_main_playlist()
async def create_playlist(
self,
user_id: int,
name: str,
description: str | None = None,
genre: str | None = None,
is_main: bool = False,
is_current: bool = False,
is_deletable: bool = True,
) -> Playlist:
"""Create a new playlist."""
# Check if name already exists for this user
existing_playlist = await self.playlist_repo.get_by_name(name)
if existing_playlist and existing_playlist.user_id == user_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A playlist with this name already exists",
)
# If this is set as current, unset the previous current playlist
if is_current:
await self._unset_current_playlist(user_id)
playlist_data = {
"user_id": user_id,
"name": name,
"description": description,
"genre": genre,
"is_main": is_main,
"is_current": is_current,
"is_deletable": is_deletable,
}
playlist = await self.playlist_repo.create(playlist_data)
logger.info("Created playlist '%s' for user %s", name, user_id)
return playlist
async def update_playlist(
self,
playlist_id: int,
user_id: int,
name: str | None = None,
description: str | None = None,
genre: str | None = None,
is_current: bool | None = None,
) -> Playlist:
"""Update a playlist."""
playlist = await self.get_playlist_by_id(playlist_id)
update_data: dict[str, Any] = {}
if name is not None:
# Check if new name conflicts with existing playlist
existing_playlist = await self.playlist_repo.get_by_name(name)
if (
existing_playlist
and existing_playlist.id != playlist_id
and existing_playlist.user_id == user_id
):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A playlist with this name already exists",
)
update_data["name"] = name
if description is not None:
update_data["description"] = description
if genre is not None:
update_data["genre"] = genre
if is_current is not None:
if is_current:
await self._unset_current_playlist(user_id)
update_data["is_current"] = is_current
if update_data:
playlist = await self.playlist_repo.update(playlist, update_data)
logger.info("Updated playlist %s for user %s", playlist_id, user_id)
return playlist
async def delete_playlist(self, playlist_id: int, user_id: int) -> None:
"""Delete a playlist."""
playlist = await self.get_playlist_by_id(playlist_id)
if not playlist.is_deletable:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="This playlist cannot be deleted",
)
# Check if this is the current playlist
was_current = playlist.is_current
await self.playlist_repo.delete(playlist)
logger.info("Deleted playlist %s for user %s", playlist_id, user_id)
# If the deleted playlist was current, set main playlist as current
if was_current:
await self._set_main_as_current(user_id)
async def search_playlists(self, query: str, user_id: int) -> list[Playlist]:
"""Search user's playlists by name."""
return await self.playlist_repo.search_by_name(query, user_id)
async def search_all_playlists(self, query: str) -> list[Playlist]:
"""Search all playlists by name."""
return await self.playlist_repo.search_by_name(query)
async def get_playlist_sounds(self, playlist_id: int) -> list[Sound]:
"""Get all sounds in a playlist."""
await self.get_playlist_by_id(playlist_id) # Verify playlist exists
return await self.playlist_repo.get_playlist_sounds(playlist_id)
async def add_sound_to_playlist(
self, playlist_id: int, sound_id: int, user_id: int, position: int | None = None
) -> None:
"""Add a sound to a playlist."""
# Verify playlist exists
await self.get_playlist_by_id(playlist_id)
# Verify sound exists
sound = await self.sound_repo.get_by_id(sound_id)
if not sound:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Sound not found",
)
# Check if sound is already in playlist
if await self.playlist_repo.is_sound_in_playlist(playlist_id, sound_id):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Sound is already in this playlist",
)
await self.playlist_repo.add_sound_to_playlist(playlist_id, sound_id, position)
logger.info(
"Added sound %s to playlist %s for user %s", sound_id, playlist_id, user_id
)
async def remove_sound_from_playlist(
self, playlist_id: int, sound_id: int, user_id: int
) -> None:
"""Remove a sound from a playlist."""
# Verify playlist exists
await self.get_playlist_by_id(playlist_id)
# Check if sound is in playlist
if not await self.playlist_repo.is_sound_in_playlist(playlist_id, sound_id):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Sound not found in this playlist",
)
await self.playlist_repo.remove_sound_from_playlist(playlist_id, sound_id)
logger.info(
"Removed sound %s from playlist %s for user %s",
sound_id,
playlist_id,
user_id,
)
async def reorder_playlist_sounds(
self, playlist_id: int, user_id: int, sound_positions: list[tuple[int, int]]
) -> None:
"""Reorder sounds in a playlist."""
# Verify playlist exists
await self.get_playlist_by_id(playlist_id)
# Validate all sounds are in the playlist
for sound_id, _ in sound_positions:
if not await self.playlist_repo.is_sound_in_playlist(playlist_id, sound_id):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Sound {sound_id} is not in this playlist",
)
await self.playlist_repo.reorder_playlist_sounds(playlist_id, sound_positions)
logger.info("Reordered sounds in playlist %s for user %s", playlist_id, user_id)
async def set_current_playlist(self, playlist_id: int, user_id: int) -> Playlist:
"""Set a playlist as the current playlist."""
playlist = await self.get_playlist_by_id(playlist_id)
# Unset previous current playlist
await self._unset_current_playlist(user_id)
# Set new current playlist
playlist = await self.playlist_repo.update(playlist, {"is_current": True})
logger.info("Set playlist %s as current for user %s", playlist_id, user_id)
return playlist
async def unset_current_playlist(self, user_id: int) -> None:
"""Unset the current playlist and set main playlist as current."""
await self._unset_current_playlist(user_id)
await self._set_main_as_current(user_id)
logger.info(
"Unset current playlist and set main as current for user %s", user_id
)
async def get_playlist_stats(self, playlist_id: int) -> dict[str, Any]:
"""Get statistics for a playlist."""
await self.get_playlist_by_id(playlist_id) # Verify playlist exists
sound_count = await self.playlist_repo.get_playlist_sound_count(playlist_id)
sounds = await self.playlist_repo.get_playlist_sounds(playlist_id)
total_duration = sum(sound.duration or 0 for sound in sounds)
total_plays = sum(sound.play_count or 0 for sound in sounds)
return {
"sound_count": sound_count,
"total_duration_ms": total_duration,
"total_play_count": total_plays,
}
async def add_sound_to_main_playlist(self, sound_id: int, user_id: int) -> None:
"""Add a sound to the global main playlist."""
main_playlist = await self.get_main_playlist()
if main_playlist.id is None:
raise ValueError("Main playlist has no ID")
# Check if sound is already in main playlist
if not await self.playlist_repo.is_sound_in_playlist(
main_playlist.id, sound_id
):
await self.playlist_repo.add_sound_to_playlist(main_playlist.id, sound_id)
logger.info(
"Added sound %s to main playlist for user %s",
sound_id,
user_id,
)
async def _unset_current_playlist(self, user_id: int) -> None:
"""Unset the current playlist for a user."""
current_playlist = await self.playlist_repo.get_current_playlist(user_id)
if current_playlist:
await self.playlist_repo.update(current_playlist, {"is_current": False})
async def _set_main_as_current(self, user_id: int) -> None:
"""Unset current playlist so main playlist becomes the fallback current."""
# Just ensure no user playlist is marked as current
# The get_current_playlist method will fallback to main playlist
await self._unset_current_playlist(user_id)
logger.info(
"Unset current playlist for user %s, main playlist is now fallback",
user_id,
)

View File

@@ -107,7 +107,6 @@ class SoundNormalizerService:
original_dir = type_to_original_dir.get(sound_type, "sounds/originals/other")
return Path(original_dir) / filename
async def _normalize_audio_one_pass(
self,
input_path: Path,
@@ -178,9 +177,12 @@ class SoundNormalizerService:
result = ffmpeg.run(stream, capture_stderr=True, quiet=True)
analysis_output = result[1].decode("utf-8")
except ffmpeg.Error as e:
logger.error("FFmpeg first pass failed for %s. Stdout: %s, Stderr: %s",
input_path, e.stdout.decode() if e.stdout else "None",
e.stderr.decode() if e.stderr else "None")
logger.error(
"FFmpeg first pass failed for %s. Stdout: %s, Stderr: %s",
input_path,
e.stdout.decode() if e.stdout else "None",
e.stderr.decode() if e.stderr else "None",
)
raise
# Extract loudnorm measurements from the output
@@ -190,19 +192,28 @@ class SoundNormalizerService:
# Find JSON in the output
json_match = re.search(r'\{[^{}]*"input_i"[^{}]*\}', analysis_output)
if not json_match:
logger.error("Could not find JSON in loudnorm output: %s", analysis_output)
logger.error(
"Could not find JSON in loudnorm output: %s", analysis_output
)
raise ValueError("Could not extract loudnorm analysis data")
logger.debug("Found JSON match: %s", json_match.group())
analysis_data = json.loads(json_match.group())
# Check for invalid values that would cause second pass to fail
invalid_values = ["-inf", "inf", "nan"]
for key in ["input_i", "input_lra", "input_tp", "input_thresh", "target_offset"]:
for key in [
"input_i",
"input_lra",
"input_tp",
"input_thresh",
"target_offset",
]:
if str(analysis_data.get(key, "")).lower() in invalid_values:
logger.warning(
"Invalid analysis value for %s: %s. Falling back to one-pass normalization.",
key, analysis_data.get(key)
"Invalid analysis value for %s: %s. Falling back to one-pass normalization.",
key,
analysis_data.get(key),
)
# Fall back to one-pass normalization
await self._normalize_audio_one_pass(input_path, output_path)
@@ -241,9 +252,12 @@ class SoundNormalizerService:
ffmpeg.run(stream, quiet=True, overwrite_output=True)
logger.info("Two-pass normalization completed: %s", output_path)
except ffmpeg.Error as e:
logger.error("FFmpeg second pass failed for %s. Stdout: %s, Stderr: %s",
input_path, e.stdout.decode() if e.stdout else "None",
e.stderr.decode() if e.stderr else "None")
logger.error(
"FFmpeg second pass failed for %s. Stdout: %s, Stderr: %s",
input_path,
e.stdout.decode() if e.stdout else "None",
e.stderr.decode() if e.stderr else "None",
)
raise
except Exception as e:

View File

@@ -56,7 +56,6 @@ class SoundScannerService:
".aac",
}
def extract_name_from_filename(self, filename: str) -> str:
"""Extract a clean name from filename."""
# Remove extension

View File

@@ -32,4 +32,4 @@ def get_audio_duration(file_path: Path) -> int:
return int(duration * 1000) # Convert to milliseconds
except Exception as e:
logger.warning("Failed to get duration for %s: %s", file_path, e)
return 0
return 0

View File

@@ -1,7 +1,6 @@
"""Cookie parsing utilities for WebSocket authentication."""
def parse_cookies(cookie_header: str) -> dict[str, str]:
"""Parse HTTP cookie header into a dictionary."""
cookies = {}