Compare commits

..

4 Commits

Author SHA1 Message Date
JSC
d926779fe4 feat: Implement playlist reordering with position swapping and reload player on current playlist changes
Some checks failed
Backend CI / lint (push) Failing after 5m7s
Backend CI / test (push) Successful in 5m14s
2025-08-01 17:49:29 +02:00
JSC
0575d12b0e refactor: Rename global current playlist methods for clarity and consistency 2025-08-01 17:12:56 +02:00
JSC
c0f51b2e23 refactor: Update playlist service and endpoints for global current playlist management 2025-08-01 16:58:25 +02:00
JSC
3132175354 refactor: Create admin enpoints and some renaming of api endpoints 2025-08-01 15:34:35 +02:00
17 changed files with 1218 additions and 1373 deletions

View File

@@ -2,7 +2,7 @@
from fastapi import APIRouter from fastapi import APIRouter
from app.api.v1 import auth, main, player, playlists, socket, sounds from app.api.v1 import admin, auth, main, player, playlists, socket, sounds
# V1 API router with v1 prefix # V1 API router with v1 prefix
api_router = APIRouter(prefix="/v1") api_router = APIRouter(prefix="/v1")
@@ -14,3 +14,4 @@ api_router.include_router(player.router, tags=["player"])
api_router.include_router(playlists.router, tags=["playlists"]) api_router.include_router(playlists.router, tags=["playlists"])
api_router.include_router(socket.router, tags=["socket"]) api_router.include_router(socket.router, tags=["socket"])
api_router.include_router(sounds.router, tags=["sounds"]) api_router.include_router(sounds.router, tags=["sounds"])
api_router.include_router(admin.router)

View File

@@ -0,0 +1,10 @@
"""Admin API endpoints."""
from fastapi import APIRouter
from app.api.v1.admin import sounds
router = APIRouter(prefix="/admin")
# Include all admin sub-routers
router.include_router(sounds.router)

235
app/api/v1/admin/sounds.py Normal file
View File

@@ -0,0 +1,235 @@
"""Admin sound management API endpoints."""
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlmodel.ext.asyncio.session import AsyncSession
from app.core.database import get_db
from app.core.dependencies import get_admin_user
from app.models.user import User
from app.services.extraction_processor import extraction_processor
from app.services.sound_normalizer import NormalizationResults, SoundNormalizerService
from app.services.sound_scanner import ScanResults, SoundScannerService
router = APIRouter(prefix="/sounds", tags=["admin-sounds"])
async def get_sound_scanner_service(
session: Annotated[AsyncSession, Depends(get_db)],
) -> SoundScannerService:
"""Get the sound scanner service."""
return SoundScannerService(session)
async def get_sound_normalizer_service(
session: Annotated[AsyncSession, Depends(get_db)],
) -> SoundNormalizerService:
"""Get the sound normalizer service."""
return SoundNormalizerService(session)
# SCAN ENDPOINTS
@router.post("/scan")
async def scan_sounds(
current_user: Annotated[User, Depends(get_admin_user)],
scanner_service: Annotated[SoundScannerService, Depends(get_sound_scanner_service)],
) -> dict[str, ScanResults | str]:
"""Sync the soundboard directory (add/update/delete sounds). Admin only."""
try:
results = await scanner_service.scan_soundboard_directory()
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to sync sounds: {e!s}",
) from e
else:
return {
"message": "Sound sync completed",
"results": results,
}
@router.post("/scan/custom")
async def scan_custom_directory(
directory: str,
current_user: Annotated[User, Depends(get_admin_user)],
scanner_service: Annotated[SoundScannerService, Depends(get_sound_scanner_service)],
sound_type: str = "SDB",
) -> dict[str, ScanResults | str]:
"""Sync a custom directory with the database (add/update/delete sounds). Admin only."""
try:
results = await scanner_service.scan_directory(directory, sound_type)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
) from e
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to sync directory: {e!s}",
) from e
else:
return {
"message": f"Sync of directory '{directory}' completed",
"results": results,
}
# NORMALIZE ENDPOINTS
@router.post("/normalize/all")
async def normalize_all_sounds(
current_user: Annotated[User, Depends(get_admin_user)],
normalizer_service: Annotated[
SoundNormalizerService,
Depends(get_sound_normalizer_service),
],
force: Annotated[
bool,
Query( # noqa: FBT002
description="Force normalization of already normalized sounds",
),
] = False,
one_pass: Annotated[
bool | None,
Query(
description="Use one-pass normalization (overrides config)",
),
] = None,
) -> dict[str, NormalizationResults | str]:
"""Normalize all unnormalized sounds. Admin only."""
try:
results = await normalizer_service.normalize_all_sounds(
force=force,
one_pass=one_pass,
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to normalize sounds: {e!s}",
) from e
else:
return {
"message": "Sound normalization completed",
"results": results,
}
@router.post("/normalize/type/{sound_type}")
async def normalize_sounds_by_type(
sound_type: str,
current_user: Annotated[User, Depends(get_admin_user)],
normalizer_service: Annotated[
SoundNormalizerService,
Depends(get_sound_normalizer_service),
],
force: Annotated[
bool,
Query( # noqa: FBT002
description="Force normalization of already normalized sounds",
),
] = False,
one_pass: Annotated[
bool | None,
Query(
description="Use one-pass normalization (overrides config)",
),
] = None,
) -> dict[str, NormalizationResults | str]:
"""Normalize all sounds of a specific type (SDB, TTS, EXT). Admin only."""
# Validate sound type
valid_types = ["SDB", "TTS", "EXT"]
if sound_type not in valid_types:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Invalid sound type. Must be one of: {', '.join(valid_types)}",
)
try:
results = await normalizer_service.normalize_sounds_by_type(
sound_type=sound_type,
force=force,
one_pass=one_pass,
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to normalize {sound_type} sounds: {e!s}",
) from e
else:
return {
"message": f"Normalization of {sound_type} sounds completed",
"results": results,
}
@router.post("/normalize/{sound_id}")
async def normalize_sound_by_id(
sound_id: int,
current_user: Annotated[User, Depends(get_admin_user)],
normalizer_service: Annotated[
SoundNormalizerService,
Depends(get_sound_normalizer_service),
],
force: Annotated[
bool,
Query( # noqa: FBT002
description="Force normalization of already normalized sound",
),
] = False,
one_pass: Annotated[
bool | None,
Query(
description="Use one-pass normalization (overrides config)",
),
] = None,
) -> dict[str, str]:
"""Normalize a specific sound by ID. Admin only."""
try:
# Get the sound
sound = await normalizer_service.sound_repo.get_by_id(sound_id)
if not sound:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Sound with ID {sound_id} not found",
)
# Normalize the sound
result = await normalizer_service.normalize_sound(
sound=sound,
force=force,
one_pass=one_pass,
)
# Check result status
if result["status"] == "error":
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to normalize sound: {result['error']}",
)
return {
"message": f"Sound normalization {result['status']}: {sound.filename}",
"status": result["status"],
"reason": result["reason"] or "",
"normalized_filename": result["normalized_filename"] or "",
}
except HTTPException:
# Re-raise HTTPExceptions without wrapping them
raise
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to normalize sound: {e!s}",
) from e
# EXTRACTION PROCESSOR STATUS
@router.get("/extract/status")
async def get_extraction_processor_status(
current_user: Annotated[User, Depends(get_admin_user)], # noqa: ARG001
) -> dict:
"""Get the status of the extraction processor. Admin only."""
return extraction_processor.get_status()

View File

@@ -62,11 +62,11 @@ async def get_main_playlist(
@router.get("/current") @router.get("/current")
async def get_current_playlist( async def get_current_playlist(
current_user: Annotated[User, Depends(get_current_active_user_flexible)], current_user: Annotated[User, Depends(get_current_active_user_flexible)], # noqa: ARG001
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)], playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistResponse: ) -> PlaylistResponse:
"""Get the user's current playlist (falls back to main playlist).""" """Get the global current playlist (falls back to main playlist)."""
playlist = await playlist_service.get_current_playlist(current_user.id) playlist = await playlist_service.get_current_playlist()
return PlaylistResponse.from_playlist(playlist) return PlaylistResponse.from_playlist(playlist)
@@ -105,13 +105,19 @@ async def update_playlist(
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)], playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistResponse: ) -> PlaylistResponse:
"""Update a playlist.""" """Update a playlist."""
if current_user.id is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User ID not available",
)
playlist = await playlist_service.update_playlist( playlist = await playlist_service.update_playlist(
playlist_id=playlist_id, playlist_id=playlist_id,
user_id=current_user.id, user_id=current_user.id,
name=request.name, name=request.name,
description=request.description, description=request.description,
genre=request.genre, genre=request.genre,
is_current=request.is_current, is_current=None, # is_current is not handled by this endpoint
) )
return PlaylistResponse.from_playlist(playlist) return PlaylistResponse.from_playlist(playlist)
@@ -212,21 +218,21 @@ async def reorder_playlist_sounds(
@router.put("/{playlist_id}/set-current") @router.put("/{playlist_id}/set-current")
async def set_current_playlist( async def set_current_playlist(
playlist_id: int, playlist_id: int,
current_user: Annotated[User, Depends(get_current_active_user_flexible)], current_user: Annotated[User, Depends(get_current_active_user_flexible)], # noqa: ARG001
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)], playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> PlaylistResponse: ) -> PlaylistResponse:
"""Set a playlist as the current playlist.""" """Set a playlist as the current playlist."""
playlist = await playlist_service.set_current_playlist(playlist_id, current_user.id) playlist = await playlist_service.set_current_playlist(playlist_id)
return PlaylistResponse.from_playlist(playlist) return PlaylistResponse.from_playlist(playlist)
@router.delete("/current") @router.delete("/current")
async def unset_current_playlist( async def unset_current_playlist(
current_user: Annotated[User, Depends(get_current_active_user_flexible)], current_user: Annotated[User, Depends(get_current_active_user_flexible)], # noqa: ARG001
playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)], playlist_service: Annotated[PlaylistService, Depends(get_playlist_service)],
) -> MessageResponse: ) -> MessageResponse:
"""Unset the current playlist.""" """Unset the current playlist."""
await playlist_service.unset_current_playlist(current_user.id) await playlist_service.unset_current_playlist()
return MessageResponse(message="Current playlist unset successfully") return MessageResponse(message="Current playlist unset successfully")

View File

@@ -13,26 +13,11 @@ from app.repositories.sound import SoundRepository
from app.services.credit import CreditService, InsufficientCreditsError from app.services.credit import CreditService, InsufficientCreditsError
from app.services.extraction import ExtractionInfo, ExtractionService from app.services.extraction import ExtractionInfo, ExtractionService
from app.services.extraction_processor import extraction_processor from app.services.extraction_processor import extraction_processor
from app.services.sound_normalizer import NormalizationResults, SoundNormalizerService
from app.services.sound_scanner import ScanResults, SoundScannerService
from app.services.vlc_player import VLCPlayerService, get_vlc_player_service from app.services.vlc_player import VLCPlayerService, get_vlc_player_service
router = APIRouter(prefix="/sounds", tags=["sounds"]) router = APIRouter(prefix="/sounds", tags=["sounds"])
async def get_sound_scanner_service(
session: Annotated[AsyncSession, Depends(get_db)],
) -> SoundScannerService:
"""Get the sound scanner service."""
return SoundScannerService(session)
async def get_sound_normalizer_service(
session: Annotated[AsyncSession, Depends(get_db)],
) -> SoundNormalizerService:
"""Get the sound normalizer service."""
return SoundNormalizerService(session)
async def get_extraction_service( async def get_extraction_service(
session: Annotated[AsyncSession, Depends(get_db)], session: Annotated[AsyncSession, Depends(get_db)],
@@ -58,216 +43,6 @@ async def get_sound_repository(
return SoundRepository(session) return SoundRepository(session)
# SCAN
@router.post("/scan")
async def scan_sounds(
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
scanner_service: Annotated[SoundScannerService, Depends(get_sound_scanner_service)],
) -> dict[str, ScanResults | str]:
"""Sync the soundboard directory (add/update/delete sounds)."""
# Only allow admins to scan sounds
if current_user.role not in ["admin", "superadmin"]:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only administrators can sync sounds",
)
try:
results = await scanner_service.scan_soundboard_directory()
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to sync sounds: {e!s}",
) from e
else:
return {
"message": "Sound sync completed",
"results": results,
}
@router.post("/scan/custom")
async def scan_custom_directory(
directory: str,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
scanner_service: Annotated[SoundScannerService, Depends(get_sound_scanner_service)],
sound_type: str = "SDB",
) -> dict[str, ScanResults | str]:
"""Sync a custom directory with the database (add/update/delete sounds)."""
# Only allow admins to sync sounds
if current_user.role not in ["admin", "superadmin"]:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only administrators can sync sounds",
)
try:
results = await scanner_service.scan_directory(directory, sound_type)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
) from e
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to sync directory: {e!s}",
) from e
else:
return {
"message": f"Sync of directory '{directory}' completed",
"results": results,
}
# NORMALIZE
@router.post("/normalize/all")
async def normalize_all_sounds(
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
normalizer_service: Annotated[
SoundNormalizerService, Depends(get_sound_normalizer_service),
],
force: Annotated[bool, Query( # noqa: FBT002
description="Force normalization of already normalized sounds",
)] = False,
one_pass: Annotated[bool | None, Query(
description="Use one-pass normalization (overrides config)",
)] = None,
) -> dict[str, NormalizationResults | str]:
"""Normalize all unnormalized sounds."""
# Only allow admins to normalize sounds
if current_user.role not in ["admin", "superadmin"]:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only administrators can normalize sounds",
)
try:
results = await normalizer_service.normalize_all_sounds(
force=force,
one_pass=one_pass,
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to normalize sounds: {e!s}",
) from e
else:
return {
"message": "Sound normalization completed",
"results": results,
}
@router.post("/normalize/type/{sound_type}")
async def normalize_sounds_by_type(
sound_type: str,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
normalizer_service: Annotated[
SoundNormalizerService, Depends(get_sound_normalizer_service),
],
force: Annotated[bool, Query( # noqa: FBT002
description="Force normalization of already normalized sounds",
)] = False,
one_pass: Annotated[bool | None, Query(
description="Use one-pass normalization (overrides config)",
)] = None,
) -> dict[str, NormalizationResults | str]:
"""Normalize all sounds of a specific type (SDB, TTS, EXT)."""
# Only allow admins to normalize sounds
if current_user.role not in ["admin", "superadmin"]:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only administrators can normalize sounds",
)
# Validate sound type
valid_types = ["SDB", "TTS", "EXT"]
if sound_type not in valid_types:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Invalid sound type. Must be one of: {', '.join(valid_types)}",
)
try:
results = await normalizer_service.normalize_sounds_by_type(
sound_type=sound_type,
force=force,
one_pass=one_pass,
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to normalize {sound_type} sounds: {e!s}",
) from e
else:
return {
"message": f"Normalization of {sound_type} sounds completed",
"results": results,
}
@router.post("/normalize/{sound_id}")
async def normalize_sound_by_id(
sound_id: int,
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
normalizer_service: Annotated[
SoundNormalizerService, Depends(get_sound_normalizer_service),
],
force: Annotated[bool, Query( # noqa: FBT002
description="Force normalization of already normalized sound",
)] = False,
one_pass: Annotated[bool | None, Query(
description="Use one-pass normalization (overrides config)",
)] = None,
) -> dict[str, str]:
"""Normalize a specific sound by ID."""
# Only allow admins to normalize sounds
if current_user.role not in ["admin", "superadmin"]:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only administrators can normalize sounds",
)
try:
# Get the sound
sound = await normalizer_service.sound_repo.get_by_id(sound_id)
if not sound:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Sound with ID {sound_id} not found",
)
# Normalize the sound
result = await normalizer_service.normalize_sound(
sound=sound,
force=force,
one_pass=one_pass,
)
# Check result status
if result["status"] == "error":
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to normalize sound: {result['error']}",
)
return {
"message": f"Sound normalization {result['status']}: {sound.filename}",
"status": result["status"],
"reason": result["reason"] or "",
"normalized_filename": result["normalized_filename"] or "",
}
except HTTPException:
# Re-raise HTTPExceptions without wrapping them
raise
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to normalize sound: {e!s}",
) from e
# EXTRACT # EXTRACT
@router.post("/extract") @router.post("/extract")
@@ -308,19 +83,6 @@ async def create_extraction(
} }
@router.get("/extract/status")
async def get_extraction_processor_status(
current_user: Annotated[User, Depends(get_current_active_user_flexible)],
) -> dict:
"""Get the status of the extraction processor."""
# Only allow admins to see processor status
if current_user.role not in ["admin", "superadmin"]:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only administrators can view processor status",
)
return extraction_processor.get_status()
@router.get("/extract/{extraction_id}") @router.get("/extract/{extraction_id}")
@@ -377,7 +139,7 @@ async def get_user_extractions(
# VLC PLAYER # VLC PLAYER
@router.post("/vlc/play/{sound_id}") @router.post("/play/{sound_id}")
async def play_sound_with_vlc( async def play_sound_with_vlc(
sound_id: int, sound_id: int,
current_user: Annotated[User, Depends(get_current_active_user_flexible)], current_user: Annotated[User, Depends(get_current_active_user_flexible)],
@@ -445,7 +207,7 @@ async def play_sound_with_vlc(
@router.post("/vlc/stop-all") @router.post("/stop")
async def stop_all_vlc_instances( async def stop_all_vlc_instances(
current_user: Annotated[User, Depends(get_current_active_user_flexible)], # noqa: ARG001 current_user: Annotated[User, Depends(get_current_active_user_flexible)], # noqa: ARG001
vlc_player: Annotated[VLCPlayerService, Depends(get_vlc_player)], vlc_player: Annotated[VLCPlayerService, Depends(get_vlc_player)],

View File

@@ -53,17 +53,16 @@ class PlaylistRepository(BaseRepository[Playlist]):
logger.exception("Failed to get main playlist") logger.exception("Failed to get main playlist")
raise raise
async def get_current_playlist(self, user_id: int) -> Playlist | None: async def get_current_playlist(self) -> Playlist | None:
"""Get the user's current playlist.""" """Get the global current playlist (app-wide)."""
try: try:
statement = select(Playlist).where( statement = select(Playlist).where(
Playlist.user_id == user_id,
Playlist.is_current == True, # noqa: E712 Playlist.is_current == True, # noqa: E712
) )
result = await self.session.exec(statement) result = await self.session.exec(statement)
return result.first() return result.first()
except Exception: except Exception:
logger.exception("Failed to get current playlist for user: %s", user_id) logger.exception("Failed to get current playlist")
raise raise
async def search_by_name( async def search_by_name(
@@ -166,6 +165,20 @@ class PlaylistRepository(BaseRepository[Playlist]):
""" """
try: try:
# Phase 1: Set all positions to temporary negative values to avoid conflicts
temp_offset = -10000 # Use large negative number to avoid conflicts
for i, (sound_id, _) in enumerate(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 = temp_offset + i
# Phase 2: Set the final positions
for sound_id, new_position in sound_positions: for sound_id, new_position in sound_positions:
statement = select(PlaylistSound).where( statement = select(PlaylistSound).where(
PlaylistSound.playlist_id == playlist_id, PlaylistSound.playlist_id == playlist_id,

View File

@@ -189,9 +189,7 @@ class PlayerService:
await self._broadcast_state() await self._broadcast_state()
sound_name = ( sound_name = (
self.state.current_sound.name self.state.current_sound.name if self.state.current_sound else "Unknown"
if self.state.current_sound
else "Unknown"
) )
logger.info("Resumed playing sound: %s", sound_name) logger.info("Resumed playing sound: %s", sound_name)
else: else:
@@ -388,7 +386,7 @@ class PlayerService:
session = self.db_session_factory() session = self.db_session_factory()
try: try:
playlist_repo = PlaylistRepository(session) playlist_repo = PlaylistRepository(session)
current_playlist = await playlist_repo.get_main_playlist() current_playlist = await playlist_repo.get_current_playlist()
if current_playlist and current_playlist.id: if current_playlist and current_playlist.id:
sounds = await playlist_repo.get_playlist_sounds(current_playlist.id) sounds = await playlist_repo.get_playlist_sounds(current_playlist.id)

View File

@@ -14,6 +14,33 @@ from app.repositories.sound import SoundRepository
logger = get_logger(__name__) logger = get_logger(__name__)
async def _reload_player_playlist() -> None:
"""Reload the player playlist after current playlist changes."""
try:
# Import here to avoid circular import issues
from app.services.player import get_player_service # noqa: PLC0415
player = get_player_service()
await player.reload_playlist()
logger.debug("Player playlist reloaded after current playlist change")
except Exception: # noqa: BLE001
# Don't fail the playlist operation if player reload fails
logger.warning("Failed to reload player playlist", exc_info=True)
async def _is_current_playlist(session: AsyncSession, playlist_id: int) -> bool:
"""Check if the given playlist is the current playlist."""
try:
from app.repositories.playlist import PlaylistRepository # noqa: PLC0415
playlist_repo = PlaylistRepository(session)
current_playlist = await playlist_repo.get_current_playlist()
return current_playlist is not None and current_playlist.id == playlist_id
except Exception: # noqa: BLE001
logger.warning("Failed to check if playlist is current", exc_info=True)
return False
class PlaylistService: class PlaylistService:
"""Service for playlist operations.""" """Service for playlist operations."""
@@ -54,9 +81,9 @@ class PlaylistService:
return main_playlist return main_playlist
async def get_current_playlist(self, user_id: int) -> Playlist: async def get_current_playlist(self) -> Playlist:
"""Get the user's current playlist, fallback to main playlist.""" """Get the global current playlist, fallback to main playlist."""
current_playlist = await self.playlist_repo.get_current_playlist(user_id) current_playlist = await self.playlist_repo.get_current_playlist()
if current_playlist: if current_playlist:
return current_playlist return current_playlist
@@ -85,7 +112,7 @@ class PlaylistService:
# If this is set as current, unset the previous current playlist # If this is set as current, unset the previous current playlist
if is_current: if is_current:
await self._unset_current_playlist(user_id) await self._unset_current_playlist()
playlist_data = { playlist_data = {
"user_id": user_id, "user_id": user_id,
@@ -99,6 +126,11 @@ class PlaylistService:
playlist = await self.playlist_repo.create(playlist_data) playlist = await self.playlist_repo.create(playlist_data)
logger.info("Created playlist '%s' for user %s", name, user_id) logger.info("Created playlist '%s' for user %s", name, user_id)
# If this was set as current, reload player playlist
if is_current:
await _reload_player_playlist()
return playlist return playlist
async def update_playlist( # noqa: PLR0913 async def update_playlist( # noqa: PLR0913
@@ -138,13 +170,17 @@ class PlaylistService:
if is_current is not None: if is_current is not None:
if is_current: if is_current:
await self._unset_current_playlist(user_id) await self._unset_current_playlist()
update_data["is_current"] = is_current update_data["is_current"] = is_current
if update_data: if update_data:
playlist = await self.playlist_repo.update(playlist, update_data) playlist = await self.playlist_repo.update(playlist, update_data)
logger.info("Updated playlist %s for user %s", playlist_id, user_id) logger.info("Updated playlist %s for user %s", playlist_id, user_id)
# If is_current was changed, reload player playlist
if "is_current" in update_data:
await _reload_player_playlist()
return playlist return playlist
async def delete_playlist(self, playlist_id: int, user_id: int) -> None: async def delete_playlist(self, playlist_id: int, user_id: int) -> None:
@@ -157,15 +193,15 @@ class PlaylistService:
detail="This playlist cannot be deleted", detail="This playlist cannot be deleted",
) )
# Check if this is the current playlist # Check if this was the current playlist before deleting
was_current = playlist.is_current was_current = playlist.is_current
await self.playlist_repo.delete(playlist) await self.playlist_repo.delete(playlist)
logger.info("Deleted playlist %s for user %s", playlist_id, user_id) logger.info("Deleted playlist %s for user %s", playlist_id, user_id)
# If the deleted playlist was current, set main playlist as current # If the deleted playlist was current, reload player to use main playlist fallback
if was_current: if was_current:
await self._set_main_as_current(user_id) await _reload_player_playlist()
async def search_playlists(self, query: str, user_id: int) -> list[Playlist]: async def search_playlists(self, query: str, user_id: int) -> list[Playlist]:
"""Search user's playlists by name.""" """Search user's playlists by name."""
@@ -214,6 +250,10 @@ class PlaylistService:
user_id, user_id,
) )
# If this is the current playlist, reload player
if await _is_current_playlist(self.session, playlist_id):
await _reload_player_playlist()
async def remove_sound_from_playlist( async def remove_sound_from_playlist(
self, self,
playlist_id: int, playlist_id: int,
@@ -239,6 +279,10 @@ class PlaylistService:
user_id, user_id,
) )
# If this is the current playlist, reload player
if await _is_current_playlist(self.session, playlist_id):
await _reload_player_playlist()
async def reorder_playlist_sounds( async def reorder_playlist_sounds(
self, self,
playlist_id: int, playlist_id: int,
@@ -260,26 +304,9 @@ class PlaylistService:
await self.playlist_repo.reorder_playlist_sounds(playlist_id, sound_positions) 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) 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: # If this is the current playlist, reload player
"""Set a playlist as the current playlist.""" if await _is_current_playlist(self.session, playlist_id):
playlist = await self.get_playlist_by_id(playlist_id) await _reload_player_playlist()
# 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]: async def get_playlist_stats(self, playlist_id: int) -> dict[str, Any]:
"""Get statistics for a playlist.""" """Get statistics for a playlist."""
@@ -305,30 +332,52 @@ class PlaylistService:
msg = "Main playlist has no ID, cannot add sound" msg = "Main playlist has no ID, cannot add sound"
raise ValueError(msg) raise ValueError(msg)
# Extract ID before async operations to avoid session issues
main_playlist_id = main_playlist.id
# Check if sound is already in main playlist # Check if sound is already in main playlist
if not await self.playlist_repo.is_sound_in_playlist( if not await self.playlist_repo.is_sound_in_playlist(
main_playlist.id, main_playlist_id,
sound_id, sound_id,
): ):
await self.playlist_repo.add_sound_to_playlist(main_playlist.id, sound_id) await self.playlist_repo.add_sound_to_playlist(main_playlist_id, sound_id)
logger.info( logger.info(
"Added sound %s to main playlist for user %s", "Added sound %s to main playlist for user %s",
sound_id, sound_id,
user_id, user_id,
) )
async def _unset_current_playlist(self, user_id: int) -> None: # If main playlist is current, reload player
"""Unset the current playlist for a user.""" if await _is_current_playlist(self.session, main_playlist_id):
current_playlist = await self.playlist_repo.get_current_playlist(user_id) await _reload_player_playlist()
# Current playlist methods (global by default)
async def set_current_playlist(self, playlist_id: int) -> Playlist:
"""Set a playlist as the current playlist (app-wide)."""
playlist = await self.get_playlist_by_id(playlist_id)
# Unset any existing current playlist globally
await self._unset_current_playlist()
# Set new current playlist
playlist = await self.playlist_repo.update(playlist, {"is_current": True})
logger.info("Set playlist %s as current playlist", playlist_id)
# Reload player playlist to reflect the change
await _reload_player_playlist()
return playlist
async def unset_current_playlist(self) -> None:
"""Unset the current playlist (main playlist becomes fallback)."""
await self._unset_current_playlist()
logger.info("Unset current playlist, main playlist is now fallback")
# Reload player playlist to reflect the change (will fallback to main)
await _reload_player_playlist()
async def _unset_current_playlist(self) -> None:
"""Unset any current playlist globally."""
current_playlist = await self.playlist_repo.get_current_playlist()
if current_playlist: if current_playlist:
await self.playlist_repo.update(current_playlist, {"is_current": False}) 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

@@ -0,0 +1 @@
"""Tests for admin API endpoints."""

View File

@@ -0,0 +1,554 @@
"""Tests for admin sound API endpoints."""
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from httpx import ASGITransport, AsyncClient
from app.models.user import User
if TYPE_CHECKING:
from app.services.sound_normalizer import NormalizationResults
from app.services.sound_scanner import ScanResults
class TestAdminSoundEndpoints:
"""Test admin sound API endpoints."""
@pytest.mark.asyncio
async def test_scan_sounds_success(
self,
authenticated_admin_client: AsyncClient,
admin_user: User,
) -> None:
"""Test successful sound scanning."""
# Mock the scanner service to return successful results
mock_results: ScanResults = {
"scanned": 5,
"added": 3,
"updated": 1,
"deleted": 1,
"skipped": 0,
"errors": 0,
"files": [
{
"filename": "test1.mp3",
"status": "added",
"reason": None,
"name": "Test1",
"duration": 5000,
"size": 1024,
"id": 1,
"error": None,
"changes": None,
},
{
"filename": "test2.mp3",
"status": "updated",
"reason": "file was modified",
"name": "Test2",
"duration": 7500,
"size": 2048,
"id": 2,
"error": None,
"changes": ["hash", "duration", "size"],
},
{
"filename": "test3.mp3",
"status": "deleted",
"reason": "file no longer exists",
"name": "Test3",
"duration": 3000,
"size": 512,
"id": 3,
"error": None,
"changes": None,
},
],
}
with patch(
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory",
) as mock_scan:
mock_scan.return_value = mock_results
response = await authenticated_admin_client.post("/api/v1/admin/sounds/scan")
assert response.status_code == 200
data = response.json()
assert "message" in data
assert "Sound sync completed" in data["message"]
assert "results" in data
results = data["results"]
assert results["scanned"] == 5
assert results["added"] == 3
assert results["updated"] == 1
assert results["deleted"] == 1
assert results["skipped"] == 0
assert results["errors"] == 0
assert len(results["files"]) == 3
# Check file details
assert results["files"][0]["filename"] == "test1.mp3"
assert results["files"][0]["status"] == "added"
assert results["files"][1]["status"] == "updated"
assert results["files"][2]["status"] == "deleted"
@pytest.mark.asyncio
async def test_scan_sounds_unauthenticated(self, client: AsyncClient) -> None:
"""Test scanning sounds without authentication."""
response = await client.post("/api/v1/admin/sounds/scan")
assert response.status_code == 401
data = response.json()
assert "Could not validate credentials" in data["detail"]
@pytest.mark.asyncio
async def test_scan_sounds_non_admin(
self,
test_app,
test_user: User,
) -> None:
"""Test scanning sounds with non-admin user."""
from fastapi import HTTPException
from app.core.dependencies import get_admin_user
# Override the admin dependency to raise 403 for non-admin users
async def override_get_admin_user():
raise HTTPException(status_code=403, detail="Not enough permissions")
test_app.dependency_overrides[get_admin_user] = override_get_admin_user
# Create API token for regular user
headers = {"API-TOKEN": "test_api_token"}
async with AsyncClient(
transport=ASGITransport(app=test_app),
base_url="http://test",
) as client:
response = await client.post("/api/v1/admin/sounds/scan", headers=headers)
assert response.status_code == 403
data = response.json()
assert "Not enough permissions" in data["detail"]
# Clean up override
test_app.dependency_overrides.pop(get_admin_user, None)
@pytest.mark.asyncio
async def test_scan_sounds_service_error(
self,
authenticated_admin_client: AsyncClient,
admin_user: User,
) -> None:
"""Test scanning sounds when service raises an error."""
with patch(
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory",
) as mock_scan:
mock_scan.side_effect = Exception("Directory not found")
response = await authenticated_admin_client.post("/api/v1/admin/sounds/scan")
assert response.status_code == 500
data = response.json()
assert "Failed to sync sounds" in data["detail"]
assert "Directory not found" in data["detail"]
@pytest.mark.asyncio
async def test_scan_custom_directory_success(
self,
authenticated_admin_client: AsyncClient,
admin_user: User,
) -> None:
"""Test successful custom directory scanning."""
mock_results: ScanResults = {
"scanned": 2,
"added": 2,
"updated": 0,
"deleted": 0,
"skipped": 0,
"errors": 0,
"files": [
{
"filename": "custom1.wav",
"status": "added",
"reason": None,
"name": "Custom1",
"duration": 4000,
"size": 800,
"id": 10,
"error": None,
"changes": None,
},
{
"filename": "custom2.wav",
"status": "added",
"reason": None,
"name": "Custom2",
"duration": 6000,
"size": 1200,
"id": 11,
"error": None,
"changes": None,
},
],
}
with patch(
"app.services.sound_scanner.SoundScannerService.scan_directory",
) as mock_scan:
mock_scan.return_value = mock_results
response = await authenticated_admin_client.post(
"/api/v1/admin/sounds/scan/custom",
params={"directory": "/custom/path", "sound_type": "CUSTOM"},
)
assert response.status_code == 200
data = response.json()
assert "Sync of directory '/custom/path' completed" in data["message"]
assert "results" in data
results = data["results"]
assert results["scanned"] == 2
assert results["added"] == 2
assert len(results["files"]) == 2
# Verify the service was called with correct parameters
mock_scan.assert_called_once_with("/custom/path", "CUSTOM")
@pytest.mark.asyncio
async def test_normalize_all_sounds_success(
self,
authenticated_admin_client: AsyncClient,
admin_user: User,
) -> None:
"""Test successful normalization of all sounds."""
mock_results: NormalizationResults = {
"processed": 3,
"normalized": 2,
"skipped": 1,
"errors": 0,
"files": [
{
"filename": "test1.mp3",
"status": "normalized",
"reason": None,
"original_path": "/fake/test1.mp3",
"normalized_path": "/fake/test1_normalized.mp3",
"normalized_filename": "test1_normalized.mp3",
"normalized_duration": 5000,
"normalized_size": 1024,
"normalized_hash": "norm_hash1",
"id": 1,
"error": None,
},
{
"filename": "test2.wav",
"status": "normalized",
"reason": None,
"original_path": "/fake/test2.wav",
"normalized_path": "/fake/test2_normalized.mp3",
"normalized_filename": "test2_normalized.mp3",
"normalized_duration": 7000,
"normalized_size": 2048,
"normalized_hash": "norm_hash2",
"id": 2,
"error": None,
},
{
"filename": "test3.mp3",
"status": "skipped",
"reason": "already normalized",
"original_path": None,
"normalized_path": None,
"normalized_filename": None,
"normalized_duration": None,
"normalized_size": None,
"normalized_hash": None,
"id": 3,
"error": None,
},
],
}
with patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_all_sounds",
) as mock_normalize:
mock_normalize.return_value = mock_results
response = await authenticated_admin_client.post(
"/api/v1/admin/sounds/normalize/all",
)
assert response.status_code == 200
data = response.json()
assert "message" in data
assert "Sound normalization completed" in data["message"]
assert "results" in data
results = data["results"]
assert results["processed"] == 3
assert results["normalized"] == 2
assert results["skipped"] == 1
assert results["errors"] == 0
assert len(results["files"]) == 3
@pytest.mark.asyncio
async def test_normalize_all_sounds_unauthenticated(self, client: AsyncClient) -> None:
"""Test normalizing sounds without authentication."""
response = await client.post("/api/v1/admin/sounds/normalize/all")
assert response.status_code == 401
data = response.json()
assert "Could not validate credentials" in data["detail"]
@pytest.mark.asyncio
async def test_normalize_all_sounds_non_admin(
self,
test_app,
test_user: User,
) -> None:
"""Test normalizing sounds with non-admin user."""
from fastapi import HTTPException
from app.core.dependencies import get_admin_user
# Override the admin dependency to raise 403 for non-admin users
async def override_get_admin_user():
raise HTTPException(status_code=403, detail="Not enough permissions")
test_app.dependency_overrides[get_admin_user] = override_get_admin_user
headers = {"API-TOKEN": "test_api_token"}
async with AsyncClient(
transport=ASGITransport(app=test_app),
base_url="http://test",
) as client:
response = await client.post(
"/api/v1/admin/sounds/normalize/all", headers=headers,
)
assert response.status_code == 403
data = response.json()
assert "Not enough permissions" in data["detail"]
# Clean up override
test_app.dependency_overrides.pop(get_admin_user, None)
@pytest.mark.asyncio
async def test_normalize_sounds_by_type_success(
self,
authenticated_admin_client: AsyncClient,
admin_user: User,
) -> None:
"""Test successful normalization by sound type."""
mock_results: NormalizationResults = {
"processed": 2,
"normalized": 2,
"skipped": 0,
"errors": 0,
"files": [
{
"filename": "sdb1.mp3",
"status": "normalized",
"reason": None,
"original_path": "/fake/sdb1.mp3",
"normalized_path": "/fake/sdb1_normalized.mp3",
"normalized_filename": "sdb1_normalized.mp3",
"normalized_duration": 4000,
"normalized_size": 800,
"normalized_hash": "sdb_hash1",
"id": 10,
"error": None,
},
{
"filename": "sdb2.wav",
"status": "normalized",
"reason": None,
"original_path": "/fake/sdb2.wav",
"normalized_path": "/fake/sdb2_normalized.mp3",
"normalized_filename": "sdb2_normalized.mp3",
"normalized_duration": 6000,
"normalized_size": 1200,
"normalized_hash": "sdb_hash2",
"id": 11,
"error": None,
},
],
}
with patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_sounds_by_type",
) as mock_normalize:
mock_normalize.return_value = mock_results
response = await authenticated_admin_client.post(
"/api/v1/admin/sounds/normalize/type/SDB",
)
assert response.status_code == 200
data = response.json()
assert "Normalization of SDB sounds completed" in data["message"]
assert "results" in data
results = data["results"]
assert results["processed"] == 2
assert results["normalized"] == 2
assert len(results["files"]) == 2
# Verify the service was called with correct type
mock_normalize.assert_called_once_with(
sound_type="SDB", force=False, one_pass=None,
)
@pytest.mark.asyncio
async def test_normalize_sounds_by_type_invalid_type(
self,
authenticated_admin_client: AsyncClient,
admin_user: User,
) -> None:
"""Test normalization with invalid sound type."""
response = await authenticated_admin_client.post(
"/api/v1/admin/sounds/normalize/type/INVALID",
)
assert response.status_code == 400
data = response.json()
assert "Invalid sound type" in data["detail"]
assert "Must be one of: SDB, TTS, EXT" in data["detail"]
@pytest.mark.asyncio
async def test_normalize_sound_by_id_success(
self,
authenticated_admin_client: AsyncClient,
admin_user: User,
) -> None:
"""Test successful normalization of a specific sound."""
# Mock the sound
mock_sound = type(
"Sound",
(),
{
"id": 42,
"filename": "specific_sound.mp3",
"type": "SDB",
"name": "Specific Sound",
},
)()
# Mock normalization result
mock_result = {
"filename": "specific_sound.mp3",
"status": "normalized",
"reason": None,
"original_path": "/fake/specific_sound.mp3",
"normalized_path": "/fake/specific_sound_normalized.mp3",
"normalized_filename": "specific_sound_normalized.mp3",
"normalized_duration": 8000,
"normalized_size": 1600,
"normalized_hash": "specific_hash",
"id": 42,
"error": None,
}
with (
patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_sound",
) as mock_normalize_sound,
patch("app.repositories.sound.SoundRepository.get_by_id") as mock_get_sound,
):
mock_get_sound.return_value = mock_sound
mock_normalize_sound.return_value = mock_result
response = await authenticated_admin_client.post(
"/api/v1/admin/sounds/normalize/42",
)
assert response.status_code == 200
data = response.json()
assert "Sound normalization normalized" in data["message"]
assert "specific_sound.mp3" in data["message"]
assert data["status"] == "normalized"
assert data["normalized_filename"] == "specific_sound_normalized.mp3"
# Verify sound was retrieved and normalized
mock_get_sound.assert_called_once_with(42)
mock_normalize_sound.assert_called_once()
@pytest.mark.asyncio
async def test_get_extraction_processor_status(
self,
authenticated_admin_client: AsyncClient,
admin_user: User,
) -> None:
"""Test getting extraction processor status."""
with patch(
"app.services.extraction_processor.extraction_processor.get_status"
) as mock_get_status:
mock_status = {
"is_running": True,
"queue_size": 2,
"active_extractions": 1,
"max_concurrent": 2,
}
mock_get_status.return_value = mock_status
response = await authenticated_admin_client.get(
"/api/v1/admin/sounds/extract/status"
)
assert response.status_code == 200
data = response.json()
assert data == mock_status
@pytest.mark.asyncio
async def test_get_extraction_processor_status_unauthenticated(
self, client: AsyncClient
) -> None:
"""Test getting extraction processor status without authentication."""
response = await client.get("/api/v1/admin/sounds/extract/status")
assert response.status_code == 401
data = response.json()
assert "Could not validate credentials" in data["detail"]
@pytest.mark.asyncio
async def test_get_extraction_processor_status_non_admin(
self,
test_app,
test_user: User,
) -> None:
"""Test getting extraction processor status with non-admin user."""
from fastapi import HTTPException
from app.core.dependencies import get_admin_user
# Override the admin dependency to raise 403 for non-admin users
async def override_get_admin_user():
raise HTTPException(status_code=403, detail="Not enough permissions")
test_app.dependency_overrides[get_admin_user] = override_get_admin_user
headers = {"API-TOKEN": "test_api_token"}
async with AsyncClient(
transport=ASGITransport(app=test_app),
base_url="http://test",
) as client:
response = await client.get(
"/api/v1/admin/sounds/extract/status", headers=headers
)
assert response.status_code == 403
data = response.json()
assert "Not enough permissions" in data["detail"]
# Clean up override
test_app.dependency_overrides.pop(get_admin_user, None)

View File

@@ -45,35 +45,20 @@ class TestExtractionEndpoints:
assert response.status_code == 401 assert response.status_code == 401
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_get_processor_status_admin( async def test_get_processor_status_moved_to_admin(
self, test_client: AsyncClient, admin_cookies: dict[str, str], self, test_client: AsyncClient, admin_cookies: dict[str, str],
) -> None: ) -> None:
"""Test getting processor status as admin.""" """Test that processor status endpoint was moved to admin."""
# Set cookies on client instance to avoid deprecation warning # Set cookies on client instance to avoid deprecation warning
test_client.cookies.update(admin_cookies) test_client.cookies.update(admin_cookies)
response = await test_client.get("/api/v1/sounds/extract/status") # The new admin endpoint should work
response = await test_client.get("/api/v1/admin/sounds/extract/status")
# Should succeed for admin users
assert response.status_code == 200 assert response.status_code == 200
data = response.json() data = response.json()
assert "running" in data assert "running" in data or "is_running" in data
assert "max_concurrent" in data assert "max_concurrent" in data
@pytest.mark.asyncio
async def test_get_processor_status_non_admin(
self, test_client: AsyncClient, auth_cookies: dict[str, str],
) -> None:
"""Test getting processor status as non-admin user."""
# Set cookies on client instance to avoid deprecation warning
test_client.cookies.update(auth_cookies)
response = await test_client.get("/api/v1/sounds/extract/status")
# Should return 403 for non-admin users
assert response.status_code == 403
assert "Only administrators" in response.json()["detail"]
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_get_user_extractions( async def test_get_user_extractions(
self, test_client: AsyncClient, auth_cookies: dict[str, str], self, test_client: AsyncClient, auth_cookies: dict[str, str],

View File

@@ -358,14 +358,14 @@ class TestPlaylistEndpoints:
assert data["genre"] == "jazz" assert data["genre"] == "jazz"
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_update_playlist_set_current( async def test_update_playlist_basic_fields(
self, self,
authenticated_client: AsyncClient, authenticated_client: AsyncClient,
test_session: AsyncSession, test_session: AsyncSession,
test_user: User, test_user: User,
) -> None: ) -> None:
"""Test PUT /api/v1/playlists/{id} - set playlist as current.""" """Test PUT /api/v1/playlists/{id} - update basic fields only."""
# Create test playlists within this test # Create test playlist
user_id = test_user.id user_id = test_user.id
test_playlist = Playlist( test_playlist = Playlist(
user_id=user_id, user_id=user_id,
@@ -377,25 +377,13 @@ class TestPlaylistEndpoints:
is_deletable=True, is_deletable=True,
) )
test_session.add(test_playlist) test_session.add(test_playlist)
# Note: main_playlist doesn't need to be current=True for this test
# The service logic handles current playlist management
main_playlist = Playlist(
user_id=None,
name="Main Playlist",
description="Main playlist",
is_main=True,
is_current=False,
is_deletable=False,
)
test_session.add(main_playlist)
await test_session.commit() await test_session.commit()
await test_session.refresh(test_playlist) await test_session.refresh(test_playlist)
# Extract ID before HTTP request # Extract ID before HTTP request
playlist_id = test_playlist.id playlist_id = test_playlist.id
payload = {"is_current": True} payload = {"name": "Updated Playlist", "description": "Updated description"}
response = await authenticated_client.put( response = await authenticated_client.put(
f"/api/v1/playlists/{playlist_id}", json=payload, f"/api/v1/playlists/{playlist_id}", json=payload,
@@ -403,7 +391,10 @@ class TestPlaylistEndpoints:
assert response.status_code == 200 assert response.status_code == 200
data = response.json() data = response.json()
assert data["is_current"] is True assert data["name"] == "Updated Playlist"
assert data["description"] == "Updated description"
# is_current should remain unchanged (not handled by this endpoint)
assert data["is_current"] is False
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_delete_playlist_success( async def test_delete_playlist_success(

File diff suppressed because it is too large Load Diff

View File

@@ -50,7 +50,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try: try:
response = await authenticated_client.post("/api/v1/sounds/vlc/play/1") response = await authenticated_client.post("/api/v1/sounds/play/1")
assert response.status_code == 200 assert response.status_code == 200
data = response.json() data = response.json()
@@ -89,7 +89,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try: try:
response = await authenticated_client.post("/api/v1/sounds/vlc/play/999") response = await authenticated_client.post("/api/v1/sounds/play/999")
assert response.status_code == 404 assert response.status_code == 404
data = response.json() data = response.json()
@@ -136,7 +136,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try: try:
response = await authenticated_client.post("/api/v1/sounds/vlc/play/1") response = await authenticated_client.post("/api/v1/sounds/play/1")
assert response.status_code == 500 assert response.status_code == 500
data = response.json() data = response.json()
@@ -169,7 +169,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try: try:
response = await authenticated_client.post("/api/v1/sounds/vlc/play/1") response = await authenticated_client.post("/api/v1/sounds/play/1")
assert response.status_code == 500 assert response.status_code == 500
data = response.json() data = response.json()
@@ -186,7 +186,7 @@ class TestVLCEndpoints:
client: AsyncClient, client: AsyncClient,
) -> None: ) -> None:
"""Test VLC playback without authentication.""" """Test VLC playback without authentication."""
response = await client.post("/api/v1/sounds/vlc/play/1") response = await client.post("/api/v1/sounds/play/1")
assert response.status_code == 401 assert response.status_code == 401
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -212,7 +212,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try: try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all") response = await authenticated_client.post("/api/v1/sounds/stop")
assert response.status_code == 200 assert response.status_code == 200
data = response.json() data = response.json()
@@ -250,7 +250,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try: try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all") response = await authenticated_client.post("/api/v1/sounds/stop")
assert response.status_code == 200 assert response.status_code == 200
data = response.json() data = response.json()
@@ -285,7 +285,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try: try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all") response = await authenticated_client.post("/api/v1/sounds/stop")
assert response.status_code == 200 assert response.status_code == 200
data = response.json() data = response.json()
@@ -320,7 +320,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try: try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all") response = await authenticated_client.post("/api/v1/sounds/stop")
assert response.status_code == 200 assert response.status_code == 200
data = response.json() data = response.json()
@@ -347,7 +347,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try: try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all") response = await authenticated_client.post("/api/v1/sounds/stop")
assert response.status_code == 500 assert response.status_code == 500
data = response.json() data = response.json()
@@ -362,7 +362,7 @@ class TestVLCEndpoints:
client: AsyncClient, client: AsyncClient,
) -> None: ) -> None:
"""Test stopping VLC instances without authentication.""" """Test stopping VLC instances without authentication."""
response = await client.post("/api/v1/sounds/vlc/stop-all") response = await client.post("/api/v1/sounds/stop")
assert response.status_code == 401 assert response.status_code == 401
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -401,7 +401,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try: try:
response = await authenticated_admin_client.post("/api/v1/sounds/vlc/play/1") response = await authenticated_admin_client.post("/api/v1/sounds/play/1")
assert response.status_code == 200 assert response.status_code == 200
data = response.json() data = response.json()
@@ -427,7 +427,7 @@ class TestVLCEndpoints:
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service_2 test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service_2
try: try:
response = await authenticated_admin_client.post("/api/v1/sounds/vlc/stop-all") response = await authenticated_admin_client.post("/api/v1/sounds/stop")
assert response.status_code == 200 assert response.status_code == 200
data = response.json() data = response.json()

View File

@@ -222,28 +222,11 @@ class TestPlaylistRepository:
test_session: AsyncSession, test_session: AsyncSession,
ensure_plans: Any, ensure_plans: Any,
) -> None: ) -> None:
"""Test getting current playlist when none is set.""" """Test getting current playlist when none is set globally."""
# Create test user within this test # Test the repository method - should return None when no current playlist is set globally
user = User( playlist = await playlist_repository.get_current_playlist()
email="test2@example.com",
name="Test User 2",
password_hash=PasswordUtils.hash_password("password123"),
role="user",
is_active=True,
plan_id=ensure_plans[0].id,
credits=100,
)
test_session.add(user)
await test_session.commit()
await test_session.refresh(user)
# Extract user ID immediately after refresh # Should return None since no playlist is marked as current globally
user_id = user.id
# Test the repository method - should return None when no current playlist
playlist = await playlist_repository.get_current_playlist(user_id)
# Should return None since no user playlist is marked as current
assert playlist is None assert playlist is None
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -828,3 +811,78 @@ class TestPlaylistRepository:
assert len(sounds) == TWO_SOUNDS assert len(sounds) == TWO_SOUNDS
assert sounds[0].id == sound2_id # sound2 now at position 5 assert sounds[0].id == sound2_id # sound2 now at position 5
assert sounds[1].id == sound1_id # sound1 now at position 10 assert sounds[1].id == sound1_id # sound1 now at position 10
@pytest.mark.asyncio
async def test_reorder_playlist_sounds_position_swap(
self,
playlist_repository: PlaylistRepository,
test_session: AsyncSession,
ensure_plans: Any,
) -> None:
"""Test reordering sounds with position swapping (regression test)."""
# Create objects within this test
user = User(
email="test@example.com",
name="Test User",
password_hash=PasswordUtils.hash_password("password123"),
role="user",
is_active=True,
plan_id=ensure_plans[0].id,
credits=100,
)
test_session.add(user)
await test_session.commit()
await test_session.refresh(user)
user_id = user.id
playlist = Playlist(
user_id=user_id,
name="Test Playlist",
description="A test playlist",
genre="test",
is_main=False,
is_current=False,
is_deletable=True,
)
test_session.add(playlist)
# Create multiple sounds
sound1 = Sound(name="Sound 1", filename="sound1.mp3", type="SDB", hash="hash1")
sound2 = Sound(name="Sound 2", filename="sound2.mp3", type="SDB", hash="hash2")
test_session.add_all([playlist, sound1, sound2])
await test_session.commit()
await test_session.refresh(playlist)
await test_session.refresh(sound1)
await test_session.refresh(sound2)
# Extract IDs before async calls
playlist_id = playlist.id
sound1_id = sound1.id
sound2_id = sound2.id
# Add sounds to playlist at positions 0 and 1
await playlist_repository.add_sound_to_playlist(
playlist_id, sound1_id, position=0,
)
await playlist_repository.add_sound_to_playlist(
playlist_id, sound2_id, position=1,
)
# Verify initial order
sounds = await playlist_repository.get_playlist_sounds(playlist_id)
assert len(sounds) == TWO_SOUNDS
assert sounds[0].id == sound1_id # sound1 at position 0
assert sounds[1].id == sound2_id # sound2 at position 1
# Swap positions - this used to cause unique constraint violation
sound_positions = [(sound1_id, 1), (sound2_id, 0)]
await playlist_repository.reorder_playlist_sounds(
playlist_id, sound_positions,
)
# Verify swapped order
sounds = await playlist_repository.get_playlist_sounds(playlist_id)
assert len(sounds) == TWO_SOUNDS
assert sounds[0].id == sound2_id # sound2 now at position 0
assert sounds[1].id == sound1_id # sound1 now at position 1

View File

@@ -364,7 +364,7 @@ class TestPlayerService:
mock_playlist = Mock() mock_playlist = Mock()
mock_playlist.id = 1 mock_playlist.id = 1
mock_playlist.name = "Test Playlist" mock_playlist.name = "Test Playlist"
mock_repo.get_main_playlist.return_value = mock_playlist mock_repo.get_current_playlist.return_value = mock_playlist # Return current playlist directly
# Mock sounds # Mock sounds
sound1 = Sound(id=1, name="Song 1", filename="song1.mp3", duration=30000) sound1 = Sound(id=1, name="Song 1", filename="song1.mp3", duration=30000)
@@ -562,7 +562,7 @@ class TestPlayerService:
mock_playlist = Mock() mock_playlist = Mock()
mock_playlist.id = 2 # Different ID mock_playlist.id = 2 # Different ID
mock_playlist.name = "New Playlist" mock_playlist.name = "New Playlist"
mock_repo.get_main_playlist.return_value = mock_playlist mock_repo.get_current_playlist.return_value = mock_playlist # Return current playlist directly
sound1 = Sound(id=1, name="Song 1", filename="song1.mp3", duration=30000) sound1 = Sound(id=1, name="Song 1", filename="song1.mp3", duration=30000)
mock_sounds = [sound1] mock_sounds = [sound1]
@@ -597,7 +597,7 @@ class TestPlayerService:
mock_playlist = Mock() mock_playlist = Mock()
mock_playlist.id = 1 mock_playlist.id = 1
mock_playlist.name = "Same Playlist" mock_playlist.name = "Same Playlist"
mock_repo.get_main_playlist.return_value = mock_playlist mock_repo.get_current_playlist.return_value = mock_playlist # Return current playlist directly
# Track 2 moved to index 0 # Track 2 moved to index 0
sound1 = Sound(id=2, name="Song 2", filename="song2.mp3", duration=45000) sound1 = Sound(id=2, name="Song 2", filename="song2.mp3", duration=45000)

View File

@@ -464,7 +464,7 @@ class TestPlaylistService:
# Verify main playlist is now fallback current (main playlist doesn't have is_current=True) # Verify main playlist is now fallback current (main playlist doesn't have is_current=True)
# The service returns main playlist when no current is set # The service returns main playlist when no current is set
current = await playlist_service.get_current_playlist(user_id) current = await playlist_service.get_current_playlist()
assert current.is_main is True assert current.is_main is True
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -754,7 +754,7 @@ class TestPlaylistService:
# Set test_playlist as current # Set test_playlist as current
updated_playlist = await playlist_service.set_current_playlist( updated_playlist = await playlist_service.set_current_playlist(
test_playlist_id, user_id, test_playlist_id,
) )
assert updated_playlist.is_current is True assert updated_playlist.is_current is True
@@ -804,10 +804,10 @@ class TestPlaylistService:
assert current_playlist.is_current is True assert current_playlist.is_current is True
# Unset current playlist # Unset current playlist
await playlist_service.unset_current_playlist(user_id) await playlist_service.unset_current_playlist()
# Verify get_current_playlist returns main playlist as fallback # Verify get_current_playlist returns main playlist as fallback
current = await playlist_service.get_current_playlist(user_id) current = await playlist_service.get_current_playlist()
assert current.id == main_playlist_id assert current.id == main_playlist_id
assert current.is_main is True assert current.is_main is True