82 lines
2.8 KiB
Python
82 lines
2.8 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from typing import Optional
|
|
from sqlmodel import Session
|
|
from app.db.session import get_session
|
|
from app.models.music import Playlist, PlaylistSong, UserRole
|
|
from app.api.dependencies import RoleChecker, get_current_user
|
|
|
|
router = APIRouter(prefix="/playlists", tags=["playlists"])
|
|
|
|
@router.post("/")
|
|
async def create_playlist(
|
|
name: str,
|
|
description: Optional[str] = None,
|
|
user=Depends(get_current_user),
|
|
session: Session = Depends(get_session)
|
|
):
|
|
playlist = Playlist(name=name, description=description, owner_id=user.id)
|
|
session.add(playlist)
|
|
session.commit()
|
|
session.refresh(playlist)
|
|
return playlist
|
|
|
|
@router.get("/")
|
|
async def list_playlists(
|
|
user=Depends(get_current_user),
|
|
session: Session = Depends(get_session)
|
|
):
|
|
playlists = session.exec(Playlist.select().where(Playlist.owner_id == user.id)).all()
|
|
return playlists
|
|
|
|
@router.post("/{playlist_id}/songs/{song_id}")
|
|
async def add_song_to_playlist(
|
|
playlist_id: int,
|
|
song_id: int,
|
|
user=Depends(get_current_user),
|
|
session: Session = Depends(get_session)
|
|
):
|
|
playlist = session.exec(Playlist.select().where(Playlist.id == playlist_id)).first()
|
|
if not playlist:
|
|
raise HTTPException(status_code=404, detail="Playlist not found")
|
|
|
|
if playlist.owner_id != user.id:
|
|
raise HTTPException(status_code=403, detail="You are not the owner of this playlist")
|
|
|
|
# Check if song exists (simplified)
|
|
from app.models.music import Song
|
|
song = session.exec(Song.select().where(Song.id == song_id)).first()
|
|
if not song:
|
|
raise HTTPException(status_code=404, detail="Song not found")
|
|
|
|
# Prevent duplicates
|
|
existing = session.exec(PlaylistSong.select().where(
|
|
PlaylistSong.playlist_id == playlist_id,
|
|
PlaylistSong.song_id == song_id
|
|
)).first()
|
|
if existing:
|
|
raise HTTPException(status_code=400, detail="Song already in playlist")
|
|
|
|
entry = PlaylistSong(playlist_id=playlist_id, song_id=song_id)
|
|
session.add(entry)
|
|
session.commit()
|
|
return {"message": "Song added to playlist"}
|
|
|
|
@router.get("/{playlist_id}/songs")
|
|
async def get_playlist_songs(
|
|
playlist_id: int,
|
|
session: Session = Depends(get_session)
|
|
):
|
|
entries = session.exec(PlaylistSong.select().where(PlaylistSong.playlist_id == playlist_id)).all()
|
|
from app.models.music import Song
|
|
results = []
|
|
for entry in entries:
|
|
song = session.exec(Song.select().where(Song.id == entry.song_id)).first()
|
|
if song:
|
|
results.append({
|
|
"id": song.id,
|
|
"title": song.title,
|
|
"artist": song.artist.username if song.artist else "Unknown",
|
|
"duration": song.duration
|
|
})
|
|
return results
|