Files
Music-site/backend/app/routes/music.py
2026-02-24 21:24:16 +06:00

73 lines
2.1 KiB
Python

from fastapi import APIRouter, Depends, UploadFile, File, Form, HTTPException
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from typing import List
from pydantic import BaseModel
import shutil
import os
from app.database import get_db
from app.models.models import Song, User
from app.auth import get_current_user
router = APIRouter()
class SongResponse(BaseModel):
id: int
title: str
artist: str
file_path: str
cover_path: str | None
duration: int
owner_id: int
class Config:
from_attributes = True
@router.post("/upload")
async def upload_song(
title: str = Form(...),
artist: str = Form(...),
duration: int = Form(...),
file: UploadFile = File(...),
cover: UploadFile = File(None),
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
file_path = f"uploads/music/{current_user.id}_{file.filename}"
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
cover_path = None
if cover:
cover_path = f"uploads/covers/{current_user.id}_{cover.filename}"
with open(cover_path, "wb") as buffer:
shutil.copyfileobj(cover.file, buffer)
song = Song(
title=title,
artist=artist,
file_path=file_path,
cover_path=cover_path,
duration=duration,
owner_id=current_user.id
)
db.add(song)
db.commit()
db.refresh(song)
return song
@router.get("/songs", response_model=List[SongResponse])
def get_songs(db: Session = Depends(get_db)):
return db.query(Song).all()
@router.get("/my-songs", response_model=List[SongResponse])
def get_my_songs(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
return db.query(Song).filter(Song.owner_id == current_user.id).all()
@router.get("/download/{song_id}")
def download_song(song_id: int, db: Session = Depends(get_db)):
song = db.query(Song).filter(Song.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
return FileResponse(song.file_path, filename=f"{song.title}.mp3")