feat: remove voice

This commit is contained in:
Harold 2025-12-11 00:00:40 +08:00
parent e69edfafd2
commit 6db8e70cf4
4 changed files with 87 additions and 16 deletions

View file

@ -8,6 +8,8 @@ from infra.fishaudio import get_fish_audio
from infra.openai import get_openai
from services.voice_service import voice_service
from services.llm_service import llm_service
from services.agent_service import agent_service
from utils.exceptions import ConflictException
from schemas.voice import (
LiveAgentVoice,
DiscoverVoiceResponse,
@ -259,18 +261,31 @@ async def update_voice(
async def remove_voice(
voice_id: str,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
db: AsyncSession = Depends(get_db),
s3 = Depends(get_s3),
fish_client = Depends(get_fish_audio)
):
"""
Remove a voice from user's my voices
- Only deletes the database record (reference)
Remove a voice completely from user's my voices
- Checks if voice is bound to any agent (returns 409 Conflict if bound)
- Deletes from database, S3, and Fish Audio
- User must own the voice
"""
await voice_service.remove_voice(
db=db,
voice_id=voice_id,
owner_id=current_user_id
)
# Check if voice is bound to any agent
is_bound = await agent_service.is_voice_bound(db=db, voice_id=voice_id)
if is_bound:
raise ConflictException("Cannot remove voice: it is currently bound to one or more agents")
try:
await voice_service.remove_voice(
db=db,
s3=s3,
fish_client=fish_client,
voice_id=voice_id,
owner_id=current_user_id
)
except Exception as e:
return error_response(code=500, message=f"Voice removal failed: {e}")
return success_response(
data={"voice_id": voice_id},

View file

@ -212,6 +212,26 @@ class Agent:
)
return list(result.scalars().all())
@staticmethod
async def is_voice_bound(db: AsyncSession, voice_id: str) -> bool:
"""
Check if a voice is bound to any agent
Args:
db: Database session
voice_id: Voice ID to check
Returns:
True if voice is bound to at least one agent
"""
result = await db.execute(
select(func.count())
.select_from(AgentModel)
.where(AgentModel.voice_id == voice_id)
)
count = result.scalar_one()
return count > 0
@staticmethod
async def get_agents_with_latest_message(
db: AsyncSession,

View file

@ -167,6 +167,19 @@ class AgentService:
"""
return await Agent.get_bindable_agents(db, owner_id)
async def is_voice_bound(self, db: AsyncSession, voice_id: str) -> bool:
"""
Check if a voice is bound to any agent
Args:
db: Database session
voice_id: Voice ID to check
Returns:
True if voice is bound to at least one agent
"""
return await Agent.is_voice_bound(db, voice_id)
async def create_agent(
self,
db: AsyncSession,

View file

@ -1,15 +1,16 @@
from typing import Optional, List, Tuple
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import UploadFile
from fishaudio import AsyncFishAudio, save
from fishaudio import AsyncFishAudio
from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample
from repositories import VoiceModel, Voice
from utils.ulid import generate_voice_id
from repositories import FileRepository
from datetime import datetime, timezone
from config.logger import setup_logging
from utils.exceptions import NotFoundException
TAG = __name__
logger = setup_logging(TAG)
@ -256,26 +257,48 @@ class VoiceService:
async def remove_voice(
self,
db: AsyncSession,
s3,
fish_client: AsyncFishAudio,
voice_id: str,
owner_id: str
) -> bool:
"""
Remove a voice from user's my voices
Remove a voice completely: database, S3, and Fish Audio
Args:
db: Database session
voice_id: Internal voice ID
s3: S3 client
fish_client: Fish Audio client
voice_id: Voice ID
owner_id: User ID
Returns:
True if deleted, False if not found
"""
deleted = await Voice.delete(db=db, voice_id=voice_id, owner_id=owner_id)
True if deleted successfully
if not deleted:
from utils.exceptions import NotFoundException
Raises:
NotFoundException: If voice not found or not owned by user
"""
# Get voice record first to get sample_url for S3 cleanup
voice = await Voice.get_by_voice_and_owner(db=db, voice_id=voice_id, owner_id=owner_id)
if not voice:
raise NotFoundException(f"Voice {voice_id} not found or not owned by user")
sample_url = voice.sample_url
# Delete from database first
deleted = await Voice.delete(db=db, voice_id=voice_id, owner_id=owner_id)
if not deleted:
raise NotFoundException(f"Voice {voice_id} not found or not owned by user")
# Cleanup S3 file (best effort, don't fail if cleanup fails)
try:
if sample_url:
await self._cleanup_s3_file(s3, sample_url)
await self._cleanup_fish_voice(fish_client, voice_id)
except Exception as e:
logger.bind(tag=TAG).warning(f"Cleanup failed: {e}")
return False
return True
async def update_voice(