Files
you-music/backend/app/api/api_keys.py
T
junv f7e4686816 Implement the following:* Search function should time out in 1 min if something goes wrong
* Add function tofull-size current playing song through a button in the bottom control panel
* Add an API also a feature in the home page, to allow user type a song name, then create a backend job to auto search and download song in the background, when pick the song from the results, put the result into priority candicdate if the name either has “official song” or “官方”, if the same exact song has been downloaded before, then just put the job as pending to confirm, and let user to confirm, once user confirmed, then the system can download the duplicate song, we need to persist the those jobs, if a job fails, then we mark it failed, and user can retry it later through UI, also add an summary about how to trigger this function through API
* Add API keys section in settings, so we need to evaluate api keys for public APIs
    * Now we only put the auto search and download song into the pubic API
* Add feature in search to search artist, which would return all the matched artists,
* Add sort feature to the artists and library page, like the one we have in playlist detail page
* By default sort the song in the library page by added at desc
2025-10-31 09:17:44 +11:00

117 lines
3.2 KiB
Python

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import List
import secrets
from datetime import datetime, timedelta
from app.db.session import get_db
from app.models.models import APIKey
from app.schemas.schemas import APIKeyCreate, APIKeyResponse
router = APIRouter()
@router.post("/", response_model=APIKeyResponse)
async def create_api_key(
request: APIKeyCreate,
db: AsyncSession = Depends(get_db)
):
"""Create a new API key"""
# Generate secure random key
key = f"ym_{secrets.token_urlsafe(32)}"
# Calculate expiration
expires_at = None
if request.expires_in_days:
expires_at = datetime.utcnow() + timedelta(days=request.expires_in_days)
# Create API key
api_key = APIKey(
key=key,
name=request.name,
description=request.description,
expires_at=expires_at
)
db.add(api_key)
await db.commit()
await db.refresh(api_key)
return api_key
@router.get("/", response_model=List[APIKeyResponse])
async def get_api_keys(
include_inactive: bool = False,
db: AsyncSession = Depends(get_db)
):
"""Get all API keys"""
query = select(APIKey).order_by(APIKey.created_at.desc())
if not include_inactive:
query = query.where(APIKey.is_active == True)
result = await db.execute(query)
keys = result.scalars().all()
return keys
@router.get("/{key_id}", response_model=APIKeyResponse)
async def get_api_key(key_id: int, db: AsyncSession = Depends(get_db)):
"""Get a specific API key"""
result = await db.execute(select(APIKey).where(APIKey.id == key_id))
api_key = result.scalar_one_or_none()
if not api_key:
raise HTTPException(status_code=404, detail="API key not found")
return api_key
@router.delete("/{key_id}")
async def delete_api_key(key_id: int, db: AsyncSession = Depends(get_db)):
"""Delete an API key"""
result = await db.execute(select(APIKey).where(APIKey.id == key_id))
api_key = result.scalar_one_or_none()
if not api_key:
raise HTTPException(status_code=404, detail="API key not found")
await db.delete(api_key)
await db.commit()
return {"message": "API key deleted"}
@router.post("/{key_id}/deactivate")
async def deactivate_api_key(key_id: int, db: AsyncSession = Depends(get_db)):
"""Deactivate an API key"""
result = await db.execute(select(APIKey).where(APIKey.id == key_id))
api_key = result.scalar_one_or_none()
if not api_key:
raise HTTPException(status_code=404, detail="API key not found")
api_key.is_active = False
await db.commit()
await db.refresh(api_key)
return api_key
@router.post("/{key_id}/activate")
async def activate_api_key(key_id: int, db: AsyncSession = Depends(get_db)):
"""Activate an API key"""
result = await db.execute(select(APIKey).where(APIKey.id == key_id))
api_key = result.scalar_one_or_none()
if not api_key:
raise HTTPException(status_code=404, detail="API key not found")
api_key.is_active = True
await db.commit()
await db.refresh(api_key)
return api_key