Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ad50d5c70 |
No files matched your search
@@ -245,23 +245,12 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Refresh E2E session token
|
||||
id: refresh_token
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Happy Path Production Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
|
||||
E2E_TEST_TOKEN: ${{ secrets.E2E_TEST_TOKEN }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
run: |
|
||||
@@ -688,16 +677,14 @@ jobs:
|
||||
ci-gate:
|
||||
name: "CI Gate"
|
||||
runs-on: ubuntu-latest
|
||||
# Note: frontend-e2e-full is optional (requires 'e2e' label) so not included here
|
||||
# frontend-e2e-smoke IS required - fast smoke tests catch critical regressions
|
||||
# frontend-lint IS required - catches React hooks violations that cause runtime crashes
|
||||
# frontend-e2e-happy-path is required ONLY when 'e2e-happy-path' label is present
|
||||
# frontend-e2e-full is optional (requires 'e2e' label) so not enforced here
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path]
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint]
|
||||
if: github.ref != 'refs/heads/main' && always()
|
||||
steps:
|
||||
- name: Check results
|
||||
run: |
|
||||
# Check all always-required jobs
|
||||
results=(
|
||||
"${{ needs.frontend-lint.result }}"
|
||||
"${{ needs.frontend-unit-tests.result }}"
|
||||
@@ -715,20 +702,6 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# E2E Happy Path: enforced when 'e2e-happy-path' label is on the PR
|
||||
e2e_result="${{ needs.frontend-e2e-happy-path.result }}"
|
||||
has_label="${{ contains(github.event.pull_request.labels.*.name, 'e2e-happy-path') }}"
|
||||
if [[ "$has_label" == "true" ]]; then
|
||||
if [[ "$e2e_result" != "success" ]]; then
|
||||
echo "❌ E2E Happy Path is required (label present) but result is: $e2e_result"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ E2E Happy Path passed (required by label)"
|
||||
else
|
||||
echo "ℹ️ E2E Happy Path skipped (no label)"
|
||||
fi
|
||||
|
||||
echo "✅ CI passed"
|
||||
|
||||
# ============================================
|
||||
@@ -1270,7 +1243,7 @@ jobs:
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest"
|
||||
|
||||
- name: Verify deployment and version
|
||||
run: |
|
||||
|
||||
@@ -67,24 +67,12 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: inputs.use_test_token == true
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run E2E Happy Path Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || '' }}
|
||||
E2E_TEST_TOKEN: ${{ inputs.use_test_token && secrets.E2E_TEST_TOKEN || '' }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
|
||||
@@ -1551,9 +1551,8 @@ async def delete_job_outputs(
|
||||
|
||||
This endpoint deletes:
|
||||
1. YouTube video (if uploaded)
|
||||
2. Dropbox folder (if uploaded)
|
||||
2. Dropbox folder (if uploaded) - frees brand code for reuse
|
||||
3. Google Drive files (if uploaded)
|
||||
4. Recycles brand code for reuse (if Dropbox + GDrive cleanup succeeded)
|
||||
|
||||
The job record is preserved with outputs_deleted_at timestamp set.
|
||||
State data related to distribution is cleared.
|
||||
@@ -1689,23 +1688,6 @@ async def delete_job_outputs(
|
||||
logger.error(f"Error deleting GCS finals folder for job {job_id}: {e}", exc_info=True)
|
||||
results["gcs_finals"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Recycle brand code if Dropbox and GDrive cleanup both succeeded
|
||||
dropbox_success = results["dropbox"]["status"] in ("success", "skipped")
|
||||
gdrive_success = results["gdrive"]["status"] in ("success", "skipped")
|
||||
if brand_code and dropbox_success and gdrive_success:
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
results["brand_code"] = {"status": "recycled", "code": brand_code}
|
||||
logger.info(f"Recycled brand code {brand_code} during delete-outputs for job {job_id}")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
results["brand_code"] = {"status": "failed", "error": str(e)}
|
||||
elif brand_code:
|
||||
logger.warning(f"Brand code {brand_code} NOT recycled: cleanup incomplete (dropbox={results['dropbox']['status']}, gdrive={results['gdrive']['status']})")
|
||||
results["brand_code"] = {"status": "skipped", "reason": "Dropbox/GDrive cleanup incomplete"}
|
||||
|
||||
# Update job record
|
||||
deletion_timestamp = datetime.now(timezone.utc)
|
||||
user_service = get_user_service()
|
||||
@@ -1753,14 +1735,12 @@ async def delete_job_outputs(
|
||||
overall_status = "success"
|
||||
message = "Outputs deleted successfully"
|
||||
|
||||
brand_code_status = results.get('brand_code', {}).get('status', 'n/a')
|
||||
logger.info(
|
||||
f"Admin {admin_email} deleted outputs for job {job_id}. "
|
||||
f"YouTube: {results['youtube']['status']}, "
|
||||
f"Dropbox: {results['dropbox']['status']}, "
|
||||
f"GDrive: {results['gdrive']['status']}, "
|
||||
f"GCS Finals: {results['gcs_finals']['status']}, "
|
||||
f"Brand Code: {brand_code_status}. "
|
||||
f"GCS Finals: {results['gcs_finals']['status']}. "
|
||||
f"Cleared state_data keys: {cleared_keys}"
|
||||
)
|
||||
|
||||
|
||||
@@ -17,8 +17,6 @@ import mimetypes
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request, Depends
|
||||
@@ -37,7 +35,6 @@ from backend.services.audio_search_service import (
|
||||
NoResultsError,
|
||||
DownloadError,
|
||||
)
|
||||
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
@@ -50,7 +47,6 @@ from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.exceptions import InsufficientCreditsError, RateLimitExceededError
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -200,32 +196,9 @@ class AudioSearchResponse(BaseModel):
|
||||
style_upload_urls: Optional[List[StyleUploadUrl]] = None
|
||||
|
||||
|
||||
class StandaloneSearchRequest(BaseModel):
|
||||
"""Request for standalone audio search (no job created)."""
|
||||
artist: str = Field(..., description="Artist name to search for")
|
||||
title: str = Field(..., description="Song title to search for")
|
||||
|
||||
@validator('artist', 'title')
|
||||
def normalize_text_fields(cls, v):
|
||||
if v is not None and isinstance(v, str):
|
||||
return normalize_text(v)
|
||||
return v
|
||||
|
||||
|
||||
class StandaloneSearchResponse(BaseModel):
|
||||
"""Response from standalone audio search."""
|
||||
search_session_id: str
|
||||
results: List[AudioSearchResultResponse]
|
||||
results_count: int
|
||||
|
||||
|
||||
class AudioSelectRequest(BaseModel):
|
||||
"""Request to select an audio source."""
|
||||
selection_index: int = Field(..., description="Index of the selected audio source from search results")
|
||||
# Optional overrides — sent from the guided flow's Customize step (Step 3)
|
||||
is_private: Optional[bool] = Field(None, description="Override privacy flag (guided flow Step 3)")
|
||||
display_artist: Optional[str] = Field(None, description="Override display artist name")
|
||||
display_title: Optional[str] = Field(None, description="Override display title")
|
||||
|
||||
|
||||
class AudioSelectResponse(BaseModel):
|
||||
@@ -409,9 +382,8 @@ async def _download_audio_and_trigger_workers(
|
||||
raise DownloadError(f"YouTube download failed: {e}")
|
||||
|
||||
elif source_name in ['RED', 'OPS']:
|
||||
# Torrent sources - must use remote flacfetch (async, no event loop blocking)
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
# Torrent sources - must use remote flacfetch
|
||||
if not audio_search_service.is_remote_enabled():
|
||||
raise DownloadError(
|
||||
f"Cannot download from {source_name} without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
@@ -421,48 +393,31 @@ async def _download_audio_and_trigger_workers(
|
||||
|
||||
if source_id:
|
||||
logger.info(f"Torrent download via download_by_id: {source_name} ID={source_id}")
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="",
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
else:
|
||||
if not remote_search_id:
|
||||
raise DownloadError(
|
||||
f"No source_id or remote_search_id available for {source_name} download"
|
||||
)
|
||||
logger.info(f"Torrent download via search-based download")
|
||||
download_id = await flacfetch_client.download(
|
||||
search_id=remote_search_id,
|
||||
result = audio_search_service.download(
|
||||
result_index=selection_index,
|
||||
output_dir="",
|
||||
gcs_path=gcs_destination,
|
||||
remote_search_id=remote_search_id,
|
||||
)
|
||||
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
# Extract GCS path from result
|
||||
audio_gcs_path = _extract_gcs_path(result.filepath)
|
||||
filename = os.path.basename(result.filepath)
|
||||
logger.info(f"Torrent download complete: {audio_gcs_path}")
|
||||
|
||||
elif source_name == 'Spotify':
|
||||
# Spotify downloads - use async FlacfetchClient directly (no event loop blocking)
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
# Spotify downloads - use audio_search_service
|
||||
if not audio_search_service.is_remote_enabled():
|
||||
raise DownloadError(
|
||||
f"Cannot download from Spotify without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
@@ -471,40 +426,25 @@ async def _download_audio_and_trigger_workers(
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
logger.info(f"Spotify download: source_id={source_id}")
|
||||
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="",
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
audio_gcs_path = _extract_gcs_path(result.filepath)
|
||||
filename = os.path.basename(result.filepath)
|
||||
logger.info(f"Spotify download complete: {audio_gcs_path}")
|
||||
|
||||
else:
|
||||
# Unknown source - try generic download (run sync code in thread to avoid blocking)
|
||||
# Unknown source - try generic download
|
||||
logger.warning(f"Unknown source type: {source_name}, attempting generic download")
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
|
||||
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
audio_search_service.download,
|
||||
result = audio_search_service.download(
|
||||
result_index=selection_index,
|
||||
output_dir=temp_dir,
|
||||
remote_search_id=remote_search_id,
|
||||
@@ -554,7 +494,7 @@ async def _download_audio_and_trigger_workers(
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
except (DownloadError, FlacfetchServiceError) as e:
|
||||
except DownloadError as e:
|
||||
logger.error(f"Download failed for job {job_id}: {e}")
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
except Exception as e:
|
||||
@@ -794,7 +734,7 @@ async def search_audio(
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
try:
|
||||
search_results = await audio_search_service.search_async(body.artist, body.title)
|
||||
search_results = audio_search_service.search(body.artist, body.title)
|
||||
except NoResultsError as e:
|
||||
job_manager.fail_job(job_id, f"No audio sources found for: {body.artist} - {body.title}")
|
||||
raise HTTPException(
|
||||
@@ -925,145 +865,12 @@ async def search_audio(
|
||||
style_upload_urls=style_upload_urls if style_upload_urls else None,
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
if isinstance(e, (InsufficientCreditsError, RateLimitExceededError)):
|
||||
raise
|
||||
logger.error(f"Error in audio search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/audio-search/search-standalone", response_model=StandaloneSearchResponse)
|
||||
async def search_audio_standalone(
|
||||
request: Request,
|
||||
body: StandaloneSearchRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Search for audio by artist and title WITHOUT creating a job.
|
||||
|
||||
Returns a search session ID and results. Call POST /api/jobs/create-from-search
|
||||
with the session ID and selected result index to create the actual job.
|
||||
|
||||
Credits are checked here (early feedback) but NOT deducted — deduction
|
||||
happens when the job is created via create-from-search.
|
||||
"""
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.audio_search:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Audio search is not available for this portal"
|
||||
)
|
||||
|
||||
try:
|
||||
user_email = auth_result.user_email
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
# Credit check — give early feedback but do NOT deduct here
|
||||
if not auth_result.is_admin:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
if not user_service.has_credits(user_email):
|
||||
credits_available = user_service.check_credits(user_email)
|
||||
raise InsufficientCreditsError(
|
||||
message="You're out of credits. Buy more to continue creating karaoke videos.",
|
||||
credits_available=credits_available,
|
||||
credits_required=1,
|
||||
)
|
||||
|
||||
# Perform the search (runs in thread to avoid blocking the event loop)
|
||||
audio_search_service = get_audio_search_service()
|
||||
try:
|
||||
search_results = await audio_search_service.search_async(body.artist, body.title)
|
||||
except NoResultsError:
|
||||
# No results is a normal outcome — return empty list, not an error
|
||||
search_results = []
|
||||
except AudioSearchError as e:
|
||||
raise HTTPException(status_code=500, detail=f"Search failed: {e}")
|
||||
|
||||
# Build result response objects
|
||||
result_responses: List[AudioSearchResultResponse] = []
|
||||
results_dicts: List[Dict[str, Any]] = []
|
||||
for r in search_results:
|
||||
raw_dict: Dict[str, Any] = {}
|
||||
if r.raw_result:
|
||||
if isinstance(r.raw_result, dict):
|
||||
raw_dict = r.raw_result
|
||||
else:
|
||||
try:
|
||||
raw_dict = r.raw_result.to_dict()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
result_responses.append(
|
||||
AudioSearchResultResponse(
|
||||
index=r.index,
|
||||
title=r.title,
|
||||
artist=r.artist,
|
||||
provider=r.provider,
|
||||
url=r.url,
|
||||
duration=r.duration,
|
||||
quality=r.quality,
|
||||
source_id=r.source_id,
|
||||
seeders=raw_dict.get('seeders') or r.seeders,
|
||||
target_file=raw_dict.get('target_file') or r.target_file,
|
||||
year=raw_dict.get('year'),
|
||||
label=raw_dict.get('label'),
|
||||
edition_info=raw_dict.get('edition_info'),
|
||||
release_type=raw_dict.get('release_type'),
|
||||
channel=raw_dict.get('channel'),
|
||||
view_count=raw_dict.get('view_count'),
|
||||
size_bytes=raw_dict.get('size_bytes'),
|
||||
target_file_size=raw_dict.get('target_file_size'),
|
||||
track_pattern=raw_dict.get('track_pattern'),
|
||||
match_score=raw_dict.get('match_score'),
|
||||
formatted_size=raw_dict.get('formatted_size'),
|
||||
formatted_duration=raw_dict.get('formatted_duration'),
|
||||
formatted_views=raw_dict.get('formatted_views'),
|
||||
is_lossless=raw_dict.get('is_lossless'),
|
||||
quality_str=raw_dict.get('quality_str'),
|
||||
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
|
||||
)
|
||||
)
|
||||
results_dicts.append(r.to_dict())
|
||||
|
||||
# Store session in Firestore (TTL: 30 minutes)
|
||||
session_id = str(uuid.uuid4())
|
||||
now = datetime.utcnow()
|
||||
session_data = {
|
||||
'session_id': session_id,
|
||||
'user_email': user_email,
|
||||
'tenant_id': tenant_config.id if tenant_config else None,
|
||||
'artist': body.artist,
|
||||
'title': body.title,
|
||||
'results': results_dicts,
|
||||
'remote_search_id': audio_search_service.last_remote_search_id,
|
||||
'created_at': now.isoformat(),
|
||||
'ttl_expiry': now + timedelta(minutes=30),
|
||||
}
|
||||
firestore_service = FirestoreService()
|
||||
firestore_service.create_search_session(session_data)
|
||||
|
||||
logger.info(
|
||||
f"Standalone search complete for {body.artist} - {body.title}: "
|
||||
f"{len(search_results)} results, session={session_id}"
|
||||
)
|
||||
|
||||
return StandaloneSearchResponse(
|
||||
search_session_id=session_id,
|
||||
results=result_responses,
|
||||
results_count=len(result_responses),
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error in standalone audio search: {e}", exc_info=True)
|
||||
logger.error(f"Error in audio search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@@ -1131,20 +938,6 @@ async def select_audio_source(
|
||||
# The source_id stored in job.state_data['audio_search_results'] is sufficient.
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
# Apply optional overrides from guided flow Step 3 (Customize)
|
||||
# These fields are set AFTER the job is created (Step 2), so they must be
|
||||
# patched here before the pipeline starts.
|
||||
overrides = {}
|
||||
if body.is_private is not None:
|
||||
overrides["is_private"] = body.is_private
|
||||
if body.display_artist is not None:
|
||||
overrides["display_artist"] = body.display_artist
|
||||
if body.display_title is not None:
|
||||
overrides["display_title"] = body.display_title
|
||||
if overrides:
|
||||
job_manager.update_job(job_id, overrides)
|
||||
logger.info(f"[job:{job_id}] Applied selection overrides: {list(overrides.keys())}")
|
||||
|
||||
# Validate search results exist in job state_data
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
if not search_results:
|
||||
|
||||
@@ -428,39 +428,6 @@ async def check_idle_reminder(
|
||||
return {"status": "error", "job_id": job_id, "message": str(e)}
|
||||
|
||||
|
||||
@router.post("/trigger-gdrive-validation")
|
||||
async def trigger_gdrive_validation_endpoint(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Trigger GDrive validation via the Cloud Function.
|
||||
|
||||
Called by a Cloud Tasks delayed task after a job completes and uploads
|
||||
to the public GDrive share. The 5-minute delay ensures E2E test cleanup
|
||||
finishes before the validator checks for sequence gaps.
|
||||
"""
|
||||
from backend.services.gdrive_validator_client import trigger_gdrive_validation
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info("GDRIVE_VALIDATION_TRIGGER starting (delayed post-job)")
|
||||
add_span_attribute("operation", "gdrive_validation_trigger")
|
||||
|
||||
try:
|
||||
result = trigger_gdrive_validation()
|
||||
if result is None:
|
||||
return {"status": "skipped", "message": "GDRIVE_VALIDATOR_URL not configured"}
|
||||
|
||||
status = result.get("status", "unknown")
|
||||
add_span_event("validation_complete", {"result_status": status})
|
||||
return {"status": status, "message": "GDrive validation completed", "result": result}
|
||||
except Exception as e:
|
||||
logger.exception(f"GDrive validation trigger failed: {e}")
|
||||
add_span_event("error", {"error": str(e)})
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def internal_health(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
|
||||
@@ -17,7 +17,6 @@ from pathlib import Path
|
||||
from typing import List, Optional, Dict, Any
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
|
||||
|
||||
from datetime import datetime
|
||||
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
|
||||
from backend.models.requests import (
|
||||
URLSubmissionRequest,
|
||||
@@ -39,8 +38,6 @@ from backend.services.metrics import metrics
|
||||
from backend.middleware.tenant import get_tenant_from_request
|
||||
from backend.utils.test_data import is_test_email
|
||||
from backend.exceptions import InsufficientCreditsError, RateLimitExceededError
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from pydantic import BaseModel, Field, validator
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -208,7 +205,7 @@ _SUMMARY_STATE_DATA_KEYS = {
|
||||
'backing_vocals_analysis',
|
||||
}
|
||||
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete']
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'failed', 'cancelled']
|
||||
|
||||
|
||||
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
@@ -256,7 +253,7 @@ async def list_jobs(
|
||||
exclude_test: If True (default), exclude jobs from test users (admin only)
|
||||
limit: Maximum number of jobs to return (default 100)
|
||||
fields: Set to "summary" for reduced payload with only dashboard-required fields
|
||||
hide_completed: If True, exclude successful completions (complete, prep_complete). Failed jobs remain visible.
|
||||
hide_completed: If True, exclude terminal-status jobs (complete, prep_complete, failed, cancelled)
|
||||
|
||||
Returns:
|
||||
List of jobs matching filters, ordered by created_at descending.
|
||||
@@ -364,24 +361,6 @@ async def delete_job(
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to delete this job")
|
||||
|
||||
# Recycle any unreturned brand code before deleting the job record
|
||||
state_data = job.state_data or {}
|
||||
brand_code = state_data.get('brand_code')
|
||||
if brand_code:
|
||||
if not job.outputs_deleted_at:
|
||||
logger.warning(
|
||||
f"Deleting job {job_id} with brand_code {brand_code} whose outputs "
|
||||
f"were not cleaned up first. Brand code will be recycled but "
|
||||
f"distributed files (GDrive/Dropbox/YouTube) may be orphaned."
|
||||
)
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
logger.info(f"Recycled brand code {brand_code} before deleting job {job_id}")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
|
||||
job_manager.delete_job(job_id, delete_files=delete_files)
|
||||
|
||||
return {"status": "success", "message": f"Job {job_id} deleted"}
|
||||
@@ -665,55 +644,6 @@ async def submit_corrections(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{job_id}/edit-log")
|
||||
async def submit_edit_log(
|
||||
job_id: str,
|
||||
edit_log: Dict[str, Any],
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Store an edit log from a lyrics review session.
|
||||
|
||||
Edit logs capture what edits users made and optional feedback on why,
|
||||
for use as training data to improve transcription models.
|
||||
|
||||
Stored to GCS as jobs/{job_id}/lyrics/edit_log_{session_id}.json.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
|
||||
session_id = edit_log.get("session_id", "unknown")
|
||||
entries = edit_log.get("entries", [])
|
||||
feedback_count = sum(1 for e in entries if e.get("feedback") and e["feedback"].get("reason") != "no_response")
|
||||
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/edit_log_{session_id}.json"
|
||||
storage.upload_json(gcs_path, edit_log)
|
||||
|
||||
job_manager.update_state_data(job_id, 'last_edit_log_path', gcs_path)
|
||||
job_manager.update_state_data(job_id, 'last_edit_log_session', session_id)
|
||||
|
||||
logger.info(
|
||||
f"Job {job_id}: Edit log saved — {len(entries)} entries, "
|
||||
f"{feedback_count} with feedback, session {session_id}"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"entries_count": len(entries),
|
||||
"feedback_count": feedback_count,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error saving edit log for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{job_id}/create-custom-instrumental")
|
||||
async def create_custom_instrumental(
|
||||
job_id: str,
|
||||
@@ -1725,7 +1655,6 @@ async def cleanup_distribution(
|
||||
# Clean up Dropbox
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
dropbox_cleaned = False
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
@@ -1735,11 +1664,22 @@ async def cleanup_distribution(
|
||||
folder_name = f"{brand_code} - {base_name}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
success = dropbox.delete_folder(full_path)
|
||||
dropbox_cleaned = success
|
||||
results["dropbox"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"path": full_path
|
||||
}
|
||||
# Recycle the brand code number so it can be reused
|
||||
if success:
|
||||
try:
|
||||
from backend.services.brand_code_service import (
|
||||
BrandCodeService, get_brand_code_service
|
||||
)
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
results["dropbox"]["recycled_brand_code"] = True
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
results["dropbox"]["recycled_brand_code"] = False
|
||||
else:
|
||||
results["dropbox"] = {"status": "failed", "reason": "Dropbox credentials not configured"}
|
||||
except Exception as e:
|
||||
@@ -1747,92 +1687,25 @@ async def cleanup_distribution(
|
||||
results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Clean up Google Drive
|
||||
# Use tracked file IDs if available; otherwise fall back to searching by brand code.
|
||||
# This handles old jobs where gdrive_files was not persisted (e.g., uploaded before
|
||||
# file ID tracking was implemented, or when GDrive upload silently failed and a
|
||||
# previous test run left files behind).
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
gdrive_folder_id = getattr(job, 'gdrive_folder_id', None)
|
||||
gdrive_cleaned = False
|
||||
|
||||
if gdrive_files or (gdrive_folder_id and brand_code):
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids: list = []
|
||||
gdrive_method = None # track how files were located for response
|
||||
|
||||
if gdrive_files and isinstance(gdrive_files, dict):
|
||||
# Fast path: delete using tracked file IDs from state_data
|
||||
file_ids = [v for v in gdrive_files.values() if v]
|
||||
logger.info(
|
||||
f"GDrive cleanup for job {job_id}: "
|
||||
f"using {len(file_ids)} tracked file IDs"
|
||||
)
|
||||
|
||||
if not file_ids and gdrive_folder_id and brand_code:
|
||||
# Fallback: search by brand code prefix in CDG/, MP4/, MP4-720p/ subfolders.
|
||||
# Handles jobs where gdrive_files was not tracked (old jobs, or jobs where
|
||||
# GDrive upload succeeded but file IDs were lost).
|
||||
logger.info(
|
||||
f"GDrive cleanup for job {job_id}: "
|
||||
f"no tracked file IDs, searching by brand_code '{brand_code}'"
|
||||
)
|
||||
file_ids = gdrive.find_files_by_brand_code(gdrive_folder_id, brand_code)
|
||||
gdrive_method = "brand_code_search"
|
||||
|
||||
if file_ids:
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
gdrive_cleaned = all_success
|
||||
results["gdrive"] = {
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results,
|
||||
}
|
||||
if gdrive_method:
|
||||
results["gdrive"]["method"] = gdrive_method
|
||||
else:
|
||||
gdrive_cleaned = True # Nothing to delete
|
||||
results["gdrive"] = {
|
||||
"status": "skipped",
|
||||
"reason": "no files found to delete",
|
||||
}
|
||||
else:
|
||||
# gdrive_files is a dict like {"mp4": "file_id", "mp4_720p": "file_id", "cdg": "file_id"}
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
results["gdrive"] = {
|
||||
"status": "failed",
|
||||
"reason": "Google Drive credentials not configured",
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results
|
||||
}
|
||||
else:
|
||||
results["gdrive"] = {"status": "failed", "reason": "Google Drive credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True
|
||||
)
|
||||
logger.error(f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
if not gdrive_folder_id:
|
||||
results["gdrive"]["reason"] = "no gdrive_folder_id on job and no tracked file IDs"
|
||||
|
||||
# Recycle the brand code so it can be reused — but only after GDrive is confirmed clean.
|
||||
# If we recycle before GDrive cleanup, a new job could claim the same brand code and
|
||||
# collide with leftover files on GDrive (duplicate brand code in public share).
|
||||
if dropbox_cleaned and brand_code and gdrive_cleaned:
|
||||
try:
|
||||
from backend.services.brand_code_service import (
|
||||
BrandCodeService, get_brand_code_service
|
||||
)
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
results["dropbox"]["recycled_brand_code"] = True
|
||||
logger.info(f"Recycled brand code {brand_code} after full distribution cleanup")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
results["dropbox"]["recycled_brand_code"] = False
|
||||
elif dropbox_cleaned and brand_code:
|
||||
logger.warning(
|
||||
f"Brand code {brand_code} NOT recycled: GDrive cleanup did not confirm success "
|
||||
f"(gdrive_cleaned={gdrive_cleaned}). Brand code will remain reserved to prevent "
|
||||
f"collisions with leftover GDrive files."
|
||||
)
|
||||
|
||||
# Delete the job if requested
|
||||
if delete_job:
|
||||
@@ -1847,227 +1720,3 @@ async def cleanup_distribution(
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Guided Flow: Create job from search session
|
||||
# ============================================================================
|
||||
|
||||
class CreateFromSearchRequest(BaseModel):
|
||||
"""Request to create a job from a completed standalone search session."""
|
||||
search_session_id: str = Field(..., description="Session ID returned by /api/audio-search/search-standalone")
|
||||
selection_index: int = Field(..., description="Index of the selected audio source from search results")
|
||||
artist: str = Field(..., description="Search artist name (from Step 1)")
|
||||
title: str = Field(..., description="Search title (from Step 1)")
|
||||
display_artist: Optional[str] = Field(None, description="Display artist override for title screens/filenames")
|
||||
display_title: Optional[str] = Field(None, description="Display title override for title screens/filenames")
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only, no YouTube/GDrive")
|
||||
|
||||
@validator('display_artist', 'display_title')
|
||||
def strip_whitespace(cls, v):
|
||||
if v is not None:
|
||||
return v.strip() or None
|
||||
return v
|
||||
|
||||
|
||||
@router.post("/create-from-search", response_model=JobResponse)
|
||||
async def create_job_from_search(
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: CreateFromSearchRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> JobResponse:
|
||||
"""
|
||||
Create a karaoke job from a previously completed standalone search session.
|
||||
|
||||
This is the second half of the guided job creation flow:
|
||||
1. POST /api/audio-search/search-standalone → search_session_id + results
|
||||
2. User picks a result (Step 2 of wizard)
|
||||
3. User confirms job settings (Step 3 of wizard)
|
||||
4. POST /api/jobs/create-from-search → job_id (this endpoint)
|
||||
|
||||
The job is created with all final field values at creation time (including
|
||||
is_private and display overrides). It skips AWAITING_AUDIO_SELECTION and
|
||||
goes directly to DOWNLOADING_AUDIO, then triggers workers.
|
||||
|
||||
Credit deduction happens here (inside job_manager.create_job).
|
||||
"""
|
||||
# Lazy imports from audio_search to avoid circular imports at module level
|
||||
from backend.api.routes.audio_search import (
|
||||
_validate_and_prepare_selection,
|
||||
_download_audio_and_trigger_workers,
|
||||
extract_request_metadata,
|
||||
)
|
||||
from backend.services.audio_search_service import get_audio_search_service
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
|
||||
try:
|
||||
user_email = auth_result.user_email
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
# Read the session non-destructively for validation.
|
||||
# consume_search_session (atomic read+delete) is called later, just before job creation,
|
||||
# so that a 4xx validation error leaves the session intact for the user to retry.
|
||||
firestore_service = FirestoreService()
|
||||
session = firestore_service.get_search_session(body.search_session_id)
|
||||
if not session:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Search expired — please search again"
|
||||
)
|
||||
|
||||
# Verify the session belongs to the requesting user (or admin)
|
||||
if not auth_result.is_admin and session.get('user_email') != user_email:
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to use this search session")
|
||||
|
||||
# Verify tenant consistency — session must have been created in the same tenant context
|
||||
request_tenant_id = getattr(request.state, 'tenant_id', None)
|
||||
if session.get('tenant_id') != request_tenant_id:
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to use this search session")
|
||||
|
||||
# Check TTL (belt-and-suspenders — Firestore TTL may not delete immediately)
|
||||
ttl_expiry = session.get('ttl_expiry')
|
||||
if ttl_expiry:
|
||||
if isinstance(ttl_expiry, str):
|
||||
try:
|
||||
ttl_expiry = datetime.fromisoformat(ttl_expiry)
|
||||
except ValueError:
|
||||
ttl_expiry = None
|
||||
if ttl_expiry and datetime.utcnow() > ttl_expiry.replace(tzinfo=None):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Search expired — please search again"
|
||||
)
|
||||
|
||||
search_results = session.get('results', [])
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="Search session has no results")
|
||||
|
||||
if body.selection_index < 0 or body.selection_index >= len(search_results):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid selection index {body.selection_index}. Valid range: 0-{len(search_results)-1}"
|
||||
)
|
||||
|
||||
# Apply server defaults (same as existing search endpoint)
|
||||
settings_obj = get_settings()
|
||||
effective_dropbox_path = settings_obj.default_dropbox_path
|
||||
effective_gdrive_folder_id = settings_obj.default_gdrive_folder_id
|
||||
effective_discord_webhook_url = settings_obj.default_discord_webhook_url
|
||||
effective_enable_youtube_upload = settings_obj.default_enable_youtube_upload
|
||||
effective_brand_prefix = settings_obj.default_brand_prefix
|
||||
effective_youtube_description = settings_obj.default_youtube_description
|
||||
|
||||
# Apply default theme
|
||||
theme_service = get_theme_service()
|
||||
effective_theme_id = theme_service.get_default_theme_id()
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(effective_theme_id, None, None)
|
||||
|
||||
# Determine display values
|
||||
session_artist = session.get('artist', body.artist)
|
||||
session_title = session.get('title', body.title)
|
||||
effective_display_artist = body.display_artist or session_artist
|
||||
effective_display_title = body.display_title or session_title
|
||||
|
||||
tenant_id = session.get('tenant_id')
|
||||
|
||||
request_metadata = extract_request_metadata(request, created_from="guided_flow")
|
||||
|
||||
# All validation passed — atomically consume (read+delete) the session to prevent
|
||||
# a second concurrent request from creating a duplicate job.
|
||||
consumed_session = firestore_service.consume_search_session(body.search_session_id)
|
||||
if not consumed_session:
|
||||
# Another concurrent request already consumed the session
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Search expired — please search again"
|
||||
)
|
||||
|
||||
# Create the job with all final values
|
||||
job_create = JobCreate(
|
||||
artist=effective_display_artist,
|
||||
title=effective_display_title,
|
||||
theme_id=effective_theme_id,
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
brand_prefix=effective_brand_prefix,
|
||||
enable_youtube_upload=effective_enable_youtube_upload,
|
||||
youtube_description=effective_youtube_description,
|
||||
youtube_description_template=effective_youtube_description,
|
||||
discord_webhook_url=effective_discord_webhook_url,
|
||||
dropbox_path=effective_dropbox_path,
|
||||
gdrive_folder_id=effective_gdrive_folder_id,
|
||||
user_email=user_email,
|
||||
audio_search_artist=session_artist,
|
||||
audio_search_title=session_title,
|
||||
request_metadata=request_metadata,
|
||||
is_private=body.is_private,
|
||||
tenant_id=tenant_id,
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
logger.info(f"Created job {job_id} from search session {body.search_session_id}")
|
||||
|
||||
metrics.record_job_created(job_id, source="guided_search")
|
||||
|
||||
# Apply default theme style to job (copy style_params.json to job folder)
|
||||
if effective_theme_id:
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
try:
|
||||
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, {}
|
||||
)
|
||||
theme_update = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': theme_style_assets,
|
||||
}
|
||||
if youtube_desc and not effective_youtube_description:
|
||||
theme_update['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, theme_update)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to prepare theme '{effective_theme_id}' for job {job_id}: {e}")
|
||||
|
||||
# Store search results and remote_search_id in job state_data
|
||||
# (required by _download_audio_and_trigger_workers)
|
||||
state_data_update: Dict[str, Any] = {
|
||||
'audio_search_results': search_results,
|
||||
'audio_search_count': len(search_results),
|
||||
}
|
||||
if session.get('remote_search_id'):
|
||||
state_data_update['remote_search_id'] = session['remote_search_id']
|
||||
job_manager.update_job(job_id, {'state_data': state_data_update})
|
||||
|
||||
# Transition to DOWNLOADING_AUDIO (skips AWAITING_AUDIO_SELECTION entirely)
|
||||
_validate_and_prepare_selection(
|
||||
job_id=job_id,
|
||||
selection_index=body.selection_index,
|
||||
)
|
||||
|
||||
# Trigger audio download as a background task
|
||||
audio_search_service = get_audio_search_service()
|
||||
background_tasks.add_task(
|
||||
_download_audio_and_trigger_workers,
|
||||
job_id,
|
||||
body.selection_index,
|
||||
audio_search_service,
|
||||
)
|
||||
|
||||
return JobResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Job created successfully. Audio download starting."
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job from search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@@ -732,41 +732,17 @@ async def get_preview_video(
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
async def submit_annotation(
|
||||
job_id: str,
|
||||
payload: Dict[str, Any],
|
||||
annotation: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Submit correction annotations for ML training data.
|
||||
|
||||
Accepts either a single annotation dict or {"annotations": [...]} batch.
|
||||
Stores to GCS at jobs/{job_id}/lyrics/annotations.json.
|
||||
Submit a correction annotation for ML training data.
|
||||
|
||||
For now, just log and acknowledge - full annotation support
|
||||
would require a database.
|
||||
"""
|
||||
annotations = payload.get("annotations", [payload]) if isinstance(payload, dict) else [payload]
|
||||
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
|
||||
|
||||
# Merge with any existing annotations
|
||||
existing: list = []
|
||||
try:
|
||||
existing_data = storage.download_json(gcs_path)
|
||||
if isinstance(existing_data, list):
|
||||
existing = existing_data
|
||||
elif isinstance(existing_data, dict) and "annotations" in existing_data:
|
||||
existing = existing_data["annotations"]
|
||||
except Exception:
|
||||
pass # No existing file, start fresh
|
||||
|
||||
merged = existing + annotations
|
||||
storage.upload_json(gcs_path, {"annotations": merged})
|
||||
|
||||
logger.info(f"Job {job_id}: {len(annotations)} annotation(s) saved ({len(merged)} total)")
|
||||
return {"status": "success", "saved_count": len(annotations), "total_count": len(merged)}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error saving annotations: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
logger.info(f"Job {job_id}: Annotation submitted (logged but not stored)")
|
||||
return {"status": "success", "annotation_id": "stub"}
|
||||
|
||||
|
||||
@router.get("/{job_id}/v1/annotations/stats")
|
||||
@@ -775,18 +751,11 @@ async def get_annotation_stats(
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Get annotation statistics."""
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
|
||||
data = storage.download_json(gcs_path)
|
||||
annotations = data.get("annotations", []) if isinstance(data, dict) else data
|
||||
by_type: Dict[str, int] = {}
|
||||
for a in annotations:
|
||||
atype = a.get("annotation_type", "unknown")
|
||||
by_type[atype] = by_type.get(atype, 0) + 1
|
||||
return {"total_annotations": len(annotations), "by_type": by_type}
|
||||
except Exception:
|
||||
return {"total_annotations": 0, "by_type": {}}
|
||||
return {
|
||||
"total_annotations": 0,
|
||||
"by_type": {},
|
||||
"message": "Annotation stats not yet implemented"
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{job_id}/instrumental-analysis")
|
||||
|
||||
@@ -48,10 +48,6 @@ from backend.models.user import (
|
||||
BetaFeedbackRequest,
|
||||
BetaFeedbackResponse,
|
||||
BetaTesterFeedback,
|
||||
UserFeedback,
|
||||
UserFeedbackRequest,
|
||||
UserFeedbackResponse,
|
||||
FeedbackEligibilityResponse,
|
||||
)
|
||||
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
|
||||
from backend.services.email_service import get_email_service, EmailService
|
||||
@@ -325,10 +321,6 @@ async def get_current_user(
|
||||
if auth_result.is_valid and auth_result.user_email:
|
||||
# Get or create user record for the authenticated email
|
||||
user = user_service.get_or_create_user(auth_result.user_email)
|
||||
feedback_eligible = (
|
||||
user.total_jobs_completed >= 2
|
||||
and not user.has_submitted_feedback
|
||||
)
|
||||
user_public = UserPublic(
|
||||
email=user.email,
|
||||
role=user.role if not auth_result.is_admin else UserRole.ADMIN,
|
||||
@@ -336,7 +328,6 @@ async def get_current_user(
|
||||
display_name=user.display_name,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
feedback_eligible=feedback_eligible,
|
||||
)
|
||||
return UserProfileResponse(user=user_public, has_session=True)
|
||||
|
||||
@@ -346,10 +337,6 @@ async def get_current_user(
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
feedback_eligible = (
|
||||
user.total_jobs_completed >= 2
|
||||
and not user.has_submitted_feedback
|
||||
)
|
||||
user_public = UserPublic(
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
@@ -357,7 +344,6 @@ async def get_current_user(
|
||||
display_name=user.display_name,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
feedback_eligible=feedback_eligible,
|
||||
)
|
||||
|
||||
return UserProfileResponse(user=user_public, has_session=True)
|
||||
@@ -1144,153 +1130,6 @@ async def get_feedback_form_data(
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# User Feedback-for-Credits Endpoints
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
|
||||
async def check_feedback_eligibility(
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Check if the current user is eligible to submit feedback for credits.
|
||||
|
||||
Eligible if: total_jobs_completed >= 2 AND has not already submitted feedback.
|
||||
"""
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
# Try auth service first (admin tokens, auth_tokens)
|
||||
from backend.services.auth_service import get_auth_service
|
||||
auth_service = get_auth_service()
|
||||
auth_result = auth_service.validate_token_full(token)
|
||||
|
||||
user = None
|
||||
if auth_result.is_valid and auth_result.user_email:
|
||||
user = user_service.get_or_create_user(auth_result.user_email)
|
||||
else:
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
eligible = user.total_jobs_completed >= 2 and not user.has_submitted_feedback
|
||||
|
||||
return FeedbackEligibilityResponse(
|
||||
eligible=eligible,
|
||||
has_submitted=user.has_submitted_feedback,
|
||||
jobs_completed=user.total_jobs_completed,
|
||||
credits_reward=2,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/feedback", response_model=UserFeedbackResponse)
|
||||
async def submit_user_feedback(
|
||||
request: UserFeedbackRequest,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Submit product feedback to earn 2 free credits.
|
||||
|
||||
Requires authentication. Users must have completed 2+ jobs and
|
||||
not have already submitted feedback. At least one text field
|
||||
must have >50 characters.
|
||||
"""
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
# Try auth service first (admin tokens, auth_tokens)
|
||||
from backend.services.auth_service import get_auth_service
|
||||
auth_service = get_auth_service()
|
||||
auth_result = auth_service.validate_token_full(token)
|
||||
|
||||
user = None
|
||||
if auth_result.is_valid and auth_result.user_email:
|
||||
user = user_service.get_or_create_user(auth_result.user_email)
|
||||
else:
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
# Check eligibility: must have completed 2+ jobs
|
||||
if user.total_jobs_completed < 2:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="You need to complete at least 2 karaoke videos before submitting feedback."
|
||||
)
|
||||
|
||||
# Check if already submitted
|
||||
if user.has_submitted_feedback:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="You have already submitted feedback. Thank you!"
|
||||
)
|
||||
|
||||
# Validate: at least one text field has >50 characters
|
||||
has_detailed_feedback = (
|
||||
(request.what_went_well and len(request.what_went_well) > 50) or
|
||||
(request.what_could_improve and len(request.what_could_improve) > 50) or
|
||||
(request.additional_comments and len(request.additional_comments) > 50)
|
||||
)
|
||||
if not has_detailed_feedback:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Please provide detailed feedback in at least one text field (more than 50 characters)."
|
||||
)
|
||||
|
||||
# Save feedback to Firestore
|
||||
import uuid
|
||||
|
||||
feedback = UserFeedback(
|
||||
id=str(uuid.uuid4()),
|
||||
user_email=user.email,
|
||||
overall_rating=request.overall_rating,
|
||||
ease_of_use_rating=request.ease_of_use_rating,
|
||||
lyrics_accuracy_rating=request.lyrics_accuracy_rating,
|
||||
correction_experience_rating=request.correction_experience_rating,
|
||||
what_went_well=request.what_went_well,
|
||||
what_could_improve=request.what_could_improve,
|
||||
additional_comments=request.additional_comments,
|
||||
would_recommend=request.would_recommend,
|
||||
would_use_again=request.would_use_again,
|
||||
submitted_via="web",
|
||||
)
|
||||
|
||||
user_service.db.collection("user_feedback").document(feedback.id).set(
|
||||
feedback.model_dump(mode='json')
|
||||
)
|
||||
|
||||
# Mark user as having submitted feedback
|
||||
user_service.update_user(
|
||||
user.email,
|
||||
has_submitted_feedback=True,
|
||||
)
|
||||
|
||||
# Grant 2 credits
|
||||
credits_granted = 2
|
||||
user_service.add_credits(
|
||||
email=user.email,
|
||||
amount=credits_granted,
|
||||
reason="feedback_bonus",
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"User feedback received from {_mask_email(user.email)}, "
|
||||
f"credits granted: {credits_granted}"
|
||||
)
|
||||
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message=f"Thank you for your feedback! You earned {credits_granted} free credits.",
|
||||
credits_granted=credits_granted,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Endpoints
|
||||
# =============================================================================
|
||||
@@ -1571,31 +1410,6 @@ async def enable_user(
|
||||
return {"status": "success", "message": f"User {email} has been enabled"}
|
||||
|
||||
|
||||
@router.delete("/admin/users/{email}")
|
||||
async def delete_user(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Permanently delete a user and all associated data (admin only).
|
||||
|
||||
Jobs are NOT deleted - they remain as historical records.
|
||||
"""
|
||||
admin_token, _, _ = auth_data
|
||||
admin_id = f"admin:{admin_token[:8]}..." if admin_token else "admin:unknown"
|
||||
|
||||
try:
|
||||
success = user_service.delete_user(email, admin_email=admin_id)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
return {"status": "success", "message": f"User {email} has been deleted"}
|
||||
|
||||
|
||||
@router.post("/admin/users/{email}/role")
|
||||
async def set_user_role(
|
||||
email: str,
|
||||
|
||||
@@ -93,9 +93,8 @@ class JobStatus(str, Enum):
|
||||
|
||||
# Valid state transitions
|
||||
STATE_TRANSITIONS = {
|
||||
# PENDING can go to DOWNLOADING (file upload), SEARCHING_AUDIO (artist+title search),
|
||||
# or DOWNLOADING_AUDIO (create-from-search where audio is pre-selected)
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
# PENDING can go to DOWNLOADING (file upload) or SEARCHING_AUDIO (artist+title search)
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
|
||||
# Audio search flow (for artist+title search mode)
|
||||
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
|
||||
|
||||
@@ -104,9 +104,6 @@ class User(BaseModel):
|
||||
# Users can subscribe from multiple devices/browsers
|
||||
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
|
||||
|
||||
# Feedback-for-credits program
|
||||
has_submitted_feedback: bool = False
|
||||
|
||||
|
||||
class MagicLinkToken(BaseModel):
|
||||
"""
|
||||
@@ -188,7 +185,6 @@ class UserPublic(BaseModel):
|
||||
total_jobs_created: int = 0
|
||||
total_jobs_completed: int = 0
|
||||
tenant_id: Optional[str] = None
|
||||
feedback_eligible: bool = False
|
||||
|
||||
|
||||
class AddCreditsRequest(BaseModel):
|
||||
@@ -292,70 +288,3 @@ class BetaFeedbackResponse(BaseModel):
|
||||
status: str
|
||||
message: str
|
||||
bonus_credits: int = 0 # Bonus credits for great feedback
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# User Feedback-for-Credits Models
|
||||
# ============================================================================
|
||||
|
||||
class UserFeedback(BaseModel):
|
||||
"""
|
||||
Feedback from any user (not just beta testers).
|
||||
|
||||
Stored in Firestore 'user_feedback' collection.
|
||||
Users earn 2 free credits for submitting detailed feedback.
|
||||
"""
|
||||
id: str
|
||||
user_email: str
|
||||
|
||||
# Ratings (1-5 scale)
|
||||
overall_rating: int = Field(ge=1, le=5)
|
||||
ease_of_use_rating: int = Field(ge=1, le=5)
|
||||
lyrics_accuracy_rating: int = Field(ge=1, le=5)
|
||||
correction_experience_rating: int = Field(ge=1, le=5)
|
||||
|
||||
# Open-ended feedback
|
||||
what_went_well: Optional[str] = None
|
||||
what_could_improve: Optional[str] = None
|
||||
additional_comments: Optional[str] = None
|
||||
|
||||
# Would they recommend / use again?
|
||||
would_recommend: bool = True
|
||||
would_use_again: bool = True
|
||||
|
||||
# Metadata
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
submitted_via: str = "web"
|
||||
|
||||
|
||||
class UserFeedbackRequest(BaseModel):
|
||||
"""Request to submit user feedback for credits."""
|
||||
# Ratings (1-5 scale)
|
||||
overall_rating: int = Field(ge=1, le=5)
|
||||
ease_of_use_rating: int = Field(ge=1, le=5)
|
||||
lyrics_accuracy_rating: int = Field(ge=1, le=5)
|
||||
correction_experience_rating: int = Field(ge=1, le=5)
|
||||
|
||||
# Open-ended feedback
|
||||
what_went_well: Optional[str] = None
|
||||
what_could_improve: Optional[str] = None
|
||||
additional_comments: Optional[str] = None
|
||||
|
||||
# Would they recommend / use again?
|
||||
would_recommend: bool = True
|
||||
would_use_again: bool = True
|
||||
|
||||
|
||||
class UserFeedbackResponse(BaseModel):
|
||||
"""Response after submitting user feedback."""
|
||||
status: str
|
||||
message: str
|
||||
credits_granted: int = 0
|
||||
|
||||
|
||||
class FeedbackEligibilityResponse(BaseModel):
|
||||
"""Response for feedback eligibility check."""
|
||||
eligible: bool
|
||||
has_submitted: bool
|
||||
jobs_completed: int
|
||||
credits_reward: int = 2
|
||||
@@ -64,7 +64,7 @@ except ImportError:
|
||||
FINALIZING = "finalizing"
|
||||
|
||||
STATE_TRANSITIONS = {
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
|
||||
JobStatus.AWAITING_AUDIO_SELECTION: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
|
||||
|
||||
@@ -612,13 +612,13 @@ class AudioSearchService:
|
||||
async def search_async(self, artist: str, title: str) -> List[AudioSearchResult]:
|
||||
"""
|
||||
Async version of search for use in async routes.
|
||||
|
||||
Runs the sync search in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
|
||||
Note: Currently wraps sync search in executor. Future optimization
|
||||
could make this fully async.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(None, self.search, artist, title)
|
||||
|
||||
|
||||
async def download_async(
|
||||
self,
|
||||
result_index: int,
|
||||
@@ -630,10 +630,10 @@ class AudioSearchService:
|
||||
"""
|
||||
Async version of download for use in async routes.
|
||||
|
||||
Runs the sync download in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
Note: Currently wraps sync download in executor. Future optimization
|
||||
could make this fully async.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download(result_index, output_dir, output_filename, gcs_path, remote_search_id)
|
||||
@@ -651,11 +651,8 @@ class AudioSearchService:
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Async version of download_by_id for use in async routes.
|
||||
|
||||
Runs the sync download_by_id in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download_by_id(
|
||||
|
||||
@@ -400,31 +400,9 @@ Start creating: {self.frontend_url}
|
||||
"""
|
||||
subject = "Welcome to Nomad Karaoke! 🎤"
|
||||
|
||||
credits_text = f"You have <strong>{credits} credits</strong> to get started!" if credits > 0 else ""
|
||||
|
||||
extra_styles = """
|
||||
.credits-box {
|
||||
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
||||
border: 2px solid #e2b714;
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
margin: 24px 0;
|
||||
}
|
||||
.credits-box .credits-number {
|
||||
font-size: 48px;
|
||||
font-weight: bold;
|
||||
color: #e2b714;
|
||||
line-height: 1;
|
||||
}
|
||||
.credits-box .credits-label {
|
||||
font-size: 16px;
|
||||
color: #ccc;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.credits-box .credits-note {
|
||||
font-size: 13px;
|
||||
color: #999;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.feature {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
@@ -436,22 +414,10 @@ Start creating: {self.frontend_url}
|
||||
}
|
||||
"""
|
||||
|
||||
credits_box = ""
|
||||
if credits > 0:
|
||||
credits_box = f"""
|
||||
<div class="credits-box">
|
||||
<div class="credits-number">{credits}</div>
|
||||
<div class="credits-label">Free Credits</div>
|
||||
<div class="credits-note">Each credit creates one professional karaoke video</div>
|
||||
</div>
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>Welcome to Nomad Karaoke!</p>
|
||||
|
||||
<p>Turn any song into a professional karaoke video in minutes.</p>
|
||||
|
||||
{credits_box}
|
||||
<p>Turn any song into a professional karaoke video in minutes. {credits_text}</p>
|
||||
|
||||
<p><strong>Here's how it works:</strong></p>
|
||||
|
||||
@@ -487,10 +453,6 @@ Start creating: {self.frontend_url}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p style="text-align: center; font-size: 14px; color: #999; margin-top: 20px;">
|
||||
Complete 2 videos and earn 2 more free credits by sharing your feedback!
|
||||
</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{self.frontend_url}" class="button">Get Started</a>
|
||||
</p>
|
||||
@@ -498,13 +460,11 @@ Start creating: {self.frontend_url}
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
credits_text = f"\nYou have {credits} free credits to get started!\nEach credit creates one professional karaoke video.\n" if credits > 0 else ""
|
||||
|
||||
text_content = f"""
|
||||
Welcome to Nomad Karaoke!
|
||||
|
||||
Turn any song into a professional karaoke video in minutes.
|
||||
{credits_text}
|
||||
|
||||
Here's how it works:
|
||||
|
||||
1. Search for a song
|
||||
@@ -519,8 +479,6 @@ Here's how it works:
|
||||
4. Get your video
|
||||
Download your 4K karaoke video or upload directly to YouTube.
|
||||
|
||||
Complete 2 videos and earn 2 more free credits by sharing your feedback!
|
||||
|
||||
Get started: {self.frontend_url}
|
||||
|
||||
---
|
||||
|
||||
@@ -592,101 +592,6 @@ class FirestoreService:
|
||||
logger.error(f"Error listing tokens: {e}")
|
||||
return []
|
||||
|
||||
# ============================================
|
||||
# Search Session Methods
|
||||
# ============================================
|
||||
|
||||
def create_search_session(self, session_data: dict) -> str:
|
||||
"""Store a search session for the guided job creation flow.
|
||||
|
||||
Sessions are short-lived (TTL enforced via Firestore TTL policy) and
|
||||
represent a completed audio search that hasn't yet been converted into
|
||||
a job. The document is consumed (deleted) when create-from-search runs.
|
||||
|
||||
Args:
|
||||
session_data: Dict with session_id, user_email, tenant_id, artist,
|
||||
title, results, remote_search_id, ttl_expiry.
|
||||
|
||||
Returns:
|
||||
session_id from session_data.
|
||||
"""
|
||||
try:
|
||||
session_id = session_data['session_id']
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
doc_ref.set(session_data)
|
||||
logger.info(f"Created search session {session_id}")
|
||||
return session_id
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating search session: {e}")
|
||||
raise
|
||||
|
||||
def get_search_session(self, session_id: str) -> Optional[dict]:
|
||||
"""Retrieve a search session by ID.
|
||||
|
||||
Returns None only if the document does not exist.
|
||||
Raises on Firestore errors so callers can distinguish a missing session
|
||||
from a transient datastore failure.
|
||||
|
||||
TTL-expired documents may still appear briefly; callers should check
|
||||
ttl_expiry and treat expired sessions as missing.
|
||||
|
||||
Args:
|
||||
session_id: UUID string identifying the session.
|
||||
|
||||
Returns:
|
||||
Session dict or None.
|
||||
"""
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
return doc.to_dict()
|
||||
|
||||
def consume_search_session(self, session_id: str) -> Optional[dict]:
|
||||
"""Atomically read and delete a search session.
|
||||
|
||||
Uses a Firestore transaction to prevent two concurrent job-creation
|
||||
requests from both reading the same session and creating duplicate jobs.
|
||||
|
||||
Returns the session dict if it existed, None if it did not exist.
|
||||
Raises on Firestore errors.
|
||||
|
||||
Args:
|
||||
session_id: UUID string identifying the session.
|
||||
|
||||
Returns:
|
||||
Session dict or None.
|
||||
"""
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
|
||||
@firestore.transactional
|
||||
def _read_and_delete(transaction, ref):
|
||||
doc = ref.get(transaction=transaction)
|
||||
if not doc.exists:
|
||||
return None
|
||||
session_data = doc.to_dict()
|
||||
transaction.delete(ref)
|
||||
return session_data
|
||||
|
||||
transaction = self.db.transaction()
|
||||
return _read_and_delete(transaction, doc_ref)
|
||||
|
||||
def delete_search_session(self, session_id: str) -> None:
|
||||
"""Delete a search session after it has been consumed by job creation.
|
||||
|
||||
Errors are logged but not re-raised — a missing or already-deleted
|
||||
session is a no-op.
|
||||
|
||||
Args:
|
||||
session_id: UUID string identifying the session.
|
||||
"""
|
||||
try:
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
doc_ref.delete()
|
||||
logger.debug(f"Deleted search session {session_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting search session {session_id}: {e}")
|
||||
|
||||
|
||||
# Singleton client instance
|
||||
_firestore_client: Optional[firestore.Client] = None
|
||||
|
||||
@@ -44,31 +44,6 @@ class FlacfetchServiceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _format_httpx_error(e: Exception) -> str:
|
||||
"""
|
||||
Format an httpx exception into a descriptive error string.
|
||||
|
||||
httpx.RequestError subclasses (ConnectError, ReadError, etc.) often have
|
||||
empty str() representations, which produces useless messages like
|
||||
"Status request failed: ". This helper always returns something meaningful.
|
||||
"""
|
||||
error_str = str(e)
|
||||
error_type = type(e).__name__
|
||||
|
||||
if error_str:
|
||||
return f"{error_type}: {error_str}"
|
||||
|
||||
# str(e) is empty - try to include request URL for context
|
||||
if isinstance(e, httpx.RequestError):
|
||||
try:
|
||||
request = e.request
|
||||
if request:
|
||||
return f"{error_type} for {request.method} {request.url}"
|
||||
except RuntimeError:
|
||||
pass # .request not set
|
||||
return error_type
|
||||
|
||||
|
||||
def should_retry_flacfetch_error(exception: Exception) -> bool:
|
||||
"""
|
||||
Determine if a flacfetch exception should be retried.
|
||||
@@ -121,8 +96,7 @@ async def with_retry(func, *args, **kwargs):
|
||||
if attempt >= max_attempts:
|
||||
# No more attempts - raise the last exception
|
||||
logger.warning(
|
||||
f"Flacfetch request failed after {max_attempts} attempts: "
|
||||
f"{_format_httpx_error(e) if isinstance(e, httpx.RequestError) else e}"
|
||||
f"Flacfetch request failed after {max_attempts} attempts: {e}"
|
||||
)
|
||||
raise
|
||||
|
||||
@@ -130,8 +104,7 @@ async def with_retry(func, *args, **kwargs):
|
||||
wait_time = min(min_wait * (2 ** (attempt - 1)), max_wait)
|
||||
|
||||
logger.warning(
|
||||
f"Flacfetch request failed (attempt {attempt}/{max_attempts}): "
|
||||
f"{_format_httpx_error(e) if isinstance(e, httpx.RequestError) else e}. "
|
||||
f"Flacfetch request failed (attempt {attempt}/{max_attempts}): {e}. "
|
||||
f"Retrying in {wait_time:.1f}s..."
|
||||
)
|
||||
|
||||
@@ -200,7 +173,7 @@ class FlacfetchClient:
|
||||
|
||||
return data
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Cannot reach flacfetch service: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Cannot reach flacfetch service: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Health check failed: {e.response.status_code}")
|
||||
|
||||
@@ -245,7 +218,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Search request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Search request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Search failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
@@ -277,7 +250,7 @@ class FlacfetchClient:
|
||||
try:
|
||||
return await with_retry(self._download_impl, search_id, result_index, output_filename, gcs_path)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Download request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Download start failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
@@ -349,7 +322,7 @@ class FlacfetchClient:
|
||||
source_name, source_id, output_filename, target_file, download_url, gcs_path
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Download by ID request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
@@ -392,17 +365,15 @@ class FlacfetchClient:
|
||||
async def get_download_status(self, download_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get the current status of a download.
|
||||
|
||||
|
||||
Args:
|
||||
download_id: Download ID from start_download
|
||||
|
||||
|
||||
Returns:
|
||||
Status dict with progress, speed, path info
|
||||
|
||||
|
||||
Raises:
|
||||
httpx.RequestError: On network-level failures (connection refused, timeout, etc.)
|
||||
These are NOT wrapped so wait_for_download can handle retries.
|
||||
FlacfetchServiceError: On application-level failures (404, other HTTP errors)
|
||||
FlacfetchServiceError: On status check failure
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
@@ -413,10 +384,9 @@ class FlacfetchClient:
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError:
|
||||
# Let network errors bubble up so wait_for_download can handle retries
|
||||
raise
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Status request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
raise FlacfetchServiceError(f"Download not found: {download_id}")
|
||||
@@ -428,59 +398,35 @@ class FlacfetchClient:
|
||||
timeout: int = 600,
|
||||
poll_interval: float = 2.0,
|
||||
progress_callback: Optional[callable] = None,
|
||||
max_consecutive_errors: int = 3,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Wait for a download to complete.
|
||||
|
||||
Tolerates transient network errors during status polling. A single
|
||||
connection hiccup won't fail the entire download -- only N consecutive
|
||||
poll failures will.
|
||||
|
||||
|
||||
Args:
|
||||
download_id: Download ID to wait for
|
||||
timeout: Maximum wait time in seconds
|
||||
poll_interval: Time between status checks
|
||||
progress_callback: Optional callback(status_dict) for progress updates
|
||||
max_consecutive_errors: Number of consecutive poll failures before giving up
|
||||
|
||||
|
||||
Returns:
|
||||
Final status dict with output_path or gcs_path
|
||||
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On download failure, timeout, or too many consecutive poll errors
|
||||
FlacfetchServiceError: On download failure or timeout
|
||||
"""
|
||||
elapsed = 0.0
|
||||
consecutive_errors = 0
|
||||
|
||||
|
||||
while elapsed < timeout:
|
||||
try:
|
||||
status = await self.get_download_status(download_id)
|
||||
consecutive_errors = 0 # Reset on success
|
||||
except httpx.RequestError as e:
|
||||
consecutive_errors += 1
|
||||
error_desc = _format_httpx_error(e)
|
||||
logger.warning(
|
||||
f"Status poll failed for download {download_id} "
|
||||
f"({consecutive_errors}/{max_consecutive_errors}): {error_desc}"
|
||||
)
|
||||
if consecutive_errors >= max_consecutive_errors:
|
||||
raise FlacfetchServiceError(
|
||||
f"Status polling failed after {consecutive_errors} consecutive "
|
||||
f"network errors (last: {error_desc})"
|
||||
)
|
||||
await asyncio.sleep(poll_interval)
|
||||
elapsed += poll_interval
|
||||
continue
|
||||
|
||||
status = await self.get_download_status(download_id)
|
||||
|
||||
if progress_callback:
|
||||
try:
|
||||
progress_callback(status)
|
||||
except Exception as e:
|
||||
logger.warning(f"Progress callback error: {e}")
|
||||
|
||||
|
||||
download_status = status.get("status")
|
||||
|
||||
|
||||
if download_status in ["complete", "seeding"]:
|
||||
logger.info(f"Download {download_id} complete: {status.get('gcs_path') or status.get('output_path')}")
|
||||
return status
|
||||
@@ -489,7 +435,7 @@ class FlacfetchClient:
|
||||
raise FlacfetchServiceError(f"Download failed: {error}")
|
||||
elif download_status == "cancelled":
|
||||
raise FlacfetchServiceError("Download was cancelled")
|
||||
|
||||
|
||||
# Log progress
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
@@ -498,10 +444,10 @@ class FlacfetchClient:
|
||||
f"Download {download_id}: {progress:.1f}% "
|
||||
f"({speed:.1f} KB/s, {peers} peers)"
|
||||
)
|
||||
|
||||
|
||||
await asyncio.sleep(poll_interval)
|
||||
elapsed += poll_interval
|
||||
|
||||
|
||||
raise FlacfetchServiceError(f"Download timed out after {timeout}s")
|
||||
|
||||
async def list_torrents(self) -> Dict[str, Any]:
|
||||
@@ -522,7 +468,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"List torrents failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"List torrents failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"List torrents failed: {e.response.status_code}")
|
||||
|
||||
@@ -553,7 +499,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Delete torrent failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Delete torrent failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Delete torrent failed: {e.response.status_code}")
|
||||
|
||||
@@ -587,7 +533,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Cleanup failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Cleanup failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Cleanup failed: {e.response.status_code}")
|
||||
|
||||
@@ -628,7 +574,7 @@ class FlacfetchClient:
|
||||
return deleted
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Clear search cache request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Clear search cache request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"Clear search cache failed: {e.response.status_code} - {e.response.text}"
|
||||
@@ -658,7 +604,7 @@ class FlacfetchClient:
|
||||
return deleted_count
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Clear all cache request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Clear all cache request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"Clear all cache failed: {e.response.status_code} - {e.response.text}"
|
||||
@@ -685,7 +631,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Get cache stats request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Get cache stats request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"Get cache stats failed: {e.response.status_code} - {e.response.text}"
|
||||
|
||||
@@ -12,19 +12,13 @@ shared with YouTube credentials if scopes include drive.file.
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import ssl
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from tenacity import Retrying, stop_after_attempt, wait_exponential, retry_if_exception_type
|
||||
|
||||
from backend.config import get_settings
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Transient errors that indicate a stale HTTP connection (Cloud Run idle containers)
|
||||
TRANSIENT_ERRORS = (BrokenPipeError, ConnectionResetError, ConnectionError, ssl.SSLError)
|
||||
|
||||
|
||||
class GoogleDriveService:
|
||||
"""Google Drive operations using native API."""
|
||||
@@ -39,11 +33,6 @@ class GoogleDriveService:
|
||||
self._credentials_data: Optional[Dict[str, Any]] = None
|
||||
self._loaded = False
|
||||
|
||||
def _reset_service(self):
|
||||
"""Reset the cached Drive service to force a fresh connection on next use."""
|
||||
logger.info("Resetting Google Drive service connection")
|
||||
self._service = None
|
||||
|
||||
def _load_credentials(self) -> Optional[Dict[str, Any]]:
|
||||
"""Load OAuth credentials from Secret Manager."""
|
||||
if self._loaded:
|
||||
@@ -138,9 +127,6 @@ class GoogleDriveService:
|
||||
"""
|
||||
Get existing folder or create new one, return folder ID.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
parent_id: Parent folder ID
|
||||
folder_name: Name of folder to find or create
|
||||
@@ -148,41 +134,33 @@ class GoogleDriveService:
|
||||
Returns:
|
||||
Folder ID
|
||||
"""
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
|
||||
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
|
||||
|
||||
# Search for existing folder
|
||||
# Escape single quotes in folder name for Google Drive API query syntax
|
||||
escaped_folder_name = folder_name.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id, name)").execute()
|
||||
# Search for existing folder
|
||||
# Escape single quotes in folder name for Google Drive API query syntax
|
||||
escaped_folder_name = folder_name.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id, name)").execute()
|
||||
|
||||
if results.get("files"):
|
||||
folder_id = results["files"][0]["id"]
|
||||
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
if results.get("files"):
|
||||
folder_id = results["files"][0]["id"]
|
||||
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
|
||||
# Create folder
|
||||
logger.info(f"Creating new folder '{folder_name}'")
|
||||
metadata = {
|
||||
"name": folder_name,
|
||||
"mimeType": "application/vnd.google-apps.folder",
|
||||
"parents": [parent_id],
|
||||
}
|
||||
folder = self.service.files().create(body=metadata, fields="id").execute()
|
||||
folder_id = folder["id"]
|
||||
logger.info(f"Created folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
# Create folder
|
||||
logger.info(f"Creating new folder '{folder_name}'")
|
||||
metadata = {
|
||||
"name": folder_name,
|
||||
"mimeType": "application/vnd.google-apps.folder",
|
||||
"parents": [parent_id],
|
||||
}
|
||||
folder = self.service.files().create(body=metadata, fields="id").execute()
|
||||
folder_id = folder["id"]
|
||||
logger.info(f"Created folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
|
||||
def upload_file(
|
||||
self,
|
||||
@@ -194,9 +172,6 @@ class GoogleDriveService:
|
||||
"""
|
||||
Upload a file to a specific Drive folder.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
local_path: Local file path
|
||||
parent_id: Parent folder ID in Google Drive
|
||||
@@ -208,57 +183,49 @@ class GoogleDriveService:
|
||||
"""
|
||||
from googleapiclient.http import MediaFileUpload
|
||||
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
file_size = os.path.getsize(local_path)
|
||||
logger.info(
|
||||
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
|
||||
f"as '{filename}' to folder {parent_id}"
|
||||
)
|
||||
file_size = os.path.getsize(local_path)
|
||||
logger.info(
|
||||
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
|
||||
f"as '{filename}' to folder {parent_id}"
|
||||
)
|
||||
|
||||
# Determine MIME type
|
||||
ext = os.path.splitext(local_path)[1].lower()
|
||||
mime_types = {
|
||||
".mp4": "video/mp4",
|
||||
".mkv": "video/x-matroska",
|
||||
".zip": "application/zip",
|
||||
".flac": "audio/flac",
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
}
|
||||
mime_type = mime_types.get(ext, "application/octet-stream")
|
||||
# Determine MIME type
|
||||
ext = os.path.splitext(local_path)[1].lower()
|
||||
mime_types = {
|
||||
".mp4": "video/mp4",
|
||||
".mkv": "video/x-matroska",
|
||||
".zip": "application/zip",
|
||||
".flac": "audio/flac",
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
}
|
||||
mime_type = mime_types.get(ext, "application/octet-stream")
|
||||
|
||||
# Check for existing file with same name
|
||||
if replace_existing:
|
||||
# Escape single quotes in filename for Google Drive API query syntax
|
||||
escaped_filename = filename.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id)").execute()
|
||||
for existing_file in results.get("files", []):
|
||||
logger.info(f"Deleting existing file: {existing_file['id']}")
|
||||
self.service.files().delete(fileId=existing_file["id"]).execute()
|
||||
# Check for existing file with same name
|
||||
if replace_existing:
|
||||
# Escape single quotes in filename for Google Drive API query syntax
|
||||
escaped_filename = filename.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id)").execute()
|
||||
for existing_file in results.get("files", []):
|
||||
logger.info(f"Deleting existing file: {existing_file['id']}")
|
||||
self.service.files().delete(fileId=existing_file["id"]).execute()
|
||||
|
||||
# Upload file
|
||||
metadata = {"name": filename, "parents": [parent_id]}
|
||||
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
|
||||
# Upload file
|
||||
metadata = {"name": filename, "parents": [parent_id]}
|
||||
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
|
||||
|
||||
file_result = (
|
||||
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
|
||||
)
|
||||
file_id = file_result["id"]
|
||||
logger.info(f"Successfully uploaded '{filename}': {file_id}")
|
||||
return file_id
|
||||
file_result = (
|
||||
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
|
||||
)
|
||||
file_id = file_result["id"]
|
||||
logger.info(f"Successfully uploaded '{filename}': {file_id}")
|
||||
return file_id
|
||||
|
||||
def upload_to_public_share(
|
||||
self,
|
||||
@@ -341,9 +308,6 @@ class GoogleDriveService:
|
||||
"""
|
||||
Delete a file from Google Drive.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
file_id: Google Drive file ID to delete
|
||||
|
||||
@@ -353,17 +317,9 @@ class GoogleDriveService:
|
||||
logger.info(f"Deleting Google Drive file: {file_id}")
|
||||
|
||||
try:
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
self.service.files().delete(fileId=file_id).execute()
|
||||
logger.info(f"Successfully deleted file: {file_id}")
|
||||
return True
|
||||
self.service.files().delete(fileId=file_id).execute()
|
||||
logger.info(f"Successfully deleted file: {file_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
# Check if it's a 404 (already deleted)
|
||||
if hasattr(e, 'resp') and e.resp.status == 404:
|
||||
@@ -387,85 +343,6 @@ class GoogleDriveService:
|
||||
results[file_id] = self.delete_file(file_id)
|
||||
return results
|
||||
|
||||
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
|
||||
"""
|
||||
Search for files in public share subfolders matching a brand code prefix.
|
||||
|
||||
Used as a fallback when gdrive_files is not tracked in state_data (e.g., old
|
||||
jobs uploaded before file ID tracking was implemented, or jobs where GDrive
|
||||
upload succeeded but file IDs were not saved due to a bug).
|
||||
|
||||
Searches CDG/, MP4/, MP4-720p/ subfolders for files whose name starts with
|
||||
'{brand_code} - '.
|
||||
|
||||
Args:
|
||||
root_folder_id: Root Google Drive folder ID for the public share
|
||||
brand_code: Brand code prefix to search for (e.g., "NOMAD-1271")
|
||||
|
||||
Returns:
|
||||
List of file IDs found matching the brand code
|
||||
"""
|
||||
found_ids = []
|
||||
subfolders = ["CDG", "MP4", "MP4-720p"]
|
||||
search_errors: list[Exception] = []
|
||||
|
||||
for subfolder in subfolders:
|
||||
try:
|
||||
# Find the subfolder
|
||||
escaped_subfolder = subfolder.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(
|
||||
q=query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
if not results.get("files"):
|
||||
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
|
||||
continue
|
||||
|
||||
subfolder_id = results["files"][0]["id"]
|
||||
|
||||
# Search for files whose name starts with the brand code
|
||||
# Use contains for efficiency, then filter by exact prefix
|
||||
escaped_brand = brand_code.replace("'", "\\'")
|
||||
file_query = (
|
||||
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
|
||||
f"and trashed=false"
|
||||
)
|
||||
file_results = self.service.files().list(
|
||||
q=file_query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
for f in file_results.get("files", []):
|
||||
if f["name"].startswith(f"{brand_code} - "):
|
||||
found_ids.append(f["id"])
|
||||
logger.info(
|
||||
f"Found GDrive file to clean up in {subfolder}/: "
|
||||
f"{f['name']} ({f['id']})"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
search_errors.append(e)
|
||||
|
||||
if search_errors:
|
||||
# Raise so the caller knows the search was incomplete.
|
||||
# This prevents the cleanup endpoint from treating an uncertain result
|
||||
# as "GDrive is clean" and incorrectly recycling the brand code.
|
||||
raise RuntimeError(
|
||||
f"GDrive brand_code search incomplete: "
|
||||
f"{len(search_errors)}/{len(subfolders)} subfolder(s) failed"
|
||||
)
|
||||
|
||||
return found_ids
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_gdrive_service: Optional[GoogleDriveService] = None
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
"""
|
||||
GDrive Validator Cloud Function client.
|
||||
|
||||
Lightweight HTTP client for invoking the gdrive-validator Cloud Function
|
||||
from the backend (e.g., after job completion). Uses OIDC authentication
|
||||
via the backend's service account.
|
||||
|
||||
Fire-and-forget pattern: never blocks or fails the caller.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
|
||||
import requests
|
||||
import google.auth.transport.requests
|
||||
import google.oauth2.id_token
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Cloud Function URL - set via environment variable
|
||||
GDRIVE_VALIDATOR_URL = os.environ.get("GDRIVE_VALIDATOR_URL", "")
|
||||
|
||||
|
||||
def trigger_gdrive_validation() -> dict | None:
|
||||
"""
|
||||
Invoke the GDrive validator Cloud Function.
|
||||
|
||||
Uses the backend service account's OIDC token for authentication.
|
||||
|
||||
Returns:
|
||||
Parsed JSON response from the function, or None on error.
|
||||
"""
|
||||
if not GDRIVE_VALIDATOR_URL:
|
||||
logger.debug("GDRIVE_VALIDATOR_URL not set, skipping GDrive validation trigger")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Get OIDC token for the Cloud Function URL
|
||||
auth_request = google.auth.transport.requests.Request()
|
||||
token = google.oauth2.id_token.fetch_id_token(auth_request, GDRIVE_VALIDATOR_URL)
|
||||
|
||||
response = requests.post(
|
||||
GDRIVE_VALIDATOR_URL,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
status = result.get("status", "unknown")
|
||||
|
||||
if status == "issues_found":
|
||||
logger.warning("GDrive validation found issues (notification sent)")
|
||||
elif status == "ok":
|
||||
logger.info("GDrive validation: all clear")
|
||||
else:
|
||||
logger.info(f"GDrive validation returned status: {status}")
|
||||
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to trigger GDrive validation (non-fatal)")
|
||||
return None
|
||||
@@ -48,7 +48,7 @@ CREDIT_PACKAGES = {
|
||||
|
||||
# Made-for-you service package (not a credit package - creates a job directly)
|
||||
MADE_FOR_YOU_PACKAGE = {
|
||||
"price_cents": 5000, # $50.00
|
||||
"price_cents": 1500, # $15.00
|
||||
"name": "Made For You Karaoke Video",
|
||||
"description": "Professional 4K karaoke video with perfectly synced lyrics, delivered to your email within 24 hours",
|
||||
"images": ["https://gen.nomadkaraoke.com/nomad-logo.png"],
|
||||
|
||||
@@ -768,55 +768,6 @@ class UserService:
|
||||
logger.exception("Error enabling user")
|
||||
return False
|
||||
|
||||
def delete_user(self, email: str, admin_email: str) -> bool:
|
||||
"""
|
||||
Permanently delete a user and all their associated data.
|
||||
|
||||
Deletes: user document, sessions, magic links.
|
||||
Does NOT delete jobs (they remain as historical records).
|
||||
|
||||
Args:
|
||||
email: Email of the user to delete
|
||||
admin_email: Email/ID of the admin performing the action
|
||||
|
||||
Returns:
|
||||
True if user was deleted, False if user not found
|
||||
|
||||
Raises:
|
||||
ValueError: If trying to delete an admin user
|
||||
"""
|
||||
try:
|
||||
email = email.lower()
|
||||
user = self.get_user(email)
|
||||
|
||||
if not user:
|
||||
return False
|
||||
|
||||
if user.role == UserRole.ADMIN:
|
||||
raise ValueError("Cannot delete admin users")
|
||||
|
||||
# Revoke all active sessions
|
||||
self.revoke_all_sessions(email)
|
||||
|
||||
# Delete magic links for the user
|
||||
magic_links = self.db.collection(MAGIC_LINKS_COLLECTION).where(
|
||||
filter=FieldFilter('email', '==', email)
|
||||
).stream()
|
||||
for doc in magic_links:
|
||||
doc.reference.delete()
|
||||
|
||||
# Delete the user document
|
||||
self.db.collection(USERS_COLLECTION).document(email).delete()
|
||||
|
||||
logger.info(f"Admin {admin_email} permanently deleted user {email}")
|
||||
return True
|
||||
|
||||
except ValueError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(f"Error deleting user {email}")
|
||||
return False
|
||||
|
||||
def increment_jobs_completed(self, email: str) -> bool:
|
||||
"""Increment the completed jobs counter for a user using atomic increment."""
|
||||
try:
|
||||
|
||||
@@ -38,7 +38,6 @@ WORKER_QUEUES = {
|
||||
"render-video": "render-worker-queue",
|
||||
"video": "video-worker-queue",
|
||||
"idle-reminder": "idle-reminder-queue", # For delayed idle reminder checks
|
||||
"gdrive-validation": "gdrive-validation-queue", # For delayed post-job validation
|
||||
}
|
||||
|
||||
# Dispatch deadlines for each worker type (in seconds)
|
||||
@@ -52,15 +51,10 @@ WORKER_DISPATCH_DEADLINES = {
|
||||
"render-video": 1800, # 30 min - Video encoding can be slow
|
||||
"video": 1800, # 30 min - Video encoding can be slow
|
||||
"idle-reminder": 60, # 1 min - Quick check and potential email send
|
||||
"gdrive-validation": 120, # 2 min - Calls Cloud Function which validates GDrive
|
||||
}
|
||||
|
||||
# Default delay for idle reminders (seconds)
|
||||
IDLE_REMINDER_DELAY_SECONDS = 2 * 60 # 2 minutes
|
||||
|
||||
# Default delay for post-job GDrive validation (seconds)
|
||||
# Gives E2E tests time to verify output and clean up before validator runs
|
||||
GDRIVE_VALIDATION_DELAY_SECONDS = 5 * 60 # 5 minutes
|
||||
IDLE_REMINDER_DELAY_SECONDS = 5 * 60 # 5 minutes
|
||||
|
||||
|
||||
class WorkerService:
|
||||
@@ -588,93 +582,6 @@ class WorkerService:
|
||||
)
|
||||
return False
|
||||
|
||||
async def schedule_gdrive_validation(
|
||||
self,
|
||||
delay_seconds: int = GDRIVE_VALIDATION_DELAY_SECONDS
|
||||
) -> bool:
|
||||
"""
|
||||
Schedule a delayed GDrive validation check.
|
||||
|
||||
Fires after the specified delay so that E2E test cleanup completes
|
||||
before the validator runs, avoiding false "all clear" reports.
|
||||
|
||||
Args:
|
||||
delay_seconds: Delay before executing the validation (default: 5 minutes)
|
||||
|
||||
Returns:
|
||||
True if task was scheduled successfully, False otherwise
|
||||
"""
|
||||
if not self._use_cloud_tasks:
|
||||
logger.info(
|
||||
f"GDrive validation not scheduled (Cloud Tasks disabled). "
|
||||
f"Would have fired in {delay_seconds}s."
|
||||
)
|
||||
return True
|
||||
|
||||
try:
|
||||
from google.cloud import tasks_v2
|
||||
from google.protobuf import timestamp_pb2
|
||||
import time
|
||||
|
||||
queue_name = WORKER_QUEUES.get("gdrive-validation")
|
||||
if not queue_name:
|
||||
logger.error("GDrive validation queue not configured")
|
||||
return False
|
||||
|
||||
project = self.settings.google_cloud_project
|
||||
if not project:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
|
||||
# Build queue path
|
||||
parent = self.tasks_client.queue_path(project, location, queue_name)
|
||||
|
||||
# Build headers
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
if self._admin_token:
|
||||
headers["X-Admin-Token"] = self._admin_token
|
||||
|
||||
headers = inject_trace_context(headers)
|
||||
|
||||
# Calculate schedule time
|
||||
schedule_time = timestamp_pb2.Timestamp()
|
||||
schedule_time.FromSeconds(int(time.time()) + delay_seconds)
|
||||
|
||||
dispatch_deadline_seconds = WORKER_DISPATCH_DEADLINES.get("gdrive-validation", 120)
|
||||
|
||||
# Build task payload
|
||||
task = {
|
||||
"http_request": {
|
||||
"http_method": tasks_v2.HttpMethod.POST,
|
||||
"url": f"{self._base_url}/api/internal/trigger-gdrive-validation",
|
||||
"headers": headers,
|
||||
"body": b"{}",
|
||||
"oidc_token": {
|
||||
"service_account_email": f"karaoke-backend@{project}.iam.gserviceaccount.com",
|
||||
},
|
||||
},
|
||||
"schedule_time": schedule_time,
|
||||
"dispatch_deadline": duration_pb2.Duration(seconds=dispatch_deadline_seconds),
|
||||
}
|
||||
|
||||
response = self.tasks_client.create_task(parent=parent, task=task)
|
||||
logger.info(
|
||||
f"Scheduled GDrive validation in {delay_seconds}s: {response.name}"
|
||||
)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Failed to schedule GDrive validation: {e}",
|
||||
exc_info=True
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
# Global worker service instance
|
||||
_worker_service: Optional[WorkerService] = None
|
||||
|
||||
@@ -117,8 +117,7 @@ def mock_auth_dependency(request):
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Test admin token",
|
||||
is_admin=True,
|
||||
user_email="test@example.com",
|
||||
is_admin=True
|
||||
)
|
||||
|
||||
async def mock_require_admin():
|
||||
@@ -128,8 +127,7 @@ def mock_auth_dependency(request):
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Test admin token",
|
||||
is_admin=True,
|
||||
user_email="test@example.com",
|
||||
is_admin=True
|
||||
)
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
|
||||
@@ -115,7 +115,6 @@ class TestAudioSearchYouTubeFlow:
|
||||
async def test_torrent_download_does_not_use_youtube_service(self, mock_youtube_service, mock_services):
|
||||
"""
|
||||
When selecting a torrent result (RED/OPS), should NOT use YouTubeDownloadService.
|
||||
Should use FlacfetchClient directly instead.
|
||||
"""
|
||||
mock_job = mock_services['job_manager'].get_job.return_value
|
||||
mock_job.status = "awaiting_audio_selection"
|
||||
@@ -133,22 +132,16 @@ class TestAudioSearchYouTubeFlow:
|
||||
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
|
||||
# Mock audio_search_service for torrent download
|
||||
mock_audio_search_service = MagicMock()
|
||||
|
||||
# Mock FlacfetchClient for direct async download
|
||||
mock_flacfetch = MagicMock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-test-123")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/test/audio/test.flac",
|
||||
})
|
||||
mock_audio_search_service.is_remote_enabled = MagicMock(return_value=True)
|
||||
mock_result = MagicMock()
|
||||
mock_result.filepath = "gs://bucket/uploads/test/audio/test.flac"
|
||||
mock_audio_search_service.download_by_id = MagicMock(return_value=mock_result)
|
||||
|
||||
with patch(
|
||||
'backend.api.routes.audio_search.get_youtube_download_service',
|
||||
return_value=mock_youtube_service
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.get_flacfetch_client',
|
||||
return_value=mock_flacfetch
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.job_manager',
|
||||
mock_services['job_manager']
|
||||
@@ -159,6 +152,7 @@ class TestAudioSearchYouTubeFlow:
|
||||
'backend.api.routes.audio_search.worker_service',
|
||||
mock_services['worker_service']
|
||||
):
|
||||
# Call the download function (now runs as background task, returns None)
|
||||
await _download_audio_and_trigger_workers(
|
||||
job_id="test_job_123",
|
||||
selection_index=0,
|
||||
@@ -168,8 +162,8 @@ class TestAudioSearchYouTubeFlow:
|
||||
# YouTubeDownloadService should NOT be called for torrent
|
||||
mock_youtube_service.download_by_id.assert_not_called()
|
||||
|
||||
# FlacfetchClient.download_by_id should be called directly
|
||||
mock_flacfetch.download_by_id.assert_called_once()
|
||||
# audio_search_service.download_by_id should be called instead
|
||||
mock_audio_search_service.download_by_id.assert_called_once()
|
||||
|
||||
|
||||
class TestDirectUrlSubmissionFlow:
|
||||
|
||||
@@ -470,107 +470,3 @@ class TestDeleteOutputsGCSFinals:
|
||||
assert response.status_code == 200
|
||||
# Verify path format is jobs/{job_id}/finals/
|
||||
mock_storage.delete_folder.assert_called_once_with("jobs/abc-123-xyz/finals/")
|
||||
|
||||
|
||||
class TestDeleteOutputsBrandCodeRecycling:
|
||||
"""Tests for brand code recycling during output deletion."""
|
||||
|
||||
def test_brand_code_recycled_on_success(self, client, mock_complete_job):
|
||||
"""Test that brand code is recycled when Dropbox and GDrive cleanup succeed."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code') as mock_parse, \
|
||||
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
mock_parse.return_value = ("NOMAD", 1234)
|
||||
mock_svc = Mock()
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Brand code should be recycled (all services skip = success condition)
|
||||
assert "brand_code" in data["deleted_services"]
|
||||
assert data["deleted_services"]["brand_code"]["status"] == "recycled"
|
||||
assert data["deleted_services"]["brand_code"]["code"] == "NOMAD-1234"
|
||||
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 1234)
|
||||
|
||||
def test_brand_code_not_recycled_without_brand_code(self, client, mock_job_no_outputs):
|
||||
"""Test that no recycling happens when job has no brand code."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_no_outputs
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-456/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# No brand_code key in response since there's nothing to recycle
|
||||
assert "brand_code" not in data["deleted_services"]
|
||||
|
||||
def test_brand_code_skipped_when_dropbox_fails(self, client, mock_complete_job):
|
||||
"""Test that brand code is NOT recycled when Dropbox cleanup fails."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service') as mock_dropbox_svc:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
# Make Dropbox fail
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.side_effect = Exception("Dropbox error")
|
||||
mock_dropbox_svc.return_value = mock_dropbox
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["deleted_services"]["brand_code"]["status"] == "skipped"
|
||||
assert "incomplete" in data["deleted_services"]["brand_code"]["reason"].lower()
|
||||
|
||||
def test_brand_code_recycle_error_handled_gracefully(self, client, mock_complete_job):
|
||||
"""Test that brand code recycling errors don't crash the endpoint."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code') as mock_parse:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
# Make parse_brand_code raise an error
|
||||
mock_parse.side_effect = ValueError("Invalid brand code format")
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["deleted_services"]["brand_code"]["status"] == "failed"
|
||||
assert "Invalid brand code format" in data["deleted_services"]["brand_code"]["error"]
|
||||
@@ -1173,60 +1173,58 @@ class TestAudioSearchApiRouteDownload:
|
||||
|
||||
def test_remote_download_passes_gcs_path(self, mock_job_manager, mock_storage_service, mock_worker_service):
|
||||
"""
|
||||
Test that remote torrent downloads use FlacfetchClient directly with GCS path.
|
||||
Test that remote torrent downloads include GCS path for direct upload.
|
||||
|
||||
The route bypasses audio_search_service and calls flacfetch_client.download_by_id()
|
||||
directly to avoid event loop blocking.
|
||||
This was the bug: we were calling download() without gcs_path for
|
||||
torrent sources, causing flacfetch VM to return a local path that
|
||||
Cloud Run couldn't access.
|
||||
"""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
# Setup mock job with RED search result (includes source_id for download_by_id path)
|
||||
# Setup mock job with RED search result
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Unwanted',
|
||||
'artist': 'Avril Lavigne',
|
||||
'provider': 'RED',
|
||||
'provider': 'RED', # Torrent source
|
||||
'quality': 'FLAC 16bit CD',
|
||||
'source_id': 'torrent123',
|
||||
'target_file': 'Unwanted.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job.audio_search_artist = 'Avril Lavigne'
|
||||
mock_job.audio_search_title = 'Unwanted'
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
# Create mock audio search service with remote client
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = True
|
||||
|
||||
# Mock FlacfetchClient
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-123")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/job123/audio/Avril Lavigne - Unwanted.flac",
|
||||
})
|
||||
# Mock download to return GCS path
|
||||
mock_download_result = Mock()
|
||||
mock_download_result.filepath = "gs://bucket/uploads/job123/audio/Avril Lavigne - Unwanted.flac"
|
||||
mock_audio_service.download.return_value = mock_download_result
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job123",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
# Run the async function
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job123",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# CRITICAL: Verify FlacfetchClient.download_by_id was called with gcs_path
|
||||
mock_flacfetch.download_by_id.assert_called_once()
|
||||
call_kwargs = mock_flacfetch.download_by_id.call_args.kwargs
|
||||
# CRITICAL: Verify download was called with gcs_path for remote torrent source
|
||||
mock_audio_service.download.assert_called_once()
|
||||
call_kwargs = mock_audio_service.download.call_args.kwargs
|
||||
|
||||
# The gcs_path should be set for remote torrent downloads
|
||||
assert 'gcs_path' in call_kwargs
|
||||
assert call_kwargs['gcs_path'] == "uploads/job123/audio/"
|
||||
assert call_kwargs['source_name'] == 'RED'
|
||||
assert call_kwargs['source_id'] == 'torrent123'
|
||||
|
||||
def test_youtube_remote_download_uses_youtube_service(self, mock_job_manager, mock_storage_service, mock_worker_service):
|
||||
"""
|
||||
@@ -1345,7 +1343,7 @@ class TestAudioSearchApiRouteDownload:
|
||||
mock_youtube_service.download_by_id.assert_called_once()
|
||||
|
||||
def test_handles_gcs_path_response_correctly(self, mock_job_manager, mock_storage_service, mock_worker_service):
|
||||
"""Test that GCS path responses from FlacfetchClient are parsed correctly."""
|
||||
"""Test that GCS path responses are parsed correctly."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
@@ -1357,35 +1355,31 @@ class TestAudioSearchApiRouteDownload:
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'torrent789',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
# Create mock audio search service
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = True
|
||||
|
||||
# Mock FlacfetchClient returning full GCS path
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-789")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://karaoke-gen-bucket/uploads/job789/audio/test.flac",
|
||||
})
|
||||
# Mock download to return full GCS path
|
||||
mock_download_result = Mock()
|
||||
mock_download_result.filepath = "gs://karaoke-gen-bucket/uploads/job789/audio/test.flac"
|
||||
mock_audio_service.download.return_value = mock_download_result
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job789",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
# Run the async function
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job789",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Verify job was updated with correct GCS path (without gs://bucket/ prefix)
|
||||
update_calls = mock_job_manager.update_job.call_args_list
|
||||
@@ -1404,9 +1398,9 @@ class TestAudioSearchApiRouteDownload:
|
||||
|
||||
def test_torrent_download_requires_remote(self, mock_job_manager, mock_storage_service):
|
||||
"""
|
||||
Test that torrent sources (RED/OPS) require remote flacfetch client.
|
||||
Test that torrent sources (RED/OPS) require remote flacfetch.
|
||||
|
||||
When get_flacfetch_client() returns None, the job should be failed.
|
||||
When running as a background task, the error is caught and the job is failed.
|
||||
"""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
@@ -1423,21 +1417,22 @@ class TestAudioSearchApiRouteDownload:
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
# Create mock audio search service WITHOUT remote client
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = False
|
||||
|
||||
# No flacfetch client configured
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=None):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_no_remote",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
# The background task catches exceptions and fails the job
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_no_remote",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Verify the job was failed with an appropriate error message
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
@@ -1569,35 +1564,27 @@ class TestAudioSearchApiRouteDownload:
|
||||
'artist': 'Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'torrent_w',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = True
|
||||
mock_download_result = Mock()
|
||||
mock_download_result.filepath = "gs://bucket/uploads/job_w/audio/test.flac"
|
||||
mock_audio_service.download.return_value = mock_download_result
|
||||
|
||||
# Mock FlacfetchClient
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-w")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/job_w/audio/test.flac",
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_w",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_w",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Both workers should be triggered
|
||||
mock_worker_service.trigger_audio_worker.assert_called_once_with("job_w")
|
||||
@@ -1622,32 +1609,26 @@ class TestAudioSearchApiRouteDownload:
|
||||
'artist': 'Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'torrent_err',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
mock_audio_service.is_remote_enabled.return_value = True
|
||||
mock_audio_service.download.side_effect = RuntimeError("Unexpected connection error")
|
||||
|
||||
# Mock FlacfetchClient that raises an error
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(side_effect=RuntimeError("Unexpected connection error"))
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
# Should not raise - background tasks catch all exceptions
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_err",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
# Should not raise - background tasks catch all exceptions
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_err",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Job should be failed with error message
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
@@ -1655,502 +1636,3 @@ class TestAudioSearchApiRouteDownload:
|
||||
assert fail_args.args[0] == "job_err"
|
||||
assert "Unexpected connection error" in fail_args.args[1]
|
||||
|
||||
|
||||
class TestAsyncEventLoopFixes:
|
||||
"""
|
||||
Tests for the async event loop blocking fixes.
|
||||
|
||||
Verifies that:
|
||||
- Background tasks use FlacfetchClient async methods directly (RED/OPS/Spotify)
|
||||
- Background tasks use asyncio.to_thread for generic downloads
|
||||
- Search endpoint uses search_async instead of sync search
|
||||
- InsufficientCreditsError propagates as 402, not 500
|
||||
- FlacfetchServiceError is handled in background tasks
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(self):
|
||||
with patch('backend.api.routes.audio_search.job_manager') as mock:
|
||||
yield mock
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage_service(self):
|
||||
with patch('backend.api.routes.audio_search.storage_service') as mock:
|
||||
yield mock
|
||||
|
||||
@pytest.fixture
|
||||
def mock_worker_service(self):
|
||||
with patch('backend.api.routes.audio_search.get_worker_service') as mock:
|
||||
worker = Mock()
|
||||
worker.trigger_audio_worker = AsyncMock()
|
||||
worker.trigger_lyrics_worker = AsyncMock()
|
||||
mock.return_value = worker
|
||||
yield worker
|
||||
|
||||
def test_spotify_download_uses_flacfetch_client_directly(
|
||||
self, mock_job_manager, mock_storage_service, mock_worker_service
|
||||
):
|
||||
"""Spotify downloads should use FlacfetchClient.download_by_id() directly."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Blinding Lights',
|
||||
'artist': 'The Weeknd',
|
||||
'provider': 'Spotify',
|
||||
'quality': 'OGG 320kbps',
|
||||
'source_id': 'spotify:track:0VjIjW4GlUZAMYd2vXMi3b',
|
||||
'url': 'https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-spotify-1")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/job_sp/audio/The Weeknd - Blinding Lights.ogg",
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_sp",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Verify FlacfetchClient was used directly (not audio_search_service)
|
||||
mock_flacfetch.download_by_id.assert_called_once()
|
||||
call_kwargs = mock_flacfetch.download_by_id.call_args.kwargs
|
||||
assert call_kwargs['source_name'] == 'Spotify'
|
||||
assert call_kwargs['source_id'] == 'spotify:track:0VjIjW4GlUZAMYd2vXMi3b'
|
||||
assert call_kwargs['gcs_path'] == 'uploads/job_sp/audio/'
|
||||
|
||||
mock_flacfetch.wait_for_download.assert_called_once()
|
||||
|
||||
# audio_search_service.download_by_id should NOT be called
|
||||
mock_audio_service.download_by_id.assert_not_called()
|
||||
|
||||
def test_spotify_download_requires_flacfetch_client(self, mock_job_manager, mock_storage_service):
|
||||
"""Spotify download should fail job when FlacfetchClient is not configured."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Test',
|
||||
'provider': 'Spotify',
|
||||
'quality': 'OGG',
|
||||
'source_id': 'spotify:track:abc',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=None):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_sp_err",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "flacfetch" in mock_job_manager.fail_job.call_args.args[1].lower()
|
||||
|
||||
def test_generic_download_uses_asyncio_to_thread(self, mock_job_manager, mock_storage_service, mock_worker_service):
|
||||
"""Generic/unknown source downloads should use asyncio.to_thread to avoid blocking."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
import tempfile
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test Song',
|
||||
'artist': 'Unknown Artist',
|
||||
'provider': 'SomeNewSource',
|
||||
'quality': 'MP3',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
# Create a temporary file to simulate a downloaded file
|
||||
tmp = tempfile.NamedTemporaryFile(suffix='.mp3', delete=False)
|
||||
tmp.write(b'fake audio data')
|
||||
tmp.close()
|
||||
|
||||
mock_download_result = Mock()
|
||||
mock_download_result.filepath = tmp.name
|
||||
|
||||
mock_audio_service.download.return_value = mock_download_result
|
||||
|
||||
with patch('backend.api.routes.audio_search.asyncio') as mock_asyncio:
|
||||
# Make to_thread return a coroutine that returns the mock result
|
||||
mock_asyncio.to_thread = AsyncMock(return_value=mock_download_result)
|
||||
mock_asyncio.gather = AsyncMock()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_generic",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Verify asyncio.to_thread was called (not direct sync call)
|
||||
mock_asyncio.to_thread.assert_called_once()
|
||||
|
||||
# Cleanup
|
||||
import os
|
||||
try:
|
||||
os.unlink(tmp.name)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_red_download_without_source_id_uses_search_download(
|
||||
self, mock_job_manager, mock_storage_service, mock_worker_service
|
||||
):
|
||||
"""RED download without source_id should use flacfetch_client.download() with search_id."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
# No source_id — triggers the search-based download path
|
||||
}],
|
||||
'remote_search_id': 'search-abc-123',
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download = AsyncMock(return_value="dl-search-1")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/job_nosrc/audio/test.flac",
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_nosrc",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Should use flacfetch_client.download() (not download_by_id)
|
||||
mock_flacfetch.download.assert_called_once()
|
||||
call_kwargs = mock_flacfetch.download.call_args.kwargs
|
||||
assert call_kwargs['search_id'] == 'search-abc-123'
|
||||
assert call_kwargs['result_index'] == 0
|
||||
assert call_kwargs['gcs_path'] == 'uploads/job_nosrc/audio/'
|
||||
|
||||
def test_flacfetch_service_error_handled_in_background_task(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""FlacfetchServiceError should be caught and job should be failed."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
from backend.services.flacfetch_client import FlacfetchServiceError
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Artist',
|
||||
'provider': 'OPS',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'ops123',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(
|
||||
side_effect=FlacfetchServiceError("Connection refused")
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_fserr",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "Connection refused" in mock_job_manager.fail_job.call_args.args[1]
|
||||
|
||||
def test_wait_for_download_no_filepath_fails_job(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""If wait_for_download returns no filepath, job should be failed."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'torrent_nofp',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
# wait_for_download returns status without gcs_path or output_path
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-nofp")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
# No gcs_path or output_path
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_nofp",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "no file path" in mock_job_manager.fail_job.call_args.args[1].lower()
|
||||
|
||||
def test_spotify_wait_for_download_no_filepath_fails_job(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""Spotify: if wait_for_download returns no filepath, job should be failed."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Artist',
|
||||
'provider': 'Spotify',
|
||||
'quality': 'OGG',
|
||||
'source_id': 'spotify:track:nofp',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_flacfetch = Mock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-sp-nofp")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
})
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_sp_nofp",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "no file path" in mock_job_manager.fail_job.call_args.args[1].lower()
|
||||
|
||||
def test_youtube_download_error_fails_job(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""YouTubeDownloadError should be caught and job failed."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
from backend.services.youtube_download_service import YouTubeDownloadError
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Deleted Video',
|
||||
'artist': 'Unknown',
|
||||
'provider': 'YouTube',
|
||||
'quality': 'Opus',
|
||||
'source_id': 'deleted123',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_youtube_service = Mock()
|
||||
mock_youtube_service.download_by_id = AsyncMock(
|
||||
side_effect=YouTubeDownloadError("Video unavailable")
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_yt_err",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "Video unavailable" in mock_job_manager.fail_job.call_args.args[1]
|
||||
|
||||
def test_youtube_no_video_id_fails_job(
|
||||
self, mock_job_manager, mock_storage_service
|
||||
):
|
||||
"""YouTube download with no source_id and no extractable video ID should fail."""
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
import asyncio
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Bad Link',
|
||||
'artist': 'Unknown',
|
||||
'provider': 'YouTube',
|
||||
'quality': 'Opus',
|
||||
# No source_id
|
||||
'url': 'https://example.com/not-youtube',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
mock_audio_service = Mock()
|
||||
|
||||
mock_youtube_service = Mock()
|
||||
mock_youtube_service._extract_video_id = Mock(return_value=None)
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_download_audio_and_trigger_workers(
|
||||
job_id="job_yt_noid",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_service,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_manager.fail_job.assert_called_once()
|
||||
assert "video ID" in mock_job_manager.fail_job.call_args.args[1] or \
|
||||
"No video" in mock_job_manager.fail_job.call_args.args[1]
|
||||
|
||||
|
||||
class TestSearchAsyncUsage:
|
||||
"""Tests that the search endpoint uses search_async instead of sync search."""
|
||||
|
||||
def test_search_async_uses_get_running_loop(self):
|
||||
"""search_async should use asyncio.get_running_loop() (not deprecated get_event_loop)."""
|
||||
import asyncio
|
||||
import inspect
|
||||
|
||||
source = inspect.getsource(AudioSearchService.search_async)
|
||||
assert 'get_running_loop' in source
|
||||
assert 'get_event_loop' not in source
|
||||
|
||||
def test_download_async_uses_get_running_loop(self):
|
||||
"""download_async should use asyncio.get_running_loop()."""
|
||||
import inspect
|
||||
|
||||
source = inspect.getsource(AudioSearchService.download_async)
|
||||
assert 'get_running_loop' in source
|
||||
assert 'get_event_loop' not in source
|
||||
|
||||
def test_download_by_id_async_uses_get_running_loop(self):
|
||||
"""download_by_id_async should use asyncio.get_running_loop()."""
|
||||
import inspect
|
||||
|
||||
source = inspect.getsource(AudioSearchService.download_by_id_async)
|
||||
assert 'get_running_loop' in source
|
||||
assert 'get_event_loop' not in source
|
||||
|
||||
def test_search_endpoint_calls_search_async(self):
|
||||
"""Verify the search endpoint source calls search_async, not sync search."""
|
||||
import inspect
|
||||
from backend.api.routes.audio_search import search_audio
|
||||
|
||||
source = inspect.getsource(search_audio)
|
||||
assert 'search_async' in source
|
||||
# Should NOT have a bare .search( call (which is sync)
|
||||
# But it may have search_async( which contains "search" — so check specifically
|
||||
# that search_async is used and not audio_search_service.search(
|
||||
assert 'await audio_search_service.search_async(' in source
|
||||
|
||||
|
||||
class TestInsufficientCreditsErrorPropagation:
|
||||
"""Test that InsufficientCreditsError propagates correctly as 402."""
|
||||
|
||||
def test_exception_handler_uses_isinstance(self):
|
||||
"""
|
||||
Verify the exception handler uses isinstance() for InsufficientCreditsError.
|
||||
|
||||
This is robust against class identity issues from module reloading.
|
||||
"""
|
||||
import inspect
|
||||
from backend.api.routes.audio_search import search_audio
|
||||
|
||||
source = inspect.getsource(search_audio)
|
||||
assert 'isinstance(e, (InsufficientCreditsError, RateLimitExceededError))' in source
|
||||
|
||||
@@ -1,381 +0,0 @@
|
||||
"""
|
||||
Tests for the cleanup-distribution endpoint in jobs.py.
|
||||
|
||||
Verifies:
|
||||
- GDrive cleanup uses tracked file IDs from state_data when available (fast path)
|
||||
- GDrive cleanup falls back to brand_code search when gdrive_files is empty (fallback path)
|
||||
- Brand code is recycled ONLY after both Dropbox AND GDrive are confirmed clean
|
||||
- Brand code is NOT recycled when GDrive cleanup fails or is skipped
|
||||
- Endpoint returns correct status for each distribution service
|
||||
|
||||
The cleanup-distribution endpoint is used by the E2E happy-path test (Step 12)
|
||||
to remove test job files from YouTube, Dropbox, and Google Drive after the test.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from backend.api.routes.jobs import router
|
||||
from backend.api.dependencies import require_admin, require_auth, AuthResult, UserType
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# ─── Test App ────────────────────────────────────────────────────────────────
|
||||
|
||||
def get_mock_admin():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
app.dependency_overrides[require_auth] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
# ─── Fixtures ────────────────────────────────────────────────────────────────
|
||||
|
||||
def _make_job(
|
||||
*,
|
||||
brand_code="NOMAD-1271",
|
||||
gdrive_files=None,
|
||||
gdrive_folder_id="root-folder-id",
|
||||
dropbox_path="/Tracks-PublicShare",
|
||||
artist="piri",
|
||||
title="dog",
|
||||
):
|
||||
"""Make a mock Job in COMPLETE state with the given distribution data."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-id"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.artist = artist
|
||||
job.title = title
|
||||
job.dropbox_path = dropbox_path
|
||||
job.gdrive_folder_id = gdrive_folder_id
|
||||
job.state_data = {
|
||||
"brand_code": brand_code,
|
||||
"gdrive_files": gdrive_files if gdrive_files is not None else {},
|
||||
}
|
||||
return job
|
||||
|
||||
|
||||
# ─── GDrive Cleanup — Fast Path (tracked file IDs) ───────────────────────────
|
||||
|
||||
class TestCleanupDistributionGDriveTrackedFileIDs:
|
||||
"""GDrive cleanup uses tracked file IDs from state_data when available."""
|
||||
|
||||
def test_gdrive_cleanup_uses_tracked_file_ids(self, client):
|
||||
"""When gdrive_files has file IDs, delete_files is called with those IDs."""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"file-id-mp4": True, "file-id-cdg": True}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Should have used the tracked file IDs (fast path)
|
||||
mock_gdrive.delete_files.assert_called_once_with(["file-id-mp4", "file-id-cdg"])
|
||||
# Should NOT have searched by brand code
|
||||
mock_gdrive.find_files_by_brand_code.assert_not_called()
|
||||
|
||||
assert data["gdrive"]["status"] == "success"
|
||||
|
||||
def test_gdrive_cleanup_reports_partial_when_some_deletes_fail(self, client):
|
||||
"""When some file deletes fail, status is 'partial'."""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"file-id-mp4": True,
|
||||
"file-id-cdg": False, # This one failed
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["gdrive"]["status"] == "partial"
|
||||
|
||||
|
||||
# ─── GDrive Cleanup — Fallback Path (brand_code search) ──────────────────────
|
||||
|
||||
class TestCleanupDistributionGDriveFallback:
|
||||
"""GDrive cleanup searches by brand_code when gdrive_files is empty."""
|
||||
|
||||
def test_falls_back_to_brand_code_search_when_gdrive_files_empty(self, client):
|
||||
"""When gdrive_files={}, search GDrive by brand_code and delete found files."""
|
||||
job = _make_job(gdrive_files={}) # Empty — simulates old jobs / silently-failed uploads
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
# find_files_by_brand_code returns file IDs found by searching GDrive
|
||||
mock_gdrive.find_files_by_brand_code.return_value = ["old-file-id-cdg", "old-file-id-mp4"]
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"old-file-id-cdg": True,
|
||||
"old-file-id-mp4": True,
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Should have searched by brand code (fallback path)
|
||||
mock_gdrive.find_files_by_brand_code.assert_called_once_with(
|
||||
"root-folder-id", "NOMAD-1271"
|
||||
)
|
||||
# Should have deleted the found files
|
||||
mock_gdrive.delete_files.assert_called_once()
|
||||
assert data["gdrive"]["status"] == "success"
|
||||
|
||||
def test_falls_back_to_brand_code_search_when_gdrive_files_none(self, client):
|
||||
"""When gdrive_files not in state_data (old job), search by brand_code."""
|
||||
job = _make_job(gdrive_files=None)
|
||||
job.state_data = {"brand_code": "NOMAD-1271"} # No gdrive_files key at all
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = ["legacy-file-id"]
|
||||
mock_gdrive.delete_files.return_value = {"legacy-file-id": True}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_gdrive.find_files_by_brand_code.assert_called_once()
|
||||
|
||||
def test_reports_skipped_when_no_files_found_by_brand_code(self, client):
|
||||
"""When brand_code search finds nothing, GDrive status is 'skipped'."""
|
||||
job = _make_job(gdrive_files={})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = [] # Nothing found
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["gdrive"]["status"] == "skipped"
|
||||
assert "no files found" in data["gdrive"]["reason"]
|
||||
|
||||
|
||||
# ─── Brand Code Recycling — Gated on GDrive Success ──────────────────────────
|
||||
|
||||
class TestCleanupDistributionBrandCodeRecycling:
|
||||
"""Brand code is recycled only after BOTH Dropbox AND GDrive are confirmed clean."""
|
||||
|
||||
def test_brand_code_recycled_when_both_dropbox_and_gdrive_cleaned(self, client):
|
||||
"""Brand code is recycled when Dropbox delete succeeds and GDrive cleanup succeeds."""
|
||||
job = _make_job(gdrive_files={"cdg": "file-id"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True # Dropbox success
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"file-id": True} # GDrive success
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Brand code should be recycled
|
||||
mock_brand_service.recycle_brand_code.assert_called_once()
|
||||
assert data["dropbox"].get("recycled_brand_code") is True
|
||||
|
||||
def test_brand_code_not_recycled_when_gdrive_cleanup_partial(self, client):
|
||||
"""Brand code is NOT recycled when GDrive delete only partially succeeded.
|
||||
|
||||
If GDrive still has files with this brand code, recycling would allow a new
|
||||
job to get the same brand code, creating a duplicate in the public share.
|
||||
"""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True # Dropbox success
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"file-id-mp4": True,
|
||||
"file-id-cdg": False, # CDG file still on GDrive
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Brand code should NOT be recycled because GDrive still has a file
|
||||
mock_brand_service.recycle_brand_code.assert_not_called()
|
||||
# recycled_brand_code key should be absent (recycling never attempted)
|
||||
assert "recycled_brand_code" not in data.get("dropbox", {})
|
||||
|
||||
def test_brand_code_not_recycled_when_gdrive_not_configured(self, client):
|
||||
"""Brand code is NOT recycled when GDrive is not configured.
|
||||
|
||||
Without GDrive credentials, we cannot confirm that GDrive was cleaned.
|
||||
A previous upload may have succeeded (e.g., different credentials rotation).
|
||||
"""
|
||||
job = _make_job(gdrive_files={"cdg": "file-id"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = False # GDrive not configured
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
# Brand code NOT recycled — GDrive might still have files
|
||||
mock_brand_service.recycle_brand_code.assert_not_called()
|
||||
|
||||
def test_brand_code_recycled_when_gdrive_finds_nothing_to_delete(self, client):
|
||||
"""Brand code IS recycled when GDrive search finds nothing (already clean)."""
|
||||
job = _make_job(gdrive_files={}) # Empty — no tracked IDs
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = [] # GDrive already clean
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# GDrive was confirmed clean (nothing found), so brand code IS recycled
|
||||
mock_brand_service.recycle_brand_code.assert_called_once()
|
||||
assert data["dropbox"].get("recycled_brand_code") is True
|
||||
@@ -19,7 +19,6 @@ import httpx
|
||||
from backend.services.flacfetch_client import (
|
||||
FlacfetchClient,
|
||||
FlacfetchServiceError,
|
||||
_format_httpx_error,
|
||||
get_flacfetch_client,
|
||||
reset_flacfetch_client,
|
||||
)
|
||||
@@ -828,223 +827,3 @@ class TestFlacfetchRetryLogic:
|
||||
assert result == "test789"
|
||||
assert mock_client.post.call_count == 3
|
||||
|
||||
|
||||
class TestFormatHttpxError:
|
||||
"""Test _format_httpx_error helper for descriptive error messages."""
|
||||
|
||||
def test_formats_error_with_message(self):
|
||||
"""Test formatting when str(error) has content."""
|
||||
error = httpx.ConnectError("Connection refused")
|
||||
result = _format_httpx_error(error)
|
||||
assert result == "ConnectError: Connection refused"
|
||||
|
||||
def test_formats_error_with_empty_message(self):
|
||||
"""Test formatting when str(error) is empty -- the exact case from job c6b1b00f."""
|
||||
request = httpx.Request("GET", "http://10.128.0.41:8080/download/dl_abc/status")
|
||||
error = httpx.ConnectError("", request=request)
|
||||
result = _format_httpx_error(error)
|
||||
# Should include class name and URL context, NOT be empty
|
||||
assert "ConnectError" in result
|
||||
assert "GET" in result
|
||||
assert "10.128.0.41" in result
|
||||
|
||||
def test_formats_error_with_empty_message_no_request(self):
|
||||
"""Test formatting when both str and request are unavailable."""
|
||||
# Use base RequestError which doesn't require request in constructor
|
||||
error = httpx.RequestError("")
|
||||
result = _format_httpx_error(error)
|
||||
# Should at minimum return the class name
|
||||
assert result == "RequestError"
|
||||
|
||||
def test_formats_timeout_error(self):
|
||||
"""Test formatting of timeout errors."""
|
||||
error = httpx.ReadTimeout("timed out")
|
||||
result = _format_httpx_error(error)
|
||||
assert result == "ReadTimeout: timed out"
|
||||
|
||||
def test_formats_non_httpx_error(self):
|
||||
"""Test formatting of a generic exception."""
|
||||
error = ValueError("bad value")
|
||||
result = _format_httpx_error(error)
|
||||
assert result == "ValueError: bad value"
|
||||
|
||||
|
||||
class TestWaitForDownloadRetryTolerance:
|
||||
"""Test that wait_for_download tolerates transient poll failures."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tolerates_single_poll_failure(self):
|
||||
"""Test that a single transient error doesn't fail the download."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
call_count = 0
|
||||
async def mock_get_status(download_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count == 2:
|
||||
raise httpx.ConnectError("transient failure")
|
||||
if call_count >= 3:
|
||||
return {"status": "complete", "gcs_path": "gs://bucket/test.flac"}
|
||||
return {"status": "downloading", "progress": 50.0}
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
result = await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01
|
||||
)
|
||||
assert result["status"] == "complete"
|
||||
assert call_count == 3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tolerates_two_consecutive_failures(self):
|
||||
"""Test that two consecutive errors don't fail with default threshold of 3."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
mock_request = httpx.Request("GET", "http://localhost:8080/download/dl_test/status")
|
||||
|
||||
call_count = 0
|
||||
async def mock_get_status(download_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count in (2, 3):
|
||||
raise httpx.ConnectError("", request=mock_request)
|
||||
if call_count >= 4:
|
||||
return {"status": "complete", "gcs_path": "gs://bucket/test.flac"}
|
||||
return {"status": "downloading", "progress": 25.0}
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
result = await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01
|
||||
)
|
||||
assert result["status"] == "complete"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fails_after_max_consecutive_errors(self):
|
||||
"""Test that 3 consecutive errors (default) fails with descriptive message."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
call_count = 0
|
||||
async def mock_get_status(download_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count == 1:
|
||||
return {"status": "downloading", "progress": 10.0}
|
||||
# All subsequent polls fail
|
||||
raise httpx.ConnectError("connection reset")
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
with pytest.raises(FlacfetchServiceError) as exc_info:
|
||||
await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01
|
||||
)
|
||||
|
||||
error_msg = str(exc_info.value)
|
||||
assert "3 consecutive" in error_msg
|
||||
assert "ConnectError" in error_msg
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resets_error_count_on_success(self):
|
||||
"""Test that a successful poll resets the consecutive error counter."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
mock_request = httpx.Request("GET", "http://localhost:8080/download/dl_test/status")
|
||||
|
||||
call_count = 0
|
||||
async def mock_get_status(download_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
# Fail twice, succeed, fail twice, succeed, complete
|
||||
if call_count in (1, 2):
|
||||
raise httpx.ConnectError("", request=mock_request)
|
||||
if call_count == 3:
|
||||
return {"status": "downloading", "progress": 25.0}
|
||||
if call_count in (4, 5):
|
||||
raise httpx.ConnectError("", request=mock_request)
|
||||
if call_count == 6:
|
||||
return {"status": "downloading", "progress": 75.0}
|
||||
return {"status": "complete", "gcs_path": "gs://bucket/test.flac"}
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
result = await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01
|
||||
)
|
||||
assert result["status"] == "complete"
|
||||
assert call_count == 7 # 2 fail + 1 ok + 2 fail + 1 ok + 1 complete
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_max_consecutive_errors(self):
|
||||
"""Test configuring a different consecutive error threshold."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
async def mock_get_status(download_id):
|
||||
raise httpx.ReadError("read failed")
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
with pytest.raises(FlacfetchServiceError) as exc_info:
|
||||
await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01,
|
||||
max_consecutive_errors=5,
|
||||
)
|
||||
|
||||
assert "5 consecutive" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_error_message_includes_error_type_for_empty_str(self):
|
||||
"""Test the exact scenario from job c6b1b00f: empty httpx error string."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
mock_request = httpx.Request("GET", "http://10.128.0.41:8080/download/dl_e93031543e96/status")
|
||||
|
||||
async def mock_get_status(download_id):
|
||||
# Simulate the exact error from job c6b1b00f -- empty string
|
||||
raise httpx.ConnectError("", request=mock_request)
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
with pytest.raises(FlacfetchServiceError) as exc_info:
|
||||
await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01,
|
||||
)
|
||||
|
||||
error_msg = str(exc_info.value)
|
||||
# Must contain useful info, NOT just "Status request failed: "
|
||||
assert "ConnectError" in error_msg
|
||||
assert "consecutive" in error_msg
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_application_errors_still_fail_immediately(self):
|
||||
"""Test that FlacfetchServiceError (download not found, etc.) still fails immediately."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
async def mock_get_status(download_id):
|
||||
raise FlacfetchServiceError("Download not found: dl_test")
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="Download not found"):
|
||||
await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01,
|
||||
)
|
||||
|
||||
@@ -9,7 +9,6 @@ These tests mock the Google API client and Secret Manager to verify:
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
|
||||
@@ -502,451 +501,24 @@ class TestUploadToPublicShare:
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
class TestRetryBehavior:
|
||||
"""Test retry behavior for transient connection errors."""
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_retries_on_broken_pipe(self, mock_get_settings):
|
||||
"""Test that BrokenPipeError triggers retry and succeeds on second attempt."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# First call raises BrokenPipeError, second succeeds
|
||||
mock_list_result.execute.side_effect = [
|
||||
BrokenPipeError("[Errno 32] Broken pipe"),
|
||||
{"files": [{"id": "folder-123", "name": "MP4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to clear but re-set the mock (avoid real OAuth)
|
||||
def mock_reset():
|
||||
service._service = mock_drive
|
||||
|
||||
service._reset_service = mock_reset
|
||||
|
||||
folder_id = service.get_or_create_folder("parent-123", "MP4")
|
||||
assert folder_id == "folder-123"
|
||||
assert mock_list_result.execute.call_count == 2
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_gives_up_after_3_attempts(self, mock_get_settings):
|
||||
"""Test that 3 consecutive failures raises the exception."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = BrokenPipeError("[Errno 32] Broken pipe")
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to re-set the mock (avoid real OAuth)
|
||||
service._reset_service = lambda: setattr(service, '_service', mock_drive)
|
||||
|
||||
with pytest.raises(BrokenPipeError):
|
||||
service.get_or_create_folder("parent-123", "MP4")
|
||||
|
||||
assert mock_list_result.execute.call_count == 3
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_service_reset_on_retry(self, mock_get_settings):
|
||||
"""Test that _service is reset to None between retry attempts."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
BrokenPipeError("[Errno 32] Broken pipe"),
|
||||
{"files": [{"id": "folder-123", "name": "MP4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to track calls but still do the reset
|
||||
original_reset = service._reset_service
|
||||
reset_calls = []
|
||||
|
||||
def tracked_reset():
|
||||
reset_calls.append(True)
|
||||
original_reset()
|
||||
# Re-set mock service so the retry works
|
||||
service._service = mock_drive
|
||||
|
||||
service._reset_service = tracked_reset
|
||||
|
||||
folder_id = service.get_or_create_folder("parent-123", "MP4")
|
||||
assert folder_id == "folder-123"
|
||||
assert len(reset_calls) == 1 # Reset called once between attempt 1 and 2
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_retries_on_ssl_error(self, mock_get_settings):
|
||||
"""Test that SSLError triggers retry."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
ssl.SSLError("SSL: UNEXPECTED_EOF_WHILE_READING"),
|
||||
{"files": [{"id": "folder-123", "name": "MP4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to re-set the mock (avoid real OAuth)
|
||||
service._reset_service = lambda: setattr(service, '_service', mock_drive)
|
||||
|
||||
folder_id = service.get_or_create_folder("parent-123", "MP4")
|
||||
assert folder_id == "folder-123"
|
||||
assert mock_list_result.execute.call_count == 2
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_no_retry_on_non_transient_error(self, mock_get_settings):
|
||||
"""Test that non-transient errors are not retried."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = ValueError("bad value")
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
service.get_or_create_folder("parent-123", "MP4")
|
||||
|
||||
assert mock_list_result.execute.call_count == 1
|
||||
|
||||
|
||||
class TestDeleteFile:
|
||||
"""Test delete_file and delete_files methods."""
|
||||
|
||||
def _make_service(self, mock_get_settings):
|
||||
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
mock_settings = Mock()
|
||||
mock_get_settings.return_value = mock_settings
|
||||
service = GoogleDriveService()
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
return service
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_file_success(self, mock_get_settings):
|
||||
"""Successful delete returns True."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_delete = Mock()
|
||||
mock_delete.execute.return_value = None
|
||||
mock_files_api.delete.return_value = mock_delete
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.delete_file("file-id-123")
|
||||
|
||||
assert result is True
|
||||
mock_files_api.delete.assert_called_once_with(fileId="file-id-123")
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_file_returns_true_on_404(self, mock_get_settings):
|
||||
"""404 (already deleted) returns True — idempotent cleanup."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_delete = Mock()
|
||||
not_found = Exception("File not found")
|
||||
not_found.resp = Mock()
|
||||
not_found.resp.status = 404
|
||||
mock_delete.execute.side_effect = not_found
|
||||
mock_files_api.delete.return_value = mock_delete
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.delete_file("already-gone-id")
|
||||
|
||||
assert result is True
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_file_returns_false_on_error(self, mock_get_settings):
|
||||
"""Non-404 errors return False."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_delete = Mock()
|
||||
mock_delete.execute.side_effect = Exception("Permission denied")
|
||||
mock_files_api.delete.return_value = mock_delete
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.delete_file("restricted-file")
|
||||
|
||||
assert result is False
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_files_calls_delete_file_for_each_id(self, mock_get_settings):
|
||||
"""delete_files returns a per-ID success dict."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
# Stub delete_file: first ID succeeds, second fails
|
||||
results_by_id = {"id-1": True, "id-2": False}
|
||||
service.delete_file = lambda fid: results_by_id[fid]
|
||||
|
||||
result = service.delete_files(["id-1", "id-2"])
|
||||
|
||||
assert result == {"id-1": True, "id-2": False}
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_files_empty_list(self, mock_get_settings):
|
||||
"""delete_files with empty list returns empty dict."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
result = service.delete_files([])
|
||||
assert result == {}
|
||||
|
||||
|
||||
class TestFindFilesByBrandCode:
|
||||
"""Test find_files_by_brand_code method — used as fallback in cleanup-distribution."""
|
||||
|
||||
def _make_service(self, mock_get_settings):
|
||||
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
service = GoogleDriveService()
|
||||
service._loaded = True
|
||||
service._credentials_data = {
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
}
|
||||
return service
|
||||
|
||||
def _attach_mock_drive(self, service, list_side_effects):
|
||||
"""Attach a mock Drive client whose files().list().execute() returns given values."""
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = list_side_effects
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
return mock_files_api
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_finds_files_in_all_subfolders(self, mock_get_settings):
|
||||
"""Test finds matching files across CDG/, MP4/, MP4-720p/ subfolders."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# Responses: for each subfolder: (1) find subfolder, (2) search for files
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]}, # CDG subfolder found
|
||||
{"files": [{"id": "cdg-file-1", "name": "NOMAD-1271 - piri - dog.zip"}]},
|
||||
{"files": [{"id": "mp4-folder"}]}, # MP4 subfolder found
|
||||
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
|
||||
{"files": [{"id": "mp4720-folder"}]}, # MP4-720p subfolder found
|
||||
{"files": [{"id": "mp4720-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert len(result) == 3
|
||||
assert "cdg-file-1" in result
|
||||
assert "mp4-file-1" in result
|
||||
assert "mp4720-file-1" in result
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_returns_empty_when_subfolder_not_found(self, mock_get_settings):
|
||||
"""Test returns empty list when public share subfolders don't exist."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# All subfolder lookups return empty
|
||||
mock_list_result.execute.return_value = {"files": []}
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == []
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_filters_by_exact_brand_code_prefix(self, mock_get_settings):
|
||||
"""Test only returns files whose name starts with '{brand_code} - '."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]},
|
||||
{
|
||||
"files": [
|
||||
{"id": "match-id", "name": "NOMAD-1271 - piri - dog.zip"},
|
||||
# This one contains NOMAD-1271 but doesn't START with it — should be excluded
|
||||
{"id": "no-match-id", "name": "BONUS-NOMAD-1271 - other.zip"},
|
||||
]
|
||||
},
|
||||
{"files": []}, # MP4 subfolder not found
|
||||
{"files": []}, # MP4-720p subfolder not found
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == ["match-id"]
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_returns_empty_when_no_files_match_brand_code(self, mock_get_settings):
|
||||
"""Test returns empty list when subfolder exists but has no matching files."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]},
|
||||
{"files": [{"id": "other-id", "name": "NOMAD-1300 - someone else.zip"}]},
|
||||
{"files": []}, # MP4 not found
|
||||
{"files": []}, # MP4-720p not found
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == []
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_raises_after_all_subfolders_when_any_error(self, mock_get_settings):
|
||||
"""When any subfolder search errors, raises RuntimeError after processing all subfolders.
|
||||
|
||||
This prevents the cleanup endpoint from treating an incomplete search result
|
||||
as "GDrive is clean" and incorrectly recycling the brand code.
|
||||
"""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]},
|
||||
Exception("API error"), # CDG file search fails
|
||||
{"files": [{"id": "mp4-folder"}]},
|
||||
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
|
||||
{"files": [{"id": "mp4720-folder"}]},
|
||||
{"files": []},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
# Should raise after processing all subfolders — an incomplete search must not
|
||||
# be silently treated as "nothing found" by the caller
|
||||
with pytest.raises(RuntimeError, match="search incomplete"):
|
||||
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
|
||||
class TestGetGdriveService:
|
||||
"""Test get_gdrive_service singleton."""
|
||||
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_get_gdrive_service_singleton(self, mock_get_settings):
|
||||
"""Test get_gdrive_service returns singleton instance."""
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
import backend.services.gdrive_service as gdrive_module
|
||||
|
||||
|
||||
# Reset singleton
|
||||
gdrive_module._gdrive_service = None
|
||||
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = None
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
|
||||
service1 = get_gdrive_service()
|
||||
service2 = get_gdrive_service()
|
||||
|
||||
|
||||
assert service1 is service2
|
||||
|
||||
@@ -1,307 +0,0 @@
|
||||
"""
|
||||
Tests for delayed GDrive validation trigger.
|
||||
|
||||
The post-job GDrive validation was firing immediately after upload, before E2E
|
||||
test cleanup could run. This caused false "all clear" reports when the validator
|
||||
checked sequence gaps while test files still existed in GDrive.
|
||||
|
||||
Fix: Use Cloud Tasks to delay the validation by 5 minutes.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, AsyncMock, patch
|
||||
|
||||
|
||||
class TestGdriveValidationEndpoint:
|
||||
"""Tests for POST /api/internal/trigger-gdrive-validation."""
|
||||
|
||||
@pytest.fixture
|
||||
def client_and_mocks(self):
|
||||
"""Create TestClient with mocked dependencies."""
|
||||
import os
|
||||
os.environ.setdefault('ADMIN_TOKENS', 'test-admin-token')
|
||||
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
|
||||
with patch('backend.api.routes.internal.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
yield TestClient(app)
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers(self):
|
||||
return {"Authorization": "Bearer test-admin-token"}
|
||||
|
||||
def test_endpoint_returns_200(self, client_and_mocks, auth_headers):
|
||||
"""Test gdrive validation endpoint returns 200 with auth."""
|
||||
with patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
return_value={"status": "ok", "total_files": 1276}
|
||||
):
|
||||
response = client_and_mocks.post(
|
||||
"/api/internal/trigger-gdrive-validation",
|
||||
headers=auth_headers,
|
||||
json={},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "ok"
|
||||
|
||||
def test_endpoint_returns_skipped_when_url_not_set(self, client_and_mocks, auth_headers):
|
||||
"""Test endpoint returns skipped when GDRIVE_VALIDATOR_URL is not configured."""
|
||||
with patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
return_value=None
|
||||
):
|
||||
response = client_and_mocks.post(
|
||||
"/api/internal/trigger-gdrive-validation",
|
||||
headers=auth_headers,
|
||||
json={},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "skipped"
|
||||
|
||||
def test_endpoint_handles_issues_found(self, client_and_mocks, auth_headers):
|
||||
"""Test endpoint properly relays issues_found status."""
|
||||
with patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
return_value={"status": "issues_found", "issues": ["NOMAD-1276 missing"]}
|
||||
):
|
||||
response = client_and_mocks.post(
|
||||
"/api/internal/trigger-gdrive-validation",
|
||||
headers=auth_headers,
|
||||
json={},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "issues_found"
|
||||
|
||||
def test_endpoint_handles_exception(self, client_and_mocks, auth_headers):
|
||||
"""Test endpoint returns error status on exception."""
|
||||
with patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
side_effect=Exception("Connection refused")
|
||||
):
|
||||
response = client_and_mocks.post(
|
||||
"/api/internal/trigger-gdrive-validation",
|
||||
headers=auth_headers,
|
||||
json={},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "error"
|
||||
assert "Connection refused" in data["message"]
|
||||
|
||||
|
||||
class TestScheduleGdriveValidation:
|
||||
"""Tests for WorkerService.schedule_gdrive_validation()."""
|
||||
|
||||
def test_skips_when_cloud_tasks_disabled(self):
|
||||
"""Test validation scheduling is skipped in dev mode (no Cloud Tasks)."""
|
||||
import asyncio
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.enable_cloud_tasks = False
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
|
||||
from backend.services.worker_service import WorkerService
|
||||
service = WorkerService()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
result = loop.run_until_complete(service.schedule_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Should return True (success) even though it didn't schedule
|
||||
assert result is True
|
||||
|
||||
def test_schedules_with_correct_url(self):
|
||||
"""Test that validation is scheduled targeting the right endpoint."""
|
||||
import asyncio
|
||||
|
||||
mock_tasks_client = MagicMock()
|
||||
mock_response = MagicMock()
|
||||
mock_response.name = "projects/test/queues/gdrive-validation-queue/tasks/abc123"
|
||||
mock_tasks_client.create_task.return_value = mock_response
|
||||
mock_tasks_client.queue_path.return_value = "projects/test/locations/us-central1/queues/gdrive-validation-queue"
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.cloud_run_url = "https://api.nomadkaraoke.com"
|
||||
|
||||
from backend.services.worker_service import WorkerService
|
||||
service = WorkerService()
|
||||
# Override the lazy property by setting the private attribute
|
||||
service._tasks_client = mock_tasks_client
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
result = loop.run_until_complete(service.schedule_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
assert result is True
|
||||
mock_tasks_client.create_task.assert_called_once()
|
||||
|
||||
# Verify the task targets the right endpoint
|
||||
create_call = mock_tasks_client.create_task.call_args
|
||||
task_payload = create_call.kwargs.get('task', {})
|
||||
url = task_payload.get('http_request', {}).get('url', '')
|
||||
assert 'trigger-gdrive-validation' in url
|
||||
|
||||
def test_returns_false_on_error(self):
|
||||
"""Test that scheduling failure returns False (non-fatal)."""
|
||||
import asyncio
|
||||
|
||||
mock_tasks_client = MagicMock()
|
||||
mock_tasks_client.create_task.side_effect = Exception("Queue not found")
|
||||
mock_tasks_client.queue_path.return_value = "projects/test/queues/gdrive-validation-queue"
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.cloud_run_url = "https://api.nomadkaraoke.com"
|
||||
|
||||
from backend.services.worker_service import WorkerService
|
||||
service = WorkerService()
|
||||
service._tasks_client = mock_tasks_client
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
result = loop.run_until_complete(service.schedule_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestOrchestratorUsesDelayedValidation:
|
||||
"""Test that the orchestrator uses delayed validation instead of immediate."""
|
||||
|
||||
def test_orchestrator_schedules_delayed_validation(self):
|
||||
"""Test _trigger_gdrive_validation uses schedule_gdrive_validation."""
|
||||
import asyncio
|
||||
|
||||
mock_worker_service = MagicMock()
|
||||
mock_worker_service.schedule_gdrive_validation = AsyncMock(return_value=True)
|
||||
|
||||
with patch(
|
||||
'backend.services.worker_service.get_worker_service',
|
||||
return_value=mock_worker_service
|
||||
):
|
||||
from backend.workers.video_worker_orchestrator import VideoWorkerOrchestrator
|
||||
|
||||
# Create a minimal orchestrator instance
|
||||
mock_config = MagicMock()
|
||||
mock_job_log = MagicMock()
|
||||
orchestrator = VideoWorkerOrchestrator.__new__(VideoWorkerOrchestrator)
|
||||
orchestrator.config = mock_config
|
||||
orchestrator.job_log = mock_job_log
|
||||
orchestrator.result = MagicMock()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(orchestrator._trigger_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_worker_service.schedule_gdrive_validation.assert_called_once()
|
||||
mock_job_log.info.assert_called_once()
|
||||
assert "5 min" in mock_job_log.info.call_args[0][0]
|
||||
|
||||
def test_orchestrator_falls_back_to_immediate_on_failure(self):
|
||||
"""Test _trigger_gdrive_validation falls back to immediate call if scheduling fails."""
|
||||
import asyncio
|
||||
|
||||
mock_worker_service = MagicMock()
|
||||
mock_worker_service.schedule_gdrive_validation = AsyncMock(return_value=False)
|
||||
|
||||
mock_validator = MagicMock(return_value={"status": "ok"})
|
||||
|
||||
with patch(
|
||||
'backend.services.worker_service.get_worker_service',
|
||||
return_value=mock_worker_service
|
||||
), patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
mock_validator
|
||||
):
|
||||
from backend.workers.video_worker_orchestrator import VideoWorkerOrchestrator
|
||||
|
||||
mock_config = MagicMock()
|
||||
mock_job_log = MagicMock()
|
||||
orchestrator = VideoWorkerOrchestrator.__new__(VideoWorkerOrchestrator)
|
||||
orchestrator.config = mock_config
|
||||
orchestrator.job_log = mock_job_log
|
||||
orchestrator.result = MagicMock()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(orchestrator._trigger_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Should have called the fallback immediate trigger
|
||||
mock_validator.assert_called_once()
|
||||
# Should have logged a warning about the fallback
|
||||
mock_job_log.warning.assert_called_once()
|
||||
|
||||
def test_orchestrator_handles_exception_gracefully(self):
|
||||
"""Test _trigger_gdrive_validation never crashes the pipeline."""
|
||||
import asyncio
|
||||
|
||||
with patch(
|
||||
'backend.services.worker_service.get_worker_service',
|
||||
side_effect=Exception("Service unavailable")
|
||||
):
|
||||
from backend.workers.video_worker_orchestrator import VideoWorkerOrchestrator
|
||||
|
||||
mock_config = MagicMock()
|
||||
mock_job_log = MagicMock()
|
||||
orchestrator = VideoWorkerOrchestrator.__new__(VideoWorkerOrchestrator)
|
||||
orchestrator.config = mock_config
|
||||
orchestrator.job_log = mock_job_log
|
||||
orchestrator.result = MagicMock()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
# Should not raise - non-fatal
|
||||
loop.run_until_complete(orchestrator._trigger_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_log.warning.assert_called_once()
|
||||
|
||||
|
||||
class TestGdriveValidationConstants:
|
||||
"""Test that the delay constant is correctly set."""
|
||||
|
||||
def test_delay_is_five_minutes(self):
|
||||
"""Verify GDRIVE_VALIDATION_DELAY_SECONDS is 300 (5 minutes)."""
|
||||
from backend.services.worker_service import GDRIVE_VALIDATION_DELAY_SECONDS
|
||||
assert GDRIVE_VALIDATION_DELAY_SECONDS == 300
|
||||
|
||||
def test_queue_is_configured(self):
|
||||
"""Verify gdrive-validation queue is in WORKER_QUEUES."""
|
||||
from backend.services.worker_service import WORKER_QUEUES
|
||||
assert "gdrive-validation" in WORKER_QUEUES
|
||||
assert WORKER_QUEUES["gdrive-validation"] == "gdrive-validation-queue"
|
||||
|
||||
def test_dispatch_deadline_is_configured(self):
|
||||
"""Verify gdrive-validation dispatch deadline is set."""
|
||||
from backend.services.worker_service import WORKER_DISPATCH_DEADLINES
|
||||
assert "gdrive-validation" in WORKER_DISPATCH_DEADLINES
|
||||
assert WORKER_DISPATCH_DEADLINES["gdrive-validation"] == 120
|
||||
@@ -196,7 +196,7 @@ class TestUserEmailExtraction:
|
||||
mock_jm.create_job.return_value = mock_job
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_cred.return_value.check_youtube_credentials.return_value = Mock(status=Mock(value="valid"))
|
||||
mock_search.return_value.search_async = AsyncMock(return_value=[])
|
||||
mock_search.return_value.search.return_value = []
|
||||
|
||||
await search_audio(
|
||||
request=mock_request,
|
||||
|
||||
@@ -214,91 +214,6 @@ class TestDeleteJob:
|
||||
assert response.status_code in [200, 404]
|
||||
|
||||
|
||||
class TestDeleteJobBrandCodeRecycling:
|
||||
"""Tests for brand code recycling in DELETE /api/jobs/{job_id}."""
|
||||
|
||||
def test_brand_code_recycled_before_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Test that brand code is recycled before the job is deleted."""
|
||||
mock_job_manager = MagicMock()
|
||||
job_with_brand = Job(
|
||||
job_id="test-bc-123",
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={"brand_code": "NOMAD-0042"},
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job_with_brand
|
||||
mock_job_manager.delete_job.return_value = True
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', return_value=("NOMAD", 42)) as mock_parse, \
|
||||
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
|
||||
mock_svc = MagicMock()
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-123", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_parse.assert_called_once_with("NOMAD-0042")
|
||||
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
|
||||
def test_recycling_failure_does_not_prevent_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Test that job deletion proceeds even if brand code recycling fails."""
|
||||
mock_job_manager = MagicMock()
|
||||
job_with_brand = Job(
|
||||
job_id="test-bc-456",
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={"brand_code": "NOMAD-0099"},
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job_with_brand
|
||||
mock_job_manager.delete_job.return_value = True
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', side_effect=ValueError("Bad format")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-456", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Job should still be deleted despite recycling failure
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
|
||||
def test_no_brand_code_skips_recycling(self, client, mock_job_manager, auth_headers):
|
||||
"""Test that deletion without brand code doesn't attempt recycling."""
|
||||
with patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
|
||||
response = client.delete("/api/jobs/test123", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_get_svc.assert_not_called()
|
||||
|
||||
|
||||
class TestCancelJob:
|
||||
"""Tests for POST /api/jobs/{job_id}/cancel."""
|
||||
|
||||
@@ -359,129 +274,10 @@ class TestSelectInstrumental:
|
||||
|
||||
class TestStartReview:
|
||||
"""Tests for POST /api/jobs/{job_id}/start-review."""
|
||||
|
||||
|
||||
def test_start_review_endpoint_exists(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test start review endpoint exists."""
|
||||
response = client.post("/api/jobs/test123/start-review", headers=auth_headers)
|
||||
# Should not be 404 or 405
|
||||
assert response.status_code not in [404, 405]
|
||||
|
||||
|
||||
class TestSubmitEditLog:
|
||||
"""Tests for POST /api/jobs/{job_id}/edit-log."""
|
||||
|
||||
def test_submit_edit_log_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test submitting a valid edit log returns 200."""
|
||||
edit_log = {
|
||||
"session_id": "sess-abc",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "hash123",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": [
|
||||
{
|
||||
"id": "e1",
|
||||
"timestamp": "2026-03-01T00:01:00.000Z",
|
||||
"operation": "word_change",
|
||||
"segment_id": "s1",
|
||||
"segment_index": 0,
|
||||
"word_ids_before": ["w1"],
|
||||
"word_ids_after": ["w1"],
|
||||
"text_before": "helo",
|
||||
"text_after": "hello",
|
||||
"feedback": {"reason": "misheard_word", "timestamp": "2026-03-01T00:01:05.000Z"}
|
||||
}
|
||||
]
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
response = client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["entries_count"] == 1
|
||||
assert data["feedback_count"] == 1
|
||||
|
||||
def test_submit_edit_log_stores_to_gcs(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test edit log is stored to GCS with correct path."""
|
||||
edit_log = {
|
||||
"session_id": "sess-xyz",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "hash123",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": []
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
mock_storage.upload_json.assert_called_once_with(
|
||||
"jobs/test123/lyrics/edit_log_sess-xyz.json",
|
||||
edit_log
|
||||
)
|
||||
|
||||
def test_submit_edit_log_updates_firestore(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test edit log updates Firestore state_data."""
|
||||
edit_log = {
|
||||
"session_id": "sess-123",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "h",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": []
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
mock_job_manager.update_state_data.assert_any_call(
|
||||
"test123", "last_edit_log_path", "jobs/test123/lyrics/edit_log_sess-123.json"
|
||||
)
|
||||
mock_job_manager.update_state_data.assert_any_call(
|
||||
"test123", "last_edit_log_session", "sess-123"
|
||||
)
|
||||
|
||||
def test_submit_edit_log_nonexistent_job_returns_404(self, mock_worker_service, auth_headers):
|
||||
"""Test submitting to nonexistent job returns 404."""
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_jm
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_jm), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.services.job_manager.JobManager', mock_jm_factory), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
from backend.main import app
|
||||
test_client = TestClient(app)
|
||||
response = test_client.post(
|
||||
"/api/jobs/nonexistent/edit-log",
|
||||
json={"session_id": "s", "entries": []},
|
||||
headers=auth_headers
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_submit_edit_log_counts_feedback_correctly(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test feedback count excludes no_response entries."""
|
||||
edit_log = {
|
||||
"session_id": "sess-1",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "h",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": [
|
||||
{"id": "e1", "feedback": {"reason": "misheard_word"}},
|
||||
{"id": "e2", "feedback": {"reason": "no_response"}},
|
||||
{"id": "e3", "feedback": None},
|
||||
{"id": "e4", "feedback": {"reason": "wrong_lyrics"}},
|
||||
]
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
response = client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
data = response.json()
|
||||
assert data["entries_count"] == 4
|
||||
assert data["feedback_count"] == 2 # misheard_word + wrong_lyrics
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
"""
|
||||
Unit tests for the annotations endpoint in review.py.
|
||||
|
||||
Tests the actual storage logic (not the stub version).
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage():
|
||||
"""Create a mock StorageService that tracks calls."""
|
||||
storage = MagicMock()
|
||||
storage.upload_json = MagicMock()
|
||||
# Default: no existing annotations
|
||||
storage.download_json = MagicMock(side_effect=Exception("Not found"))
|
||||
return storage
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_storage):
|
||||
"""Create TestClient with mocked dependencies for review routes."""
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = MagicMock(
|
||||
job_id="test-job",
|
||||
status="in_review",
|
||||
review_token="test-review-token"
|
||||
)
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_jm
|
||||
|
||||
# Override review auth to bypass complex auth chain
|
||||
async def fake_review_auth():
|
||||
return ("test-job", "full")
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_jm), \
|
||||
patch('backend.services.job_manager.JobManager', mock_jm_factory), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
|
||||
# Override review auth dependency (must use the same function object used by routes)
|
||||
app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
|
||||
# Patch StorageService inside the review module
|
||||
with patch('backend.api.routes.review.StorageService', return_value=mock_storage):
|
||||
yield TestClient(app)
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestSubmitAnnotations:
|
||||
"""Tests for POST /api/review/{job_id}/v1/annotations."""
|
||||
|
||||
def test_submit_single_annotation(self, client, mock_storage):
|
||||
"""Test submitting a single annotation stores to GCS."""
|
||||
annotation = {"annotation_type": "SOUND_ALIKE", "original_text": "helo", "corrected_text": "hello"}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=annotation)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["saved_count"] == 1
|
||||
|
||||
def test_submit_batch_annotations(self, client, mock_storage):
|
||||
"""Test submitting a batch of annotations."""
|
||||
payload = {
|
||||
"annotations": [
|
||||
{"annotation_type": "SOUND_ALIKE", "original_text": "a"},
|
||||
{"annotation_type": "EXTRA_WORDS", "original_text": "b"},
|
||||
]
|
||||
}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=payload)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["saved_count"] == 2
|
||||
assert data["total_count"] == 2
|
||||
|
||||
def test_annotations_stored_to_correct_gcs_path(self, client, mock_storage):
|
||||
"""Test annotations are stored at jobs/{job_id}/lyrics/annotations.json."""
|
||||
client.post(
|
||||
"/api/review/test-job/v1/annotations",
|
||||
json={"annotation_type": "MANUAL_EDIT"}
|
||||
)
|
||||
mock_storage.upload_json.assert_called_once()
|
||||
gcs_path = mock_storage.upload_json.call_args[0][0]
|
||||
assert gcs_path == "jobs/test-job/lyrics/annotations.json"
|
||||
|
||||
def test_annotations_merged_with_existing(self, client, mock_storage):
|
||||
"""Test new annotations are merged with existing ones."""
|
||||
# Set up existing annotations
|
||||
mock_storage.download_json.side_effect = None
|
||||
mock_storage.download_json.return_value = {
|
||||
"annotations": [{"annotation_type": "SOUND_ALIKE", "original_text": "existing"}]
|
||||
}
|
||||
|
||||
payload = {"annotations": [{"annotation_type": "EXTRA_WORDS", "original_text": "new"}]}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=payload)
|
||||
|
||||
data = response.json()
|
||||
assert data["saved_count"] == 1
|
||||
assert data["total_count"] == 2 # 1 existing + 1 new
|
||||
|
||||
# Verify merged data was uploaded
|
||||
uploaded_data = mock_storage.upload_json.call_args[0][1]
|
||||
assert len(uploaded_data["annotations"]) == 2
|
||||
|
||||
def test_annotations_fresh_when_no_existing(self, client, mock_storage):
|
||||
"""Test annotations start fresh when no existing file."""
|
||||
payload = {"annotations": [{"annotation_type": "NO_ERROR"}]}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=payload)
|
||||
assert response.json()["total_count"] == 1
|
||||
@@ -490,14 +490,13 @@ class TestSummaryEndpoint:
|
||||
assert list(result['file_urls'].keys()) == ['finals']
|
||||
|
||||
def test_hide_completed_statuses(self):
|
||||
"""Verify _HIDE_COMPLETED_STATUSES only hides successful completions (not failed/cancelled)."""
|
||||
"""Verify _HIDE_COMPLETED_STATUSES includes the expected terminal statuses."""
|
||||
from backend.api.routes.jobs import _HIDE_COMPLETED_STATUSES
|
||||
|
||||
assert 'complete' in _HIDE_COMPLETED_STATUSES
|
||||
assert 'prep_complete' in _HIDE_COMPLETED_STATUSES
|
||||
# Failed/cancelled should NOT be hidden - users need to see these
|
||||
assert 'failed' not in _HIDE_COMPLETED_STATUSES
|
||||
assert 'cancelled' not in _HIDE_COMPLETED_STATUSES
|
||||
assert 'failed' in _HIDE_COMPLETED_STATUSES
|
||||
assert 'cancelled' in _HIDE_COMPLETED_STATUSES
|
||||
# Active statuses should NOT be in the list
|
||||
assert 'pending' not in _HIDE_COMPLETED_STATUSES
|
||||
assert 'downloading' not in _HIDE_COMPLETED_STATUSES
|
||||
|
||||
@@ -1,230 +0,0 @@
|
||||
"""
|
||||
Tests for audio select endpoint overrides (guided flow Step 3).
|
||||
|
||||
When the guided flow reaches Step 3 (Customize), the user can change:
|
||||
- is_private: Whether the job should use private distribution
|
||||
- display_artist: Override the display artist name
|
||||
- display_title: Override the display title
|
||||
|
||||
These overrides are sent with the select request and applied to the job
|
||||
BEFORE the pipeline starts, since the job was created in Step 2 before
|
||||
these fields were available.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, AsyncMock
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
|
||||
class TestAudioSelectRequestOverrides:
|
||||
"""Tests for AudioSelectRequest model with optional overrides."""
|
||||
|
||||
def test_model_accepts_overrides(self):
|
||||
"""Test AudioSelectRequest accepts is_private, display_artist, display_title."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
req = AudioSelectRequest(
|
||||
selection_index=0,
|
||||
is_private=True,
|
||||
display_artist="Custom Artist",
|
||||
display_title="Custom Title",
|
||||
)
|
||||
assert req.selection_index == 0
|
||||
assert req.is_private is True
|
||||
assert req.display_artist == "Custom Artist"
|
||||
assert req.display_title == "Custom Title"
|
||||
|
||||
def test_model_defaults_overrides_to_none(self):
|
||||
"""Test AudioSelectRequest defaults override fields to None."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
req = AudioSelectRequest(selection_index=0)
|
||||
assert req.is_private is None
|
||||
assert req.display_artist is None
|
||||
assert req.display_title is None
|
||||
|
||||
def test_model_accepts_is_private_false(self):
|
||||
"""Test AudioSelectRequest distinguishes is_private=False from None."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
req = AudioSelectRequest(selection_index=0, is_private=False)
|
||||
assert req.is_private is False
|
||||
|
||||
|
||||
class TestSelectEndpointAppliesOverrides:
|
||||
"""Tests that the select_audio_source endpoint applies overrides to the job."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(self):
|
||||
"""Mock the job manager singleton."""
|
||||
with patch('backend.api.routes.audio_search.job_manager') as mock:
|
||||
yield mock
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage_service(self):
|
||||
"""Mock the storage service singleton."""
|
||||
with patch('backend.api.routes.audio_search.storage_service') as mock:
|
||||
yield mock
|
||||
|
||||
def test_overrides_applied_before_selection(self, mock_job_manager, mock_storage_service):
|
||||
"""Test is_private and display overrides are applied to job before pipeline starts."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
# Setup mock job in AWAITING_AUDIO_SELECTION state
|
||||
mock_job = Mock()
|
||||
mock_job.status = JobStatus.AWAITING_AUDIO_SELECTION
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test Song',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'abc123',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
body = AudioSelectRequest(
|
||||
selection_index=0,
|
||||
is_private=True,
|
||||
display_artist="DJ Test",
|
||||
display_title="The Remix",
|
||||
)
|
||||
|
||||
# We test the override logic directly by checking update_job calls
|
||||
# The first update_job call should be the overrides (before _validate_and_prepare_selection)
|
||||
import asyncio
|
||||
from unittest.mock import call
|
||||
from fastapi import BackgroundTasks
|
||||
|
||||
# Mock BackgroundTasks and auth
|
||||
bg_tasks = Mock(spec=BackgroundTasks)
|
||||
auth_result = Mock()
|
||||
|
||||
# Mock the audio search service
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'):
|
||||
from backend.api.routes.audio_search import select_audio_source
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
select_audio_source(
|
||||
job_id="test-job",
|
||||
background_tasks=bg_tasks,
|
||||
body=body,
|
||||
auth_result=auth_result,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# The overrides should be applied via update_job
|
||||
update_calls = mock_job_manager.update_job.call_args_list
|
||||
# First call should be the overrides
|
||||
override_call = update_calls[0]
|
||||
assert override_call.args[0] == "test-job"
|
||||
override_data = override_call.args[1]
|
||||
assert override_data["is_private"] is True
|
||||
assert override_data["display_artist"] == "DJ Test"
|
||||
assert override_data["display_title"] == "The Remix"
|
||||
|
||||
def test_no_overrides_skips_update(self, mock_job_manager, mock_storage_service):
|
||||
"""Test that when no overrides are provided, update_job is NOT called for overrides."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.status = JobStatus.AWAITING_AUDIO_SELECTION
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test Song',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'abc123',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
body = AudioSelectRequest(selection_index=0)
|
||||
|
||||
import asyncio
|
||||
from fastapi import BackgroundTasks
|
||||
|
||||
bg_tasks = Mock(spec=BackgroundTasks)
|
||||
auth_result = Mock()
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'):
|
||||
from backend.api.routes.audio_search import select_audio_source
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
select_audio_source(
|
||||
job_id="test-job",
|
||||
background_tasks=bg_tasks,
|
||||
body=body,
|
||||
auth_result=auth_result,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# update_job will be called by _validate_and_prepare_selection for download params
|
||||
# but NOT for overrides. The override call would have is_private/display_artist/display_title
|
||||
for call_args in mock_job_manager.update_job.call_args_list:
|
||||
update_data = call_args.args[1]
|
||||
assert "is_private" not in update_data
|
||||
assert "display_artist" not in update_data
|
||||
assert "display_title" not in update_data
|
||||
|
||||
def test_partial_overrides_only_applies_provided(self, mock_job_manager, mock_storage_service):
|
||||
"""Test that only provided override fields are sent to update_job."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.status = JobStatus.AWAITING_AUDIO_SELECTION
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test Song',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'abc123',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
# Only is_private, no display overrides
|
||||
body = AudioSelectRequest(selection_index=0, is_private=True)
|
||||
|
||||
import asyncio
|
||||
from fastapi import BackgroundTasks
|
||||
|
||||
bg_tasks = Mock(spec=BackgroundTasks)
|
||||
auth_result = Mock()
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'):
|
||||
from backend.api.routes.audio_search import select_audio_source
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
select_audio_source(
|
||||
job_id="test-job",
|
||||
background_tasks=bg_tasks,
|
||||
body=body,
|
||||
auth_result=auth_result,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Find the override call (first update_job call)
|
||||
override_call = mock_job_manager.update_job.call_args_list[0]
|
||||
override_data = override_call.args[1]
|
||||
assert override_data == {"is_private": True}
|
||||
assert "display_artist" not in override_data
|
||||
assert "display_title" not in override_data
|
||||
@@ -1,959 +0,0 @@
|
||||
"""
|
||||
Unit tests for the standalone search + create-from-search guided flow.
|
||||
|
||||
Covers:
|
||||
- FirestoreService search session CRUD (including consume_search_session)
|
||||
- POST /api/audio-search/search-standalone (no job created)
|
||||
- POST /api/jobs/create-from-search (session validation, ownership, tenant, job creation)
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, timedelta, UTC
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_mock_creds():
|
||||
creds = MagicMock()
|
||||
creds.universe_domain = "googleapis.com"
|
||||
return creds
|
||||
|
||||
|
||||
def _make_mock_job_manager(job=None):
|
||||
mgr = MagicMock()
|
||||
if job is None:
|
||||
job = Job(
|
||||
job_id="test-job-123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
)
|
||||
mgr.create_job.return_value = job
|
||||
mgr.get_job.return_value = job
|
||||
mgr.update_job.return_value = None
|
||||
mgr.update_state_data.return_value = None
|
||||
return mgr
|
||||
|
||||
|
||||
def _make_search_session(user_email="test@example.com", expired=False, tenant_id=None):
|
||||
now = datetime.utcnow()
|
||||
ttl = now - timedelta(hours=1) if expired else now + timedelta(minutes=30)
|
||||
return {
|
||||
"session_id": "sess-abc-123",
|
||||
"user_email": user_email,
|
||||
"tenant_id": tenant_id,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"results": [
|
||||
{
|
||||
"index": 0,
|
||||
"title": "Waterloo",
|
||||
"artist": "ABBA",
|
||||
"provider": "YouTube",
|
||||
"url": "https://youtube.com/watch?v=abc",
|
||||
}
|
||||
],
|
||||
"remote_search_id": None,
|
||||
"created_at": now.isoformat(),
|
||||
"ttl_expiry": ttl,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# State machine — PENDING → DOWNLOADING_AUDIO transition
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestStateTransitionPendingToDownloadingAudio:
|
||||
"""Verify PENDING → DOWNLOADING_AUDIO is a valid state transition (create-from-search path)."""
|
||||
|
||||
def test_pending_allows_downloading_audio_transition(self):
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
assert JobStatus.DOWNLOADING_AUDIO in STATE_TRANSITIONS[JobStatus.PENDING]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# FirestoreService session CRUD
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestFirestoreServiceSearchSessionCRUD:
|
||||
"""Unit tests for search session CRUD methods on FirestoreService."""
|
||||
|
||||
def test_create_search_session_stores_document(self):
|
||||
"""create_search_session should write to Firestore and return session_id."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
session_data = {
|
||||
"session_id": "sess-xyz",
|
||||
"user_email": "user@example.com",
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"results": [],
|
||||
}
|
||||
returned_id = svc.create_search_session(session_data)
|
||||
|
||||
mock_db.collection.assert_called_once_with("search_sessions")
|
||||
mock_collection.document.assert_called_once_with("sess-xyz")
|
||||
mock_doc.set.assert_called_once_with(session_data)
|
||||
assert returned_id == "sess-xyz"
|
||||
|
||||
def test_get_search_session_returns_dict_when_exists(self):
|
||||
"""get_search_session should return doc dict when document exists."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
session_dict = {"session_id": "sess-xyz", "user_email": "user@example.com"}
|
||||
mock_snapshot = MagicMock()
|
||||
mock_snapshot.exists = True
|
||||
mock_snapshot.to_dict.return_value = session_dict
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.get.return_value = mock_snapshot
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
result = svc.get_search_session("sess-xyz")
|
||||
|
||||
assert result == session_dict
|
||||
|
||||
def test_get_search_session_returns_none_when_missing(self):
|
||||
"""get_search_session should return None when document doesn't exist."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_snapshot = MagicMock()
|
||||
mock_snapshot.exists = False
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.get.return_value = mock_snapshot
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
result = svc.get_search_session("nonexistent-session")
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_get_search_session_raises_on_firestore_error(self):
|
||||
"""get_search_session should raise (not return None) on Firestore errors."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.side_effect = Exception("Firestore unavailable")
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
with pytest.raises(Exception, match="Firestore unavailable"):
|
||||
svc.get_search_session("sess-xyz")
|
||||
|
||||
def test_consume_search_session_returns_session_and_deletes_atomically(self):
|
||||
"""consume_search_session should return session data and delete within transaction."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from google.cloud import firestore as fs
|
||||
|
||||
session_dict = {"session_id": "sess-xyz", "user_email": "user@example.com"}
|
||||
|
||||
mock_snapshot = MagicMock()
|
||||
mock_snapshot.exists = True
|
||||
mock_snapshot.to_dict.return_value = session_dict
|
||||
|
||||
mock_doc_ref = MagicMock()
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc_ref
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
# Simulate Firestore transaction: the @transactional function gets called
|
||||
# with a transaction object; we simulate by calling the inner function directly.
|
||||
captured_fn = {}
|
||||
|
||||
def fake_transactional(fn):
|
||||
captured_fn['fn'] = fn
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return fn(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
mock_transaction = MagicMock()
|
||||
mock_doc_ref.get.return_value = mock_snapshot
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
with patch.object(fs, 'transactional', fake_transactional):
|
||||
result = svc.consume_search_session("sess-xyz")
|
||||
|
||||
assert result == session_dict
|
||||
|
||||
def test_consume_search_session_returns_none_when_missing(self):
|
||||
"""consume_search_session returns None when document doesn't exist."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from google.cloud import firestore as fs
|
||||
|
||||
mock_snapshot = MagicMock()
|
||||
mock_snapshot.exists = False
|
||||
|
||||
mock_doc_ref = MagicMock()
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc_ref
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
def fake_transactional(fn):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return fn(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
mock_transaction = MagicMock()
|
||||
mock_doc_ref.get.return_value = mock_snapshot
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
with patch.object(fs, 'transactional', fake_transactional):
|
||||
result = svc.consume_search_session("nonexistent-session")
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_delete_search_session_calls_firestore_delete(self):
|
||||
"""delete_search_session should call Firestore delete."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
svc.delete_search_session("sess-xyz")
|
||||
|
||||
mock_doc.delete.assert_called_once()
|
||||
|
||||
def test_delete_search_session_silently_ignores_errors(self):
|
||||
"""delete_search_session should not raise on Firestore errors."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.side_effect = Exception("Connection error")
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
# Should not raise
|
||||
svc.delete_search_session("sess-xyz")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# POST /api/audio-search/search-standalone
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def standalone_client(mock_job_manager_standalone):
|
||||
"""TestClient for standalone search tests."""
|
||||
from backend.services.audio_search_service import AudioSearchResult
|
||||
|
||||
mock_search_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="YouTube",
|
||||
url="https://youtube.com/watch?v=abc",
|
||||
duration=180,
|
||||
quality="320kbps",
|
||||
source_id="abc",
|
||||
index=0,
|
||||
)
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
mock_audio_search.search_async = AsyncMock(return_value=[mock_search_result])
|
||||
mock_audio_search.last_remote_search_id = None
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.create_search_session.return_value = "sess-new-123"
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_standalone
|
||||
|
||||
with patch("backend.api.routes.audio_search.job_manager", mock_job_manager_standalone), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.api.routes.audio_search.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
client._mock_audio_search = mock_audio_search
|
||||
client._mock_firestore = mock_firestore
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager_standalone():
|
||||
return _make_mock_job_manager()
|
||||
|
||||
|
||||
class TestSearchAudioStandalone:
|
||||
"""Tests for POST /api/audio-search/search-standalone."""
|
||||
|
||||
def test_returns_200_and_session_id(self, standalone_client, auth_headers):
|
||||
"""Successful search returns 200 with search_session_id."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "search_session_id" in data
|
||||
assert data["results_count"] == 1
|
||||
|
||||
def test_returns_results_in_response(self, standalone_client, auth_headers):
|
||||
"""Response includes search result details."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
data = response.json()
|
||||
results = data["results"]
|
||||
assert len(results) == 1
|
||||
assert results[0]["title"] == "Waterloo"
|
||||
assert results[0]["provider"] == "YouTube"
|
||||
|
||||
def test_no_job_is_created(self, standalone_client, mock_job_manager_standalone, auth_headers):
|
||||
"""Standalone search must NOT create any job."""
|
||||
standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
mock_job_manager_standalone.create_job.assert_not_called()
|
||||
|
||||
def test_session_is_stored_in_firestore(self, standalone_client, auth_headers):
|
||||
"""Search session is stored in Firestore."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
standalone_client._mock_firestore.create_search_session.assert_called_once()
|
||||
|
||||
def test_no_results_returns_empty_list(self, mock_job_manager_standalone, auth_headers):
|
||||
"""No-results case returns empty results list, not an error."""
|
||||
from backend.services.audio_search_service import NoResultsError
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
mock_audio_search.search_async = AsyncMock(side_effect=NoResultsError("No results"))
|
||||
mock_audio_search.last_remote_search_id = None
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_standalone
|
||||
|
||||
with patch("backend.api.routes.audio_search.job_manager", mock_job_manager_standalone), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.api.routes.audio_search.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "Unknown Artist", "title": "Unknown Song"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["results"] == []
|
||||
assert data["results_count"] == 0
|
||||
|
||||
def test_missing_artist_returns_422(self, standalone_client, auth_headers):
|
||||
"""Missing required artist field returns 422 validation error."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_missing_title_returns_422(self, standalone_client, auth_headers):
|
||||
"""Missing required title field returns 422 validation error."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# POST /api/jobs/create-from-search
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def create_from_search_client(mock_job_manager_cfs):
|
||||
"""TestClient for create-from-search tests with a valid session in Firestore."""
|
||||
session = _make_search_session(user_email="test@example.com")
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
mock_firestore.consume_search_session.return_value = session
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.api.routes.audio_search._validate_and_prepare_selection"), \
|
||||
patch("backend.api.routes.audio_search._download_audio_and_trigger_workers"), \
|
||||
patch("backend.api.routes.audio_search.extract_request_metadata", return_value={}), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
client._mock_firestore = mock_firestore
|
||||
client._mock_jm = mock_job_manager_cfs
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager_cfs():
|
||||
return _make_mock_job_manager()
|
||||
|
||||
|
||||
class TestCreateJobFromSearch:
|
||||
"""Tests for POST /api/jobs/create-from-search."""
|
||||
|
||||
def test_returns_200_with_job_id(self, create_from_search_client, auth_headers):
|
||||
"""Successful call returns 200 with job_id."""
|
||||
response = create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "job_id" in data
|
||||
assert data["job_id"] == "test-job-123"
|
||||
|
||||
def test_job_is_created_via_job_manager(self, create_from_search_client, auth_headers):
|
||||
"""Job must be created through job_manager.create_job."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
create_from_search_client._mock_jm.create_job.assert_called_once()
|
||||
|
||||
def test_is_private_flag_passed_to_job(self, create_from_search_client, auth_headers):
|
||||
"""is_private flag is included in JobCreate passed to job_manager."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"is_private": True,
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
job_create = call_args[0][0] # First positional arg
|
||||
assert job_create.is_private is True
|
||||
|
||||
def test_display_overrides_applied_when_provided(self, create_from_search_client, auth_headers):
|
||||
"""display_artist and display_title overrides are applied."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"display_artist": "Abba (Display)",
|
||||
"display_title": "Waterloo (Karaoke)",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
job_create = call_args[0][0]
|
||||
assert job_create.artist == "Abba (Display)"
|
||||
assert job_create.title == "Waterloo (Karaoke)"
|
||||
|
||||
def test_session_consumed_atomically(self, create_from_search_client, auth_headers):
|
||||
"""Session is consumed (atomically read+deleted) via consume_search_session."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
# consume_search_session handles both read + delete atomically
|
||||
create_from_search_client._mock_firestore.consume_search_session.assert_called_once_with(
|
||||
"sess-abc-123"
|
||||
)
|
||||
# No separate delete_search_session call needed
|
||||
create_from_search_client._mock_firestore.delete_search_session.assert_not_called()
|
||||
|
||||
def test_missing_session_returns_404(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 404 when search session is not found (expired or invalid)."""
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = None # session not found
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "expired-session",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "Search expired" in response.json()["detail"]
|
||||
|
||||
def test_expired_ttl_returns_404(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 404 when session TTL has passed (belt-and-suspenders check)."""
|
||||
expired_session = _make_search_session(user_email="test@example.com", expired=True)
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = expired_session
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "Search expired" in response.json()["detail"]
|
||||
|
||||
def test_tenant_mismatch_returns_403(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 403 when session tenant_id doesn't match the request tenant."""
|
||||
# Session was created in tenant "tenant-a"
|
||||
session_with_tenant = _make_search_session(user_email="test@example.com", tenant_id="tenant-a")
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session_with_tenant
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
# Request arrives from the default (no-tenant) context — tenant_id=None in request.state
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 403
|
||||
|
||||
def test_invalid_selection_index_returns_400(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 400 when selection_index is out of bounds."""
|
||||
session = _make_search_session() # 1 result at index 0
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 99, # out of range
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "Invalid selection index" in response.json()["detail"]
|
||||
|
||||
def test_missing_required_fields_returns_422(self, create_from_search_client, auth_headers):
|
||||
"""Missing required fields return 422 validation error."""
|
||||
response = create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={"search_session_id": "sess-abc-123"}, # missing selection_index, artist, title
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_no_awaiting_selection_state(self, create_from_search_client, auth_headers):
|
||||
"""Job goes directly to downloading — AWAITING_AUDIO_SELECTION is never set."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
# The created job should NOT be in AWAITING_AUDIO_SELECTION
|
||||
# (we verify job_manager.create_job was called and the job status is not AWAITING)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
assert call_args is not None # job was created
|
||||
# The initial status is PENDING — it's then moved to DOWNLOADING_AUDIO
|
||||
# by _validate_and_prepare_selection (which is mocked here)
|
||||
created_job = create_from_search_client._mock_jm.create_job.return_value
|
||||
assert created_job.status != JobStatus.AWAITING_AUDIO_SELECTION
|
||||
|
||||
def test_different_user_cannot_use_anothers_session(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 403 when session belongs to a different user (ownership check)."""
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
# Session belongs to alice, but request comes from bob (non-admin)
|
||||
session = _make_search_session(user_email="alice@example.com")
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
async def bob_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.LIMITED,
|
||||
remaining_uses=5, message="OK", is_admin=False,
|
||||
user_email="bob@example.com",
|
||||
)
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
app.dependency_overrides[require_auth] = bob_auth
|
||||
try:
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
finally:
|
||||
# Restore the default admin mock
|
||||
# Restore the default admin auth (same as conftest autouse fixture)
|
||||
async def _restore_admin_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.ADMIN,
|
||||
remaining_uses=999, message="Test admin token",
|
||||
is_admin=True, user_email="test@example.com",
|
||||
)
|
||||
app.dependency_overrides[require_auth] = _restore_admin_auth
|
||||
|
||||
assert response.status_code == 403
|
||||
|
||||
def test_remote_search_id_stored_in_state_data(self, mock_job_manager_cfs, auth_headers):
|
||||
"""remote_search_id from session is copied to job state_data."""
|
||||
session = _make_search_session(user_email="test@example.com")
|
||||
session["remote_search_id"] = "torrent-search-42"
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
mock_firestore.consume_search_session.return_value = session
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.api.routes.audio_search._validate_and_prepare_selection"), \
|
||||
patch("backend.api.routes.audio_search._download_audio_and_trigger_workers"), \
|
||||
patch("backend.api.routes.audio_search.extract_request_metadata", return_value={}), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Check that update_job was called with state_data containing remote_search_id
|
||||
update_calls = mock_job_manager_cfs.update_job.call_args_list
|
||||
state_data_call = [c for c in update_calls if 'state_data' in c[0][1]]
|
||||
assert len(state_data_call) >= 1
|
||||
state_data = state_data_call[0][0][1]['state_data']
|
||||
assert state_data['remote_search_id'] == "torrent-search-42"
|
||||
|
||||
def test_concurrent_consume_second_request_returns_404(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Second concurrent request to same session gets 404 (session already consumed)."""
|
||||
session = _make_search_session(user_email="test@example.com")
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
# First consume succeeds, simulating that another request already consumed it
|
||||
mock_firestore.consume_search_session.return_value = None
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.api.routes.audio_search._validate_and_prepare_selection"), \
|
||||
patch("backend.api.routes.audio_search._download_audio_and_trigger_workers"), \
|
||||
patch("backend.api.routes.audio_search.extract_request_metadata", return_value={}), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "Search expired" in response.json()["detail"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# POST /api/audio-search/search-standalone — credit check
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSearchStandaloneCredits:
|
||||
"""Tests for credit checking on the standalone search endpoint."""
|
||||
|
||||
def test_insufficient_credits_returns_402(self, auth_headers):
|
||||
"""Non-admin user with no credits gets 402 on search."""
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
mock_user_service = MagicMock()
|
||||
mock_user_service.has_credits.return_value = False
|
||||
mock_user_service.check_credits.return_value = 0
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_creds = _make_mock_creds()
|
||||
mock_jm = _make_mock_job_manager()
|
||||
|
||||
async def regular_user_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.LIMITED,
|
||||
remaining_uses=0, message="OK", is_admin=False,
|
||||
user_email="user@example.com",
|
||||
)
|
||||
|
||||
with patch("backend.api.routes.audio_search.job_manager", mock_jm), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.api.routes.audio_search.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.services.user_service.get_user_service", return_value=mock_user_service), \
|
||||
patch("backend.services.job_manager.JobManager", lambda *a, **k: mock_jm), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
app.dependency_overrides[require_auth] = regular_user_auth
|
||||
try:
|
||||
client = TestClient(app, raise_server_exceptions=False)
|
||||
response = client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
finally:
|
||||
# Restore the default admin auth (same as conftest autouse fixture)
|
||||
async def _restore_admin_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.ADMIN,
|
||||
remaining_uses=999, message="Test admin token",
|
||||
is_admin=True, user_email="test@example.com",
|
||||
)
|
||||
app.dependency_overrides[require_auth] = _restore_admin_auth
|
||||
|
||||
assert response.status_code == 402
|
||||
data = response.json()
|
||||
assert "credits" in data["detail"].lower()
|
||||
@@ -250,28 +250,8 @@ class TestVideoWorkerOrchestratorPackaging:
|
||||
"""Test packaging stage."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_no_lrc_cdg_disabled(self):
|
||||
"""Test packaging stage with no LRC file and CDG disabled skips silently."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=False,
|
||||
lrc_file_path=None,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Should not raise, just skip
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_no_lrc_cdg_enabled_raises(self):
|
||||
"""Test packaging stage raises when CDG enabled but no LRC file."""
|
||||
async def test_run_packaging_no_lrc(self):
|
||||
"""Test packaging stage with no LRC file."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
@@ -284,8 +264,10 @@ class TestVideoWorkerOrchestratorPackaging:
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with pytest.raises(RuntimeError, match="LRC file not available"):
|
||||
await orchestrator._run_packaging()
|
||||
# Should not raise, just skip
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_cdg(self):
|
||||
@@ -386,209 +368,6 @@ class TestVideoWorkerOrchestratorPackaging:
|
||||
"countdown_padding_seconds must be passed for CDG timestamp adjustment"
|
||||
|
||||
|
||||
class TestPackagingValidation:
|
||||
"""Test CDG/TXT packaging validation checks.
|
||||
|
||||
These tests verify that the orchestrator fails fast when CDG/TXT
|
||||
generation is enabled but fails, rather than silently proceeding
|
||||
to expensive encoding. This prevents jobs from completing without
|
||||
their requested CDG/TXT packages.
|
||||
|
||||
Added after jobs 5b6aba25 and 5161b069 completed with enable_cdg=True
|
||||
but no CDG ZIP was produced due to a FileNotFoundError being silently caught.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cdg_validation_fails_when_enabled_but_not_produced(self):
|
||||
"""Test that orchestrator raises when CDG enabled but not produced."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Mock _run_packaging to NOT set result.final_karaoke_cdg_zip (simulates failure)
|
||||
async def mock_packaging():
|
||||
pass # CDG generation "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is False
|
||||
assert "CDG generation was enabled but failed" in result.error_message
|
||||
mock_encoding.assert_not_called() # Should not reach encoding
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_txt_validation_fails_when_enabled_but_not_produced(self):
|
||||
"""Test that orchestrator raises when TXT enabled but not produced."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_txt=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging():
|
||||
pass # TXT generation "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is False
|
||||
assert "TXT generation was enabled but failed" in result.error_message
|
||||
mock_encoding.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pipeline_succeeds_when_cdg_disabled(self):
|
||||
"""Test that pipeline succeeds normally when CDG is not enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=False,
|
||||
enable_txt=False,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_pkg, \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is True
|
||||
mock_pkg.assert_not_called() # Packaging skipped entirely
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cdg_validation_passes_when_cdg_produced(self):
|
||||
"""Test that validation passes when CDG is successfully produced."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging_success():
|
||||
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_success), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_both_cdg_and_txt_validation_fail_together(self):
|
||||
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
enable_txt=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging():
|
||||
pass # Both CDG and TXT "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is False
|
||||
# CDG validation is checked first
|
||||
assert "CDG generation was enabled but failed" in result.error_message
|
||||
mock_encoding.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lrc_missing_raises_when_cdg_enabled(self):
|
||||
"""Test that missing LRC file raises when CDG is enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
lrc_file_path="/nonexistent/path.lrc",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with pytest.raises(RuntimeError, match="LRC file not available"):
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lrc_missing_raises_when_txt_enabled(self):
|
||||
"""Test that missing LRC file raises when TXT is enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_txt=True,
|
||||
lrc_file_path=None,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with pytest.raises(RuntimeError, match="LRC file not available"):
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lrc_missing_skips_when_cdg_disabled(self):
|
||||
"""Test that missing LRC file just skips packaging when CDG/TXT disabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=False,
|
||||
enable_txt=False,
|
||||
lrc_file_path=None,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Should not raise, just skip
|
||||
await orchestrator._run_packaging()
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
|
||||
|
||||
class TestVideoWorkerOrchestratorEncoding:
|
||||
"""Test encoding stage."""
|
||||
|
||||
@@ -993,12 +772,8 @@ class TestVideoWorkerOrchestratorFullPipeline:
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Mock packaging to set CDG result (validation requires it when enable_cdg=True)
|
||||
async def mock_packaging_with_result():
|
||||
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
|
||||
|
||||
# Mock all stages
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_with_result) as mock_packaging, \
|
||||
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_packaging, \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding, \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock) as mock_org, \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock) as mock_dist, \
|
||||
@@ -1512,64 +1287,3 @@ class TestOrchestratorCountdownPadding:
|
||||
assert captured_input is not None, "encode() should have been called"
|
||||
assert captured_input.options.get("countdown_padding_seconds") == 3.0, \
|
||||
"Orchestrator must pass countdown_padding_seconds in EncodingInput.options"
|
||||
|
||||
|
||||
class TestDistributionWarnings:
|
||||
"""Test distribution_warnings tracking in OrchestratorResult."""
|
||||
|
||||
def test_result_has_distribution_warnings_field(self):
|
||||
"""Test that OrchestratorResult has distribution_warnings as empty list by default."""
|
||||
result = OrchestratorResult(success=True)
|
||||
assert result.distribution_warnings == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gdrive_failure_populates_warnings(self):
|
||||
"""Test that Google Drive upload failure populates distribution_warnings."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
gdrive_folder_id="folder-123",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
orchestrator.result.brand_code = "NOMAD-0001"
|
||||
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_get:
|
||||
mock_gdrive = MagicMock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.upload_to_public_share.side_effect = Exception("Connection refused")
|
||||
mock_get.return_value = mock_gdrive
|
||||
|
||||
await orchestrator._upload_to_gdrive()
|
||||
|
||||
assert len(orchestrator.result.distribution_warnings) == 1
|
||||
assert "Google Drive upload failed" in orchestrator.result.distribution_warnings[0]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dropbox_failure_populates_warnings(self):
|
||||
"""Test that Dropbox upload failure populates distribution_warnings."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
dropbox_path="/Public Share",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
orchestrator.result.brand_code = "NOMAD-0001"
|
||||
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service") as mock_get:
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.upload_folder.side_effect = Exception("Auth expired")
|
||||
mock_get.return_value = mock_dropbox
|
||||
|
||||
await orchestrator._upload_to_dropbox()
|
||||
|
||||
assert len(orchestrator.result.distribution_warnings) == 1
|
||||
assert "Dropbox upload failed" in orchestrator.result.distribution_warnings[0]
|
||||
@@ -339,26 +339,15 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
# Store result metadata in job BEFORE transitioning to COMPLETE
|
||||
# This ensures youtube_url is available when completion email is sent
|
||||
logger.info(f"[job:{job_id}] Video generation complete")
|
||||
state_update = {
|
||||
**job.state_data,
|
||||
'brand_code': result.brand_code,
|
||||
'youtube_url': result.youtube_url,
|
||||
'dropbox_link': result.dropbox_link,
|
||||
'gdrive_files': result.gdrive_files,
|
||||
}
|
||||
if result.distribution_warnings:
|
||||
state_update['distribution_warnings'] = result.distribution_warnings
|
||||
job_manager.update_job(job_id, {'state_data': state_update})
|
||||
|
||||
# Send Pushbullet alert if any distribution uploads failed
|
||||
if result.distribution_warnings:
|
||||
_send_distribution_warning_notification(
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
warnings=result.distribution_warnings,
|
||||
settings=settings,
|
||||
)
|
||||
job_manager.update_job(job_id, {
|
||||
'state_data': {
|
||||
**job.state_data,
|
||||
'brand_code': result.brand_code,
|
||||
'youtube_url': result.youtube_url,
|
||||
'dropbox_link': result.dropbox_link,
|
||||
'gdrive_files': result.gdrive_files,
|
||||
}
|
||||
})
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
job_manager.transition_to_state(
|
||||
@@ -852,7 +841,6 @@ async def _handle_native_distribution(
|
||||
job_log.warning(f"Dropbox SDK not installed: {e}")
|
||||
except Exception as e:
|
||||
job_log.error(f"Native Dropbox upload failed: {e}", exc_info=True)
|
||||
result.setdefault('distribution_warnings', []).append(f"Dropbox upload failed: {e}")
|
||||
# Don't fail the job - distribution is optional
|
||||
|
||||
# Upload to Google Drive using native API
|
||||
@@ -896,7 +884,6 @@ async def _handle_native_distribution(
|
||||
job_log.warning(f"Google API packages not installed: {e}")
|
||||
except Exception as e:
|
||||
job_log.error(f"Native Google Drive upload failed: {e}", exc_info=True)
|
||||
result.setdefault('distribution_warnings', []).append(f"Google Drive upload failed: {e}")
|
||||
# Don't fail the job - distribution is optional
|
||||
elif existing_gdrive_files:
|
||||
job_log.info(f"Skipping Google Drive upload - orchestrator already uploaded {len(existing_gdrive_files)} files")
|
||||
@@ -904,64 +891,17 @@ async def _handle_native_distribution(
|
||||
# Update job state_data with brand code and links
|
||||
if brand_code or result.get('dropbox_link') or result.get('gdrive_files'):
|
||||
try:
|
||||
state_update = {
|
||||
**job.state_data,
|
||||
'brand_code': brand_code,
|
||||
'dropbox_link': result.get('dropbox_link'),
|
||||
'gdrive_files': result.get('gdrive_files'),
|
||||
}
|
||||
if result.get('distribution_warnings'):
|
||||
state_update['distribution_warnings'] = result['distribution_warnings']
|
||||
job_manager.update_job(job_id, {'state_data': state_update})
|
||||
job_manager.update_job(job_id, {
|
||||
'state_data': {
|
||||
**job.state_data,
|
||||
'brand_code': brand_code,
|
||||
'dropbox_link': result.get('dropbox_link'),
|
||||
'gdrive_files': result.get('gdrive_files'),
|
||||
}
|
||||
})
|
||||
except Exception as e:
|
||||
job_log.warning(f"Failed to update job state_data: {e}")
|
||||
|
||||
# Send Pushbullet alert if any distribution uploads failed
|
||||
if result.get('distribution_warnings'):
|
||||
_send_distribution_warning_notification(
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
warnings=result['distribution_warnings'],
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
|
||||
def _send_distribution_warning_notification(
|
||||
job_id: str,
|
||||
artist: str,
|
||||
title: str,
|
||||
warnings: list[str],
|
||||
settings=None,
|
||||
) -> None:
|
||||
"""Send Pushbullet notification when distribution uploads fail."""
|
||||
try:
|
||||
if settings is None:
|
||||
settings = get_settings()
|
||||
api_key = settings.get_secret("pushbullet-api-key")
|
||||
if not api_key:
|
||||
logger.warning("Pushbullet API key not found, skipping distribution warning notification")
|
||||
return
|
||||
|
||||
import requests as req
|
||||
|
||||
push_title = f"Distribution Warning: {artist} - {title}"
|
||||
body = f"Job {job_id} completed but {len(warnings)} upload(s) failed:\n\n"
|
||||
body += "\n".join(f" - {w}" for w in warnings)
|
||||
|
||||
resp = req.post(
|
||||
"https://api.pushbullet.com/v2/pushes",
|
||||
headers={"Access-Token": api_key, "Content-Type": "application/json"},
|
||||
json={"type": "note", "title": push_title, "body": body},
|
||||
timeout=10,
|
||||
)
|
||||
if resp.ok:
|
||||
logger.info(f"[job:{job_id}] Distribution warning notification sent via Pushbullet")
|
||||
else:
|
||||
logger.warning(f"[job:{job_id}] Pushbullet notification failed: {resp.status_code} {resp.text}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to send Pushbullet notification: {e}")
|
||||
|
||||
|
||||
def _validate_prerequisites(job) -> bool:
|
||||
"""Validate that all prerequisites are met for video generation."""
|
||||
|
||||
@@ -109,9 +109,6 @@ class OrchestratorResult:
|
||||
dropbox_link: Optional[str] = None
|
||||
gdrive_files: Optional[Dict[str, str]] = field(default_factory=dict)
|
||||
|
||||
# Distribution warnings (non-fatal upload failures)
|
||||
distribution_warnings: List[str] = field(default_factory=list)
|
||||
|
||||
# Timing
|
||||
encoding_time_seconds: Optional[float] = None
|
||||
total_time_seconds: Optional[float] = None
|
||||
@@ -231,18 +228,6 @@ class VideoWorkerOrchestrator:
|
||||
if self.config.enable_cdg or self.config.enable_txt:
|
||||
await self._run_packaging()
|
||||
|
||||
# Validate required packaging outputs before expensive encoding
|
||||
if self.config.enable_cdg and not self.result.final_karaoke_cdg_zip:
|
||||
raise RuntimeError(
|
||||
"CDG generation was enabled but failed. "
|
||||
"Check worker logs for CDG-related errors."
|
||||
)
|
||||
if self.config.enable_txt and not self.result.final_karaoke_txt_zip:
|
||||
raise RuntimeError(
|
||||
"TXT generation was enabled but failed. "
|
||||
"Check worker logs for TXT-related errors."
|
||||
)
|
||||
|
||||
# Stage 2: Encoding
|
||||
await self._run_encoding()
|
||||
|
||||
@@ -255,11 +240,6 @@ class VideoWorkerOrchestrator:
|
||||
# Stage 5: Notifications (Discord)
|
||||
await self._run_notifications()
|
||||
|
||||
# Stage 6: Post-distribution GDrive validation
|
||||
# Only for jobs that uploaded to the public share (non-private)
|
||||
if self.config.gdrive_folder_id:
|
||||
await self._trigger_gdrive_validation()
|
||||
|
||||
self.result.success = True
|
||||
self.result.total_time_seconds = time.time() - start_time
|
||||
|
||||
@@ -279,10 +259,6 @@ class VideoWorkerOrchestrator:
|
||||
self.job_log.info("Starting packaging stage (CDG/TXT)")
|
||||
|
||||
if not self.config.lrc_file_path or not os.path.isfile(self.config.lrc_file_path):
|
||||
if self.config.enable_cdg or self.config.enable_txt:
|
||||
raise RuntimeError(
|
||||
f"CDG/TXT generation enabled but LRC file not available: {self.config.lrc_file_path}"
|
||||
)
|
||||
self.job_log.warning("No LRC file available, skipping CDG/TXT packaging")
|
||||
return
|
||||
|
||||
@@ -611,7 +587,6 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"YouTube upload failed: {e}")
|
||||
self.result.distribution_warnings.append(f"YouTube upload failed: {e}")
|
||||
# Don't fail the pipeline - YouTube is optional
|
||||
|
||||
async def _upload_to_dropbox(self):
|
||||
@@ -648,7 +623,6 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Dropbox upload failed: {e}")
|
||||
self.result.distribution_warnings.append(f"Dropbox upload failed: {e}")
|
||||
# Don't fail the pipeline - Dropbox is optional
|
||||
|
||||
async def _upload_to_gdrive(self):
|
||||
@@ -685,7 +659,6 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Google Drive upload failed: {e}")
|
||||
self.result.distribution_warnings.append(f"Google Drive upload failed: {e}")
|
||||
# Don't fail the pipeline - GDrive is optional
|
||||
|
||||
async def _run_notifications(self):
|
||||
@@ -708,28 +681,6 @@ class VideoWorkerOrchestrator:
|
||||
self.job_log.error(f"Discord notification failed: {e}")
|
||||
# Don't fail the pipeline - notifications are optional
|
||||
|
||||
async def _trigger_gdrive_validation(self):
|
||||
"""Schedule delayed GDrive validation after uploading to the public share.
|
||||
|
||||
Uses Cloud Tasks to delay the validation by 5 minutes, giving E2E tests
|
||||
time to verify output and clean up (delete test files) before the validator
|
||||
checks for sequence gaps. Falls back to immediate trigger if scheduling fails.
|
||||
"""
|
||||
try:
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
success = await worker_service.schedule_gdrive_validation()
|
||||
if success:
|
||||
self.job_log.info("Scheduled delayed GDrive validation (5 min)")
|
||||
else:
|
||||
# Fallback: trigger immediately if scheduling failed
|
||||
self.job_log.warning("Cloud Tasks scheduling failed, triggering validation immediately")
|
||||
from backend.services.gdrive_validator_client import trigger_gdrive_validation
|
||||
trigger_gdrive_validation()
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"GDrive validation trigger failed (non-fatal): {e}")
|
||||
# Never fail the pipeline for validation
|
||||
|
||||
|
||||
def create_orchestrator_config_from_job(
|
||||
job,
|
||||
|
||||
@@ -80,46 +80,7 @@ title: "Song Title"
|
||||
is_private: false # Optional. If true, Dropbox uses Tracks-NonPublished/NOMADNP, no YouTube/GDrive
|
||||
```
|
||||
|
||||
Returns job ID. Triggers async processing. Max request body ~32MB (Cloud Run limit). For larger files, use the signed URL upload flow below.
|
||||
|
||||
#### Create Job with Signed URL Upload (large files)
|
||||
|
||||
Three-step flow that bypasses Cloud Run's 32MB body limit. Used automatically by the frontend for files ≥25MB.
|
||||
|
||||
**Step 1: Create job and get signed URLs**
|
||||
```http
|
||||
POST /api/jobs/create-with-upload-urls
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "Artist Name",
|
||||
"title": "Song Title",
|
||||
"files": [{"filename": "song.wav", "content_type": "audio/wav", "file_type": "audio"}],
|
||||
"is_private": false
|
||||
}
|
||||
```
|
||||
|
||||
Returns `job_id` and `upload_urls` list. Each entry has `file_type`, `upload_url` (signed GCS URL), and `content_type`.
|
||||
|
||||
**Step 2: Upload file directly to GCS**
|
||||
```http
|
||||
PUT <upload_url>
|
||||
Content-Type: audio/wav
|
||||
|
||||
<file bytes>
|
||||
```
|
||||
|
||||
Direct PUT to GCS signed URL — does not go through the backend.
|
||||
|
||||
**Step 3: Notify backend**
|
||||
```http
|
||||
POST /api/jobs/{job_id}/uploads-complete
|
||||
Content-Type: application/json
|
||||
|
||||
{"uploaded_files": ["audio"]}
|
||||
```
|
||||
|
||||
Triggers async processing.
|
||||
Returns job ID. Triggers async processing.
|
||||
|
||||
#### Get Job Status
|
||||
|
||||
@@ -148,7 +109,7 @@ Query parameters:
|
||||
- `status` - Filter by job status
|
||||
- `limit` / `offset` - Pagination
|
||||
- `fields` (string, optional) - Set to `summary` to return only dashboard-required fields using Firestore field projection. Reduces payload from ~16MB to <500KB for large job lists.
|
||||
- `hide_completed` (bool, default: false) - Exclude successful completions (complete, prep_complete) server-side. Failed jobs remain visible.
|
||||
- `hide_completed` (bool, default: false) - Exclude terminal statuses (complete, prep_complete, failed, cancelled) server-side
|
||||
|
||||
#### Delete Job
|
||||
|
||||
@@ -264,51 +225,6 @@ Error (duration mismatch):
|
||||
}
|
||||
```
|
||||
|
||||
#### Submit Edit Log
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/edit-log
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"session_id": "abc123",
|
||||
"job_id": "test-job",
|
||||
"audio_hash": "hash",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": [
|
||||
{
|
||||
"id": "entry-1",
|
||||
"timestamp": "2026-03-01T00:01:00.000Z",
|
||||
"operation": "word_change",
|
||||
"segment_id": "seg-0",
|
||||
"segment_index": 0,
|
||||
"word_ids_before": ["w1"],
|
||||
"word_ids_after": ["w1"],
|
||||
"text_before": "helo",
|
||||
"text_after": "hello",
|
||||
"feedback": { "reason": "misheard_word", "timestamp": "..." }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Stores a session edit log to GCS at `jobs/{job_id}/lyrics/edit_log_{session_id}.json`. Tracks all user edits and optional feedback reasons for transcription improvement. Called automatically on review submission.
|
||||
|
||||
#### Submit Annotations
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/v1/annotations
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"annotations": [
|
||||
{ "annotation_type": "SOUND_ALIKE", "original_text": "helo" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
|
||||
|
||||
### Instrumental Selection (Finalise-Only Jobs)
|
||||
|
||||
For finalise-only jobs (where audio prep was done externally), instrumental selection is handled separately:
|
||||
@@ -373,56 +289,6 @@ Content-Type: application/json
|
||||
|
||||
Selects an audio source from the search results and starts processing.
|
||||
|
||||
#### Standalone Search (Guided Flow — Step 2)
|
||||
|
||||
```http
|
||||
POST /api/audio-search/search-standalone
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "Artist Name",
|
||||
"title": "Song Title"
|
||||
}
|
||||
```
|
||||
|
||||
Searches for audio **without creating a job**. Returns a short-lived search session (30-min TTL).
|
||||
Credits are checked here but **not deducted** — deduction happens at job creation.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"search_session_id": "uuid",
|
||||
"results": [...],
|
||||
"results_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
No results returns `results: []` (not a 404). Use `search_session_id` with the create-from-search endpoint below.
|
||||
|
||||
#### Create Job from Search Session (Guided Flow — Step 3)
|
||||
|
||||
```http
|
||||
POST /api/jobs/create-from-search
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"search_session_id": "uuid",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"display_artist": "ABBA (Display)",
|
||||
"display_title": "Waterloo (Karaoke)",
|
||||
"is_private": false
|
||||
}
|
||||
```
|
||||
|
||||
Creates the job from a previously completed standalone search session. All final field values
|
||||
(is_private, display overrides) are set at creation time — no patching needed afterward.
|
||||
The job goes directly to `DOWNLOADING_AUDIO` (skips `AWAITING_AUDIO_SELECTION`).
|
||||
The session is consumed (deleted) on success.
|
||||
|
||||
Returns 404 with "Search expired — please search again" if the session has expired.
|
||||
|
||||
### Themes
|
||||
|
||||
```http
|
||||
@@ -572,8 +438,6 @@ GET /api/users/me
|
||||
Authorization: Bearer SESSION_TOKEN
|
||||
```
|
||||
|
||||
Response includes `feedback_eligible: bool` indicating whether the user can earn credits by submitting feedback (requires 2+ completed jobs and no prior feedback submission).
|
||||
|
||||
### Logout
|
||||
|
||||
```http
|
||||
@@ -652,7 +516,7 @@ Credits are checked and deducted at job creation time. The flow:
|
||||
3. **Deduct** - `user_service.deduct_credit()` atomically deducts 1 credit (with job_id for audit trail)
|
||||
4. **Refund on failure** - If the job fails, 1 credit is automatically refunded
|
||||
|
||||
Admin users bypass credit checks entirely. New users receive 2 welcome credits. Users can earn 2 additional free credits by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
|
||||
Admin users bypass credit checks entirely. New users receive 2 welcome credits.
|
||||
|
||||
#### 402 Response
|
||||
|
||||
@@ -675,9 +539,7 @@ POST /api/users/webhooks/stripe
|
||||
|
||||
Handles `checkout.session.completed` events.
|
||||
|
||||
## Beta Tester Program (Deprecated)
|
||||
|
||||
> **Note**: The beta program was removed from the homepage in PR #430. These endpoints are preserved for backward compatibility but are no longer actively promoted. New users receive 2 welcome credits instead. See [User Feedback for Credits](#user-feedback-for-credits) for the current feedback-for-credits mechanism.
|
||||
## Beta Tester Program (PR #90)
|
||||
|
||||
### Enroll as Beta Tester
|
||||
|
||||
@@ -694,7 +556,7 @@ Content-Type: application/json
|
||||
|
||||
Returns 1 free credit and session token.
|
||||
|
||||
### Submit Beta Feedback
|
||||
### Submit Feedback
|
||||
|
||||
```http
|
||||
POST /api/users/beta/feedback
|
||||
@@ -713,56 +575,6 @@ Content-Type: application/json
|
||||
|
||||
Bonus credit for detailed feedback (50+ chars).
|
||||
|
||||
### User Feedback for Credits
|
||||
|
||||
Available to all users (not just beta testers). Users who have completed 2+ jobs can submit feedback to earn 2 free credits.
|
||||
|
||||
#### Check Eligibility
|
||||
|
||||
```http
|
||||
GET /api/users/feedback/eligibility
|
||||
Authorization: Bearer SESSION_TOKEN
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"eligible": true,
|
||||
"has_submitted": false,
|
||||
"jobs_completed": 3,
|
||||
"credits_reward": 2
|
||||
}
|
||||
```
|
||||
|
||||
#### Submit Feedback
|
||||
|
||||
```http
|
||||
POST /api/users/feedback
|
||||
Authorization: Bearer SESSION_TOKEN
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"overall_rating": 4,
|
||||
"ease_of_use_rating": 5,
|
||||
"lyrics_accuracy_rating": 4,
|
||||
"correction_experience_rating": 3,
|
||||
"what_went_well": "The lyrics sync was really accurate...",
|
||||
"what_could_improve": "Would love more theme options...",
|
||||
"additional_comments": "",
|
||||
"would_recommend": true,
|
||||
"would_use_again": true
|
||||
}
|
||||
```
|
||||
|
||||
Requirements:
|
||||
- User must have completed 2+ jobs
|
||||
- At least one text field must have >50 characters
|
||||
- User can only submit once (duplicate prevention)
|
||||
|
||||
Grants 2 credits on success. Feedback stored in `user_feedback` Firestore collection.
|
||||
|
||||
The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide feedback prompts without an extra API call.
|
||||
|
||||
## Admin Endpoints
|
||||
|
||||
All admin endpoints require an admin-role session token.
|
||||
@@ -1168,7 +980,7 @@ Allowed target states:
|
||||
**Note**: With the combined review flow, `awaiting_instrumental_selection` is no longer a valid reset target for new jobs. Use `awaiting_review` instead to re-select the instrumental.
|
||||
|
||||
The `instrumental_selected` state is useful for re-encoding and re-distributing a job after using "Delete Outputs":
|
||||
1. Delete outputs → Removes YouTube/Dropbox/GDrive files, recycles brand code
|
||||
1. Delete outputs → Removes YouTube/Dropbox/GDrive files, frees brand code
|
||||
2. Reset to `instrumental_selected` → Clears video state, keeps settings, auto-triggers video worker
|
||||
3. Job re-processes with same instrumental, lyrics, and distribution settings
|
||||
|
||||
@@ -1393,7 +1205,7 @@ POST /api/admin/jobs/{job_id}/delete-outputs
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Deletes all distributed outputs (YouTube, Dropbox, Google Drive) for a job and recycles the brand code. The job record is preserved. Use this to fix quality issues: delete outputs, reset to `awaiting_review`, correct lyrics, and re-process.
|
||||
Deletes all distributed outputs (YouTube, Dropbox, Google Drive) for a job while preserving the job record. Use this to fix quality issues: delete outputs, reset to `awaiting_review`, correct lyrics, and re-process.
|
||||
|
||||
Requirements:
|
||||
- Job must be in terminal state (`complete`, `prep_complete`, `failed`, or `cancelled`)
|
||||
@@ -1408,8 +1220,7 @@ Response:
|
||||
"deleted_services": {
|
||||
"youtube": {"status": "success", "video_id": "dQw4w9WgXcQ"},
|
||||
"dropbox": {"status": "success", "path": "/Karaoke/NOMAD-1234 - Artist - Title"},
|
||||
"gdrive": {"status": "success", "files": {"mp4": true, "mp4_720p": true}},
|
||||
"brand_code": {"status": "recycled", "code": "NOMAD-1234"}
|
||||
"gdrive": {"status": "success", "files": {"mp4": true, "mp4_720p": true}}
|
||||
},
|
||||
"cleared_state_data": ["youtube_url", "brand_code", "dropbox_link", "gdrive_files"],
|
||||
"outputs_deleted_at": "2026-01-10T12:00:00Z"
|
||||
@@ -1418,7 +1229,7 @@ Response:
|
||||
|
||||
Service statuses: `success`, `failed`, `skipped` (not configured or no data), `partial` (some files failed), `error` (exception).
|
||||
|
||||
The brand code is automatically recycled after both Dropbox and GDrive cleanup succeed. If either cleanup fails, the brand code is preserved to prevent collisions. Brand code recycling status is returned in `deleted_services.brand_code`. The `DELETE /api/jobs/{id}` endpoint also recycles brand codes before deletion. When the job is re-processed and outputs are re-uploaded, the `outputs_deleted_at` flag is automatically cleared.
|
||||
The brand code is freed for reuse when the Dropbox folder is deleted. When the job is re-processed and outputs are re-uploaded, the `outputs_deleted_at` flag is automatically cleared.
|
||||
|
||||
#### Clear Worker Progress
|
||||
|
||||
|
||||
@@ -119,8 +119,6 @@ jobs/{job_id}/
|
||||
├── lyrics/
|
||||
│ ├── corrections.json # Auto-corrected
|
||||
│ ├── corrections_updated.json # After human review
|
||||
│ ├── edit_log_{session}.json # User edit log with feedback
|
||||
│ ├── annotations.json # Correction annotations
|
||||
│ └── karaoke.ass
|
||||
├── screens/
|
||||
│ ├── title.mov
|
||||
@@ -182,8 +180,7 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
|
||||
| `jobs/{job_id}/logs` | Worker log entries (subcollection) | timestamp, level, worker, message, ttl_expiry |
|
||||
| `sessions` | Magic link auth sessions | user_email, token, expires_at |
|
||||
| `magic_links` | Passwordless auth tokens | email, token, expires_at, used |
|
||||
| `user_feedback` | User feedback for credits (all users) | user_email, ratings, comments, created_at |
|
||||
| `beta_feedback` | Beta program feedback (deprecated) | user_email, ratings, comments |
|
||||
| `beta_feedback` | Beta program feedback | user_email, ratings, comments |
|
||||
|
||||
**Note**: The `users` collection in the same Firestore instance belongs to karaoke-decide (different schema: user_id, is_guest, quiz_* fields). Don't use it for karaoke-gen.
|
||||
|
||||
|
||||
@@ -17,10 +17,11 @@
|
||||
### 1. New User Registration (testmail.app)
|
||||
|
||||
- [ ] Navigate to landing page (`gen.nomadkaraoke.com`)
|
||||
- [ ] Click "Sign Up Free" button on landing page
|
||||
- [ ] Click "Sign In" or "Get Started" button
|
||||
- [ ] Generate a unique test email address (testmail.app namespace)
|
||||
- [ ] Enter the test email in the AuthDialog and click "Send Sign-In Link"
|
||||
- [ ] Wait for magic-link email via testmail.app API
|
||||
- [ ] Enter the test email in the beta enrollment form
|
||||
- [ ] Submit the form
|
||||
- [ ] Wait for welcome/magic-link email via testmail.app API
|
||||
- [ ] Extract the magic link from the email
|
||||
- [ ] Click/navigate to the magic link to authenticate
|
||||
- [ ] Verify user is logged in and has credits
|
||||
@@ -35,13 +36,12 @@
|
||||
- [ ] Click "Search" or equivalent button
|
||||
- [ ] Wait for search results to appear in the UI
|
||||
|
||||
### 3. Audio Selection & Customization (UI Only)
|
||||
### 3. Audio Selection (UI Only)
|
||||
|
||||
- [ ] Audio selection dialog/panel should appear
|
||||
- [ ] View available audio options in the UI
|
||||
- [ ] Click to select the first/best audio option
|
||||
- [ ] Confirm the selection via UI button
|
||||
- [ ] **Enable private mode** (check the `#guided-private` checkbox) — test jobs use `NOMADNP` prefix to avoid consuming public `NOMAD` brand codes and skip GDrive/YouTube uploads
|
||||
- [ ] Wait for job to transition to processing state
|
||||
|
||||
### 4. Wait for Lyrics Transcription
|
||||
@@ -93,12 +93,14 @@
|
||||
> **CRITICAL**: Test MUST clean up after itself to avoid polluting production distribution channels
|
||||
|
||||
- [ ] Verify job.state_data contains distribution results:
|
||||
- [ ] `brand_code` - The generated brand code (e.g., `NOMADNP-0042` for private mode)
|
||||
- [ ] `brand_code` - The generated brand code (e.g., "NOMAD-1234")
|
||||
- [ ] `youtube_url` - YouTube video URL (if YouTube enabled)
|
||||
- [ ] `dropbox_link` - Dropbox shared link (if Dropbox enabled)
|
||||
- [ ] YouTube and GDrive should NOT be present (private mode skips them)
|
||||
- [ ] **CLEANUP** - After verification, clean up via `cleanup-distribution` endpoint:
|
||||
- [ ] Deletes Dropbox folder and recycles brand code
|
||||
- [ ] YouTube/GDrive cleanup skipped for private jobs
|
||||
- [ ] `gdrive_files` - Google Drive file IDs (if GDrive enabled)
|
||||
- [ ] **CLEANUP** - After verification, delete all distributed content:
|
||||
- [ ] Delete YouTube video via API (using stored youtube_url)
|
||||
- [ ] Delete Dropbox folder via API (using brand_code + dropbox_path)
|
||||
- [ ] Delete Google Drive files via API (using gdrive_files IDs)
|
||||
- [ ] Delete the test job from the system (GCS + Firestore)
|
||||
|
||||
## Technical Requirements
|
||||
@@ -135,7 +137,7 @@ Use `piri - dog` because:
|
||||
|
||||
Capture screenshots at each major milestone:
|
||||
1. Landing page loaded
|
||||
2. Magic link sent
|
||||
2. Beta form submitted
|
||||
3. Email received
|
||||
4. Logged in successfully
|
||||
5. Job created
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
# Google Drive Validator
|
||||
|
||||
Automated validation of the Nomad Karaoke public Google Drive share folder. Detects duplicate brand codes, invalid filenames, and sequence gaps.
|
||||
|
||||
## Overview
|
||||
|
||||
The public share folder (`1laRKAyxo0v817SstfM5XkpbWiNKNAMSX`) contains all published karaoke tracks organized into subfolders:
|
||||
|
||||
```
|
||||
Public Share/
|
||||
CDG/ # .zip files (MP3 + CDG for KJ players)
|
||||
MP4/ # .mp4 files (4K lossless)
|
||||
MP4-720p/ # .mp4 files (720p lossy)
|
||||
```
|
||||
|
||||
Each file follows the naming convention: `NOMAD-XXXX - Artist - Title.(mp4|zip)`
|
||||
|
||||
The validator checks:
|
||||
- **Duplicate sequence numbers** - e.g., two files both named `NOMAD-1271`
|
||||
- **Invalid filenames** - files that don't match the expected pattern
|
||||
- **Sequence gaps** - missing numbers in the NOMAD-XXXX sequence (with known exclusions)
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌────────────────────────┐
|
||||
│ Cloud Scheduler │
|
||||
│ (9 PM ET daily) │
|
||||
└──────────┬─────────────┘
|
||||
│ OIDC auth
|
||||
▼
|
||||
┌──────────────────┐ ┌────────────────────────┐ ┌──────────────┐
|
||||
│ Backend (post- │ OIDC │ gdrive-validator │ API │ Google Drive │
|
||||
│ job completion) │─────────→│ Cloud Function (Gen2) │─────────→│ API v3 │
|
||||
└──────────────────┘ └──────────┬─────────────┘ └──────────────┘
|
||||
│
|
||||
┌──────────────────┐ ┌──────┴──────┐
|
||||
│ gcloud functions │ │ │
|
||||
│ call (manual) │─────────→ ▼ ▼
|
||||
└──────────────────┘ ┌───────────┐ ┌────────────┐
|
||||
│ SendGrid │ │ Pushbullet │
|
||||
│ (primary) │ │ (fallback) │
|
||||
└───────────┘ └────────────┘
|
||||
```
|
||||
|
||||
### Trigger Points
|
||||
|
||||
| Trigger | When | How |
|
||||
|---------|------|-----|
|
||||
| **Daily schedule** | 9:00 PM ET every day | Cloud Scheduler → HTTP POST with OIDC token |
|
||||
| **Post-job** | 5 minutes after each job uploads to public share | Backend orchestrator → Cloud Tasks (5 min delay) → internal endpoint → Cloud Function |
|
||||
| **Manual** | On demand | `python scripts/check_public_share.py` via gcloud CLI |
|
||||
|
||||
### Notifications
|
||||
|
||||
Notifications are sent via **both** channels (belt + suspenders):
|
||||
|
||||
1. **SendGrid email** (primary) - Sent to `gen@nomadkaraoke.com`. Provides a persistent, searchable record.
|
||||
2. **Pushbullet** (fallback) - Push notification for immediate visibility.
|
||||
|
||||
Notifications are sent when:
|
||||
- Issues are found (always)
|
||||
- No issues found and `NOTIFY_ON_SUCCESS=true` (daily summary)
|
||||
- Errors occur during validation
|
||||
|
||||
## Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `infrastructure/functions/gdrive_validator/main.py` | Cloud Function source code |
|
||||
| `infrastructure/functions/gdrive_validator/requirements.txt` | Python dependencies |
|
||||
| `infrastructure/functions/gdrive_validator/deploy.sh` | Manual deployment script |
|
||||
| `infrastructure/__main__.py` | Pulumi config (env vars, secrets, IAM) |
|
||||
| `infrastructure/modules/iam/worker_sas.py` | Service account definition |
|
||||
| `backend/services/gdrive_validator_client.py` | Backend HTTP client (OIDC auth) |
|
||||
| `backend/services/worker_service.py` | Cloud Tasks scheduling (5 min delay) |
|
||||
| `backend/api/routes/internal.py` | `/internal/trigger-gdrive-validation` endpoint |
|
||||
| `backend/workers/video_worker_orchestrator.py` | Post-job trigger integration |
|
||||
| `infrastructure/modules/cloud_tasks.py` | Pulumi config for `gdrive-validation-queue` |
|
||||
| `infrastructure/functions/gdrive_validator/test_main.py` | Unit tests for Cloud Function |
|
||||
| `scripts/check_public_share.py` | Local CLI for manual checks |
|
||||
|
||||
## Configuration
|
||||
|
||||
### Environment Variables (Cloud Function)
|
||||
|
||||
| Variable | Value | Description |
|
||||
|----------|-------|-------------|
|
||||
| `GDRIVE_FOLDER_ID` | `1laRKAyxo0v817SstfM5XkpbWiNKNAMSX` | Root folder of public share |
|
||||
| `NOTIFY_ON_SUCCESS` | `true` | Send daily "all clear" summary |
|
||||
| `EMAIL_TO` | `gen@nomadkaraoke.com` | Email recipient |
|
||||
| `EMAIL_FROM` | `gen@nomadkaraoke.com` | Email sender |
|
||||
|
||||
### Secrets (Cloud Function)
|
||||
|
||||
| Secret | Source | Description |
|
||||
|--------|--------|-------------|
|
||||
| `SENDGRID_API_KEY` | `sendgrid-api-key:latest` | SendGrid API key for email |
|
||||
| `PUSHBULLET_API_KEY` | `pushbullet-api-key:latest` | Pushbullet API key for push notifications |
|
||||
|
||||
### Secrets (Backend / Cloud Run)
|
||||
|
||||
| Secret | Source | Description |
|
||||
|--------|--------|-------------|
|
||||
| `GDRIVE_VALIDATOR_URL` | `gdrive-validator-url:latest` | Cloud Function URL for post-job trigger |
|
||||
|
||||
### IAM
|
||||
|
||||
| Principal | Role | Resource | Purpose |
|
||||
|-----------|------|----------|---------|
|
||||
| `gdrive-validator@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Self-invoke (Cloud Scheduler) |
|
||||
| Cloud Scheduler agent | `roles/cloudfunctions.invoker` | gdrive-validator function | Daily trigger |
|
||||
| `karaoke-backend@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Post-job trigger |
|
||||
| `karaoke-backend@` SA | `roles/run.invoker` | gdrive-validator Cloud Run service | Gen2 function HTTP access |
|
||||
|
||||
### Known Gaps
|
||||
|
||||
The validator knows about expected sequence gaps (historical missing numbers). These are configured identically in both:
|
||||
- `infrastructure/functions/gdrive_validator/main.py` (Cloud Function)
|
||||
- `scripts/validate_and_sync.py` (local script)
|
||||
|
||||
When a new gap is discovered intentionally (e.g., a track was removed), update the `KNOWN_GAPS` dict in **both** files.
|
||||
|
||||
## Usage
|
||||
|
||||
### Manual Check
|
||||
|
||||
```bash
|
||||
# Formatted output
|
||||
python scripts/check_public_share.py
|
||||
|
||||
# Raw JSON
|
||||
python scripts/check_public_share.py --json
|
||||
```
|
||||
|
||||
Exit codes: `0` = all clear, `1` = issues found, `2` = error.
|
||||
|
||||
### Checking Cloud Function Logs
|
||||
|
||||
```bash
|
||||
gcloud functions logs read gdrive-validator --region=us-central1 --project=nomadkaraoke --limit=50
|
||||
```
|
||||
|
||||
### Redeploying the Cloud Function
|
||||
|
||||
The Cloud Function source is not deployed via CI — it's deployed either:
|
||||
1. **Via Pulumi** (infrastructure changes like env vars, secrets, IAM)
|
||||
2. **Via `deploy.sh`** (code changes to `main.py`)
|
||||
|
||||
```bash
|
||||
cd infrastructure/functions/gdrive_validator
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
Note: `deploy.sh` deploys the source code. Pulumi manages the infrastructure (env vars, secrets, IAM, scheduler). After running `deploy.sh`, the Pulumi-managed config is overwritten by the gcloud deploy — run `pulumi up` afterward if you need to restore Pulumi-managed settings.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Email Not Received
|
||||
|
||||
1. Check Cloud Function logs for SendGrid errors:
|
||||
```bash
|
||||
gcloud functions logs read gdrive-validator --region=us-central1 --limit=20
|
||||
```
|
||||
2. Verify the SendGrid API key is set:
|
||||
```bash
|
||||
gcloud secrets versions access latest --secret=sendgrid-api-key --project=nomadkaraoke | head -c 10
|
||||
```
|
||||
3. Check SendGrid dashboard for delivery status
|
||||
4. Pushbullet should still work as fallback
|
||||
|
||||
### Post-Job Trigger Not Firing
|
||||
|
||||
The post-job trigger uses a 5-minute Cloud Tasks delay (via `gdrive-validation-queue`) to allow E2E test cleanup to finish before validation runs.
|
||||
|
||||
1. Check that `GDRIVE_VALIDATOR_URL` secret is set:
|
||||
```bash
|
||||
gcloud secrets versions access latest --secret=gdrive-validator-url --project=nomadkaraoke
|
||||
```
|
||||
2. Check backend logs for "Scheduled delayed GDrive validation" or "GDrive validation trigger failed"
|
||||
3. Check Cloud Tasks queue for pending tasks:
|
||||
```bash
|
||||
gcloud tasks list --queue=gdrive-validation-queue --location=us-central1 --project=nomadkaraoke
|
||||
```
|
||||
4. Verify the backend SA has invoker permissions:
|
||||
```bash
|
||||
gcloud functions get-iam-policy gdrive-validator --region=us-central1 --project=nomadkaraoke
|
||||
```
|
||||
5. The trigger only fires for non-private jobs (jobs with `gdrive_folder_id` set)
|
||||
6. If Cloud Tasks scheduling fails, the orchestrator falls back to immediate validation
|
||||
|
||||
### False Positive Gaps
|
||||
|
||||
If the validator reports gaps that are intentional:
|
||||
1. Add the gap number(s) to `KNOWN_GAPS` in both `main.py` and `scripts/validate_and_sync.py`
|
||||
2. Redeploy the cloud function with `./deploy.sh`
|
||||
|
||||
### Duplicate Brand Code Detected
|
||||
|
||||
This is the most critical alert. Steps:
|
||||
1. Check which files have the duplicate: the notification lists them
|
||||
2. Determine which is correct (check Firestore job records)
|
||||
3. Remove or rename the incorrect file in Google Drive
|
||||
4. Re-trigger validation to confirm the fix
|
||||
|
||||
## Cloud Function vs Local Script
|
||||
|
||||
| Check | Cloud Function | Local Script (`validate_and_sync.py`) |
|
||||
|-------|---------------|--------------------------------------|
|
||||
| Duplicate sequence numbers | Yes | Yes |
|
||||
| Invalid filenames | Yes | Yes |
|
||||
| Sequence gaps | Yes | Yes |
|
||||
| ZIP contents (MP3+CDG) | No (expensive) | Yes |
|
||||
| Video resolution | No (expensive) | Yes |
|
||||
| Render quality | No (expensive) | Yes |
|
||||
| Bidirectional sync | No (read-only) | Yes (rclone) |
|
||||
|
||||
The cloud function does metadata-only checks via the GDrive API (fast, cheap, can run frequently). The local script does deep content validation that requires downloading files (slow, run manually).
|
||||
|
||||
## History
|
||||
|
||||
- **2025-12-24**: Initial cloud function deployed with Pushbullet notifications and daily Cloud Scheduler trigger
|
||||
- **2026-02-28**: Added SendGrid email (primary), kept Pushbullet (fallback). Added post-job trigger from backend. Added `scripts/check_public_share.py` for manual invocation. Motivated by NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours.
|
||||
- **2026-03-02**: NOMAD-1276 incident fix. Post-job trigger now uses 5-minute Cloud Tasks delay instead of immediate invocation, preventing false "all clear" when E2E test files are still in GDrive during cleanup. Also fixed cross-folder gap detection (uses global max across all folders) and added 28 unit tests for the Cloud Function.
|
||||
@@ -6,16 +6,6 @@ Key insights for future AI agents working on this codebase.
|
||||
|
||||
---
|
||||
|
||||
## UX Patterns
|
||||
|
||||
### Fixture-Driven UI Verification
|
||||
For UI that renders differently based on data (e.g., audio search result tiers), fetch real production data as fixtures and build a Playwright review tool. The `npm run fixtures:review-ui` pattern (41 fixtures, console-based `next()` advancement) was far more effective than manual testing or screenshots — caught edge cases with non-Latin filenames, single-character filenames, and underscore-separated names that unit tests alone would have missed.
|
||||
|
||||
### Filename Matching Normalization
|
||||
When comparing filenames to search titles, treat underscores/hyphens/dots as word separators BEFORE stripping non-alphanumeric chars. Also require a minimum substring length (3 chars) to prevent false matches like filename "K" matching title "KoREH". For non-Latin scripts (Hebrew, etc.), return an indeterminate result rather than a false match or false mismatch.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
### Separate Collections for Multi-App Projects
|
||||
@@ -33,9 +23,6 @@ Audio separation and lyrics transcription run in parallel. Both can fail indepen
|
||||
### GCE Instance Selection for FFmpeg
|
||||
AMD EPYC (C4D series) significantly outperforms Intel Xeon (C4 series) for CPU-bound FFmpeg encoding with libass. C4D-highcpu-32 is ~5x faster than C4-standard-8. C4D requires `hyperdisk-balanced` disk type.
|
||||
|
||||
### Deferred Job Creation with Search Sessions (Mar 2026)
|
||||
When a multi-step wizard searches for resources before the user confirms (e.g., audio search in Step 2, job settings in Step 3), don't create the backend resource during the search step. Instead, store a short-lived session (Firestore TTL: 30 min) with the search results, and create the resource only at the final confirm step with all values set correctly. Benefits: no orphan records, no wrong-value patching, no ghost entries in lists, no spurious notifications. The session pattern works well: `search-standalone` returns `search_session_id` + results, `create-from-search` takes `search_session_id` + user choices → creates job with final values. Sessions auto-expire via Firestore TTL; no cleanup needed on back/abandon.
|
||||
|
||||
### Combined Review Flow (Jan 2026)
|
||||
When two sequential human review steps can be combined into one, do it. We originally had separate steps: (1) lyrics review, (2) instrumental selection. This doubled user friction and email notifications. By the time users enter lyrics review, audio separation is already complete - the instrumental stems are ready. We combined both into a single "Combined Review" session: users review lyrics AND select instrumental track on the same page, submit once. **Benefits**: Better UX (one interaction vs two), faster turnaround, reduced drop-off, simpler email notifications, cleaner codebase. **Implementation pattern**: Move analysis that was done after review (backing vocals analysis) to before review (in screens_worker). Include instrumental options in the correction-data endpoint. Require instrumental selection in the review completion request body. Remove the separate `AWAITING_INSTRUMENTAL_SELECTION` state from normal flow (keep for edge cases like finalise-only jobs for DB compatibility).
|
||||
|
||||
@@ -43,17 +30,6 @@ When two sequential human review steps can be combined into one, do it. We origi
|
||||
|
||||
## Common Gotchas
|
||||
|
||||
### Gate Resource Recycling on Full Cleanup Confirmation (Feb 2026)
|
||||
**What happened**: Brand code NOMAD-1271 was recycled and reused for a real song while old E2E test job files still existed in Google Drive, creating a duplicate in the public share.
|
||||
|
||||
**Root causes**:
|
||||
1. `if gdrive_files:` skips cleanup when `gdrive_files = {}` (empty dict is falsy) — any falsy check on a collection will silently skip work
|
||||
2. Brand code recycled after Dropbox cleanup success, *before* confirming GDrive was clean — partial cleanup allowed resource reuse with orphaned files
|
||||
|
||||
**Fix**: Use `if gdrive_files is not None` (or check explicitly). Gate resource recycling on **all** cleanup steps succeeding, not just the first one. When a resource has been distributed to N places, it's only safe to recycle when all N locations are confirmed clean.
|
||||
|
||||
**Pattern**: Treat resource IDs (brand codes, sequential IDs) like distributed transactions — either all distribution points are cleaned, or the ID stays reserved.
|
||||
|
||||
### Fail Fast, Don't Fall Back
|
||||
Silent fallbacks hide configuration errors. When critical configuration is missing (themes, credentials, etc.), raise clear errors instead of falling back to defaults. Better to fail loudly during testing than silently produce incorrect output in production. Example: Theme validation (v0.109.0) now raises `ValueError` on incomplete themes instead of merging with defaults. This ensures all cloud jobs use complete, explicit themes with no silent degradation.
|
||||
|
||||
@@ -82,15 +58,6 @@ When multiple code paths create jobs (file upload, audio search, webhooks), use
|
||||
|
||||
**Pattern**: When a function can fail, prefer exceptions over boolean returns. Silent failures accumulate into production bugs. Use centralized helpers for multi-step operations (state change + side effects) to prevent divergent implementations.
|
||||
|
||||
### Validate Pipeline Stage Outputs Before Proceeding (Feb 2026)
|
||||
**What happened**: Jobs 5b6aba25 and 5161b069 completed with `enable_cdg=True` but no CDG ZIP was produced. The orchestrator silently caught a `FileNotFoundError` during CDG generation and proceeded to 11+ minutes of GPU encoding, distribution, and notifications — all for an incomplete output.
|
||||
|
||||
**Root cause**: CDG generation failed because `instrumental_selection: custom` had no case in the filename construction (fell through to "Backing" suffix). The `FileNotFoundError` was caught by a broad `except Exception` that just logged and continued, since "CDG is optional."
|
||||
|
||||
**Fix**: Add validation gates between pipeline stages. After packaging completes but before expensive encoding begins, verify that all enabled outputs were actually produced. If `enable_cdg=True` but no CDG ZIP exists, raise `RuntimeError` immediately. This fails fast, saves encoding costs, and makes the error visible.
|
||||
|
||||
**Pattern**: When a pipeline stage produces optional outputs that were explicitly requested, validate their existence before proceeding to the next stage. "Optional" means "can be disabled," not "can silently fail when enabled."
|
||||
|
||||
### Fix Both Sides of Dual Code Paths
|
||||
When fixing a bug in a system with multiple code paths (e.g., legacy vs orchestrator, local vs cloud), verify ALL paths are fixed. PR #271 fixed the GCE worker to READ `instrumental_selection` but only checked the legacy path which was already SENDING it. The orchestrator path (production default) wasn't sending it. **Pattern**: If a component receives config from multiple callers, check ALL callers when fixing the receiving side. Write integration tests that cover each path.
|
||||
|
||||
@@ -246,18 +213,6 @@ When deferring processing from one worker to another, you MUST update the job st
|
||||
### Google Drive Query Escaping
|
||||
Escape special chars in Google Drive API queries: `'` → `\'`, `\` → `\\\\`.
|
||||
|
||||
### Google Drive Stale Connection on Cloud Run (Feb 2026)
|
||||
**What happened**: Every GDrive upload silently failed for ~1 month (64 errors, 12+ jobs). Errors: `[Errno 32] Broken pipe` or `[SSL: UNEXPECTED_EOF_WHILE_READING]`. Jobs completed with `gdrive_files: {}` and no alert was sent.
|
||||
|
||||
**Root cause**: The singleton `GoogleDriveService` caches its HTTP connection. When Cloud Run containers sit idle between jobs, the underlying TCP connection goes stale. The next API call hits a dead socket. The orchestrator catches all exceptions in distribution and continues silently.
|
||||
|
||||
**Fix** (v0.119.7):
|
||||
1. Added tenacity retry with `_reset_service()` (sets `self._service = None` to force fresh connection) on transient errors (`BrokenPipeError`, `ConnectionResetError`, `ssl.SSLError`)
|
||||
2. Added `distribution_warnings` field to `OrchestratorResult` to track non-fatal upload failures
|
||||
3. Added Pushbullet notification when distribution uploads fail, so operator is alerted immediately
|
||||
|
||||
**Pattern**: Any singleton service that caches HTTP connections should have retry logic with connection reset for stale connection errors. Cloud Run containers can idle for minutes between requests, killing keep-alive connections. Also, never silently swallow distribution failures - always track and alert on them.
|
||||
|
||||
### FFmpeg Path Escaping
|
||||
For subprocess without shell, FFmpeg filter paths need: apostrophes escaped as `'\\''`, special chars as `\\[char]`.
|
||||
|
||||
@@ -682,9 +637,6 @@ Langfuse v3 is built on OpenTelemetry. If `CallbackHandler()` is created without
|
||||
### Cold Start Mitigation
|
||||
Set `min-instances > 0` for Cloud Run services with heavy initialization.
|
||||
|
||||
### Never Call sync-over-async from FastAPI async Routes (Feb 2026)
|
||||
Sync methods that internally create new event loops (`asyncio.new_event_loop()` + `loop.run_until_complete()`) will **block the FastAPI event loop** when called from `async def` routes or background tasks. The response body gets queued but never flushed because the blocked loop can't process I/O — causing 20-36s endpoint latency instead of <1s. **Fix**: Either (a) call the underlying async client directly with `await` (preferred — e.g., `await flacfetch_client.download_by_id()`), or (b) wrap sync calls in `await asyncio.to_thread()` / `loop.run_in_executor()` to run them in a thread pool. The `nest_asyncio` library is NOT a reliable workaround — it patches CPython internals and can cause deadlocks. See `audio_search.py` and `youtube_download_service.py` for the correct async patterns.
|
||||
|
||||
---
|
||||
|
||||
## Data & Storage
|
||||
@@ -776,17 +728,3 @@ This generalizes the preview encoding pattern (`/encode-preview` was already ide
|
||||
4. **Keep docs minimal and current** - Less documentation, always accurate
|
||||
5. **Check gitignore early for new directories** - Especially frontend `lib/` dirs
|
||||
|
||||
---
|
||||
|
||||
## Incident Insights
|
||||
|
||||
### NOMAD-1276: Validator Timing Race Condition (2026-03-02)
|
||||
|
||||
**Problem:** Post-job GDrive validator fired immediately after upload, before E2E test cleanup could delete test files. Validator saw all 1,276 files (including test files), reported "no issues," then cleanup deleted the test files, leaving NOMAD-1276 as a gap.
|
||||
|
||||
**Key lessons:**
|
||||
1. **Fire-and-forget validation is risky** — When a validator runs alongside cleanup, the order matters. A 5-minute Cloud Tasks delay is a simple, reliable fix.
|
||||
2. **Multi-step UI state can silently lose data** — The guided flow's `is_private` checkbox was in Step 3, but the job was created in Step 2 with the default value. Fixed by decoupling search from job creation: search now returns a session ID, and the job is created only at Step 3 confirm with all final values. See `docs/archive/2026-03-02-decouple-search-from-job-creation.md`.
|
||||
3. **Cloud Run service naming matters for debugging** — The service is `karaoke-backend`, not `karaoke-gen-api`. Wrong name returns empty logs, wasting investigation time.
|
||||
4. **Cross-folder gap detection needs global context** — Per-folder max misses trailing gaps when folders have different highest numbers. Use the global max across all folders as the upper bound.
|
||||
|
||||
@@ -59,12 +59,12 @@ Guidelines for how to communicate about Nomad Karaoke to users, in marketing mat
|
||||
|
||||
---
|
||||
|
||||
## Free Credits
|
||||
## Beta Tester Program
|
||||
|
||||
- All new accounts receive 2 free credits to try the service
|
||||
- No payment required to get started
|
||||
- Credits never expire
|
||||
- Additional credits available for purchase ($5/credit, bulk discounts available)
|
||||
- Beta testers get up to 5 free karaoke video generations
|
||||
- Mandatory feedback required after each video
|
||||
- Must acknowledge they'll review/correct lyrics transcription
|
||||
- Helps improve the system through real-world testing
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
## What Works
|
||||
|
||||
- **Web App**: https://gen.nomadkaraoke.com
|
||||
- `/` - Landing page with pricing
|
||||
- `/` - Landing page with pricing and beta enrollment
|
||||
- `/app` - Main app (upload audio, review lyrics, download videos)
|
||||
- `/admin` - Admin dashboard (user management, job monitoring)
|
||||
- `/admin` - Admin dashboard (user management, job monitoring, beta program)
|
||||
- **Backend API**: https://api.nomadkaraoke.com - FastAPI on Cloud Run
|
||||
- **CLI Tools**: `karaoke-gen` (local), `karaoke-gen-remote` (cloud)
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
| Token-based auth | Working |
|
||||
| Magic link auth | Working |
|
||||
| Payment flow (Stripe) | Working |
|
||||
| Feedback-for-credits | Working (2+ jobs → 2 free credits) |
|
||||
| Beta tester program | Working |
|
||||
| Admin dashboard | Working |
|
||||
| Rate limiting & abuse prevention | Working |
|
||||
| CI/CD self-hosted runner | Working (GCP) |
|
||||
@@ -34,7 +34,7 @@
|
||||
|
||||
## Known Issues
|
||||
|
||||
(No known issues)
|
||||
- CDG format generation requires additional style configuration
|
||||
|
||||
## Pending Work
|
||||
|
||||
@@ -42,16 +42,6 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Feedback-for-Credits** (2026-03-01): Added a feedback-for-credits mechanism available to all users (replaces the old beta-only feedback flow). Users who complete 2+ karaoke videos can submit product feedback (star ratings + text) to earn 2 free credits (total possible free credits: 4 — 2 welcome + 2 feedback). New endpoints: `GET /api/users/feedback/eligibility`, `POST /api/users/feedback`. The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide prompts without an extra API call. Frontend shows a dismissible banner on the dashboard and a "Earn 2 Free Credits" menu item in the user dropdown when eligible. Feedback stored in `user_feedback` Firestore collection with duplicate prevention via `has_submitted_feedback` flag on user model. Welcome email updated with credit-focused messaging and feedback teaser. See [API.md](API.md#user-feedback-for-credits).
|
||||
|
||||
- **Remove Beta Program from Homepage** (2026-03-01): Removed beta enrollment from landing page and replaced with prominent "2 Free Credits" messaging. Beta enrollment endpoint preserved for backward compatibility but no longer actively promoted. See PR #430.
|
||||
|
||||
- **Fix Event Loop Blocking in Audio Search Endpoints** (2026-02-28): Fixed `/api/audio-search/{job_id}/select` taking 20-36s to respond (should be <1s) and `/api/audio-search/search` sometimes taking 25-47s. **Root cause**: Async endpoints called sync methods that create new event loops via `loop.run_until_complete()`, blocking the FastAPI event loop — response body was queued but never flushed. **Fix**: RED/OPS and Spotify download paths now call `FlacfetchClient` async methods directly (matching `YouTubeDownloadService` pattern), generic downloads use `asyncio.to_thread()`, search endpoint uses `search_async()`. Also fixed `InsufficientCreditsError` occasionally returning 500 instead of 402 by using `isinstance()` check. Added 14 new tests. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#never-call-sync-over-async-from-fastapi-async-routes-feb-2026).
|
||||
|
||||
- **GDrive Cleanup Robustness + Brand Code Race Fix** (2026-02-27): Fixed duplicate brand codes appearing in the public Google Drive share after the daily E2E test (NOMAD-1271 appearing for both the test job "piri - dog" and real song "Hot Mulligan - Pop Shuvit"). **Root causes**: (1) `if gdrive_files:` was falsy for empty dict `{}` — when GDrive upload silently failed (pre-PR #417), the entire GDrive cleanup block was skipped, (2) Brand code was recycled immediately after Dropbox cleanup succeeded, without confirming GDrive was also clean — a new job could claim the recycled code while old GDrive files still existed. **Fixes**: Added `find_files_by_brand_code()` fallback to `GoogleDriveService` that searches CDG/MP4/MP4-720p subfolders by brand code prefix when tracked file IDs aren't available. `cleanup-distribution` endpoint now: (a) uses tracked file IDs (fast path) or falls back to brand_code search, (b) only recycles the brand code after **both** Dropbox AND GDrive are confirmed clean. Added `scripts/cleanup_test_job_gdrive.py` remediation script. Added 14 new tests (94% coverage on gdrive_service.py).
|
||||
|
||||
- **CDG Packaging Fail-Fast Validation** (2026-02-27): Fixed silent CDG generation failures where jobs completed with `enable_cdg=True` but no CDG ZIP was produced. **Root cause**: Jobs 5b6aba25 and 5161b069 had `instrumental_selection: custom` but before commit b671b83f, the orchestrator had no `custom` case — it fell through to `"Backing"` suffix. The CDG generator then hit a `FileNotFoundError` looking for the wrong filename, which was silently caught. **Fix**: (1) Orchestrator now validates CDG/TXT outputs after packaging stage and before encoding — if `enable_cdg=True` but no CDG ZIP was produced, the pipeline fails fast instead of silently continuing to expensive encoding, (2) Missing LRC file now raises when CDG/TXT is enabled instead of silently skipping, (3) Added `scripts/regenerate_cdg.py` remediation script for affected jobs. Removed "CDG requires additional style configuration" known issue (the nomad theme has complete CDG styles). Added 7 new tests for validation logic.
|
||||
|
||||
- **GCE Encoding Pipeline Resilience** (2026-02-26): Made encoding pipeline resilient to Cloud Run deployment interruptions. A deployment killed a poller mid-encoding, leaving job a03ad39c permanently stuck at `encoding` status. Three fixes: (1) GCE worker `/encode` endpoint now idempotent — returns cached results for completed jobs, allows retry on failure, returns status for in-progress (previously hard 409 reject), (2) `encoding_service.py` handles cached/in_progress responses and falls back to status check on 409, (3) Health service detects jobs stuck in `encoding` >50 min. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#resilient-remote-worker-interactions-feb-2026).
|
||||
|
||||
- **Private (Non-Published) Tracks** (2026-02-24): Added `is_private` flag on jobs for private/non-published track production. Private jobs upload to Dropbox `Tracks-NonPublished` folder with `NOMADNP` brand prefix, skip YouTube and Google Drive entirely, and send completion emails without the YouTube section. Available as a checkbox on all job creation tabs and as an admin toggle (auto-deletes outputs when toggling a completed job to private). See [archive/2026-02-24-private-tracks-plan.md](archive/2026-02-24-private-tracks-plan.md).
|
||||
|
||||
@@ -33,28 +33,6 @@ curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
|
||||
|
||||
---
|
||||
|
||||
## CDG/TXT packages missing from completed job
|
||||
|
||||
**Cause:** Before v0.119.7, CDG/TXT generation failures were silently caught. Jobs would complete with `enable_cdg=True` but no CDG ZIP in outputs. Fixed in v0.119.7 with fail-fast validation — new jobs will now fail loudly if CDG/TXT generation fails.
|
||||
|
||||
**Recovery** (for jobs that already completed without CDG/TXT):
|
||||
|
||||
```bash
|
||||
# Regenerate and distribute CDG/TXT packages for specific jobs
|
||||
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
|
||||
python -m scripts.regenerate_cdg JOB_ID [JOB_ID ...]
|
||||
|
||||
# Example:
|
||||
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
|
||||
python -m scripts.regenerate_cdg 5b6aba25 5161b069
|
||||
```
|
||||
|
||||
The script is idempotent — re-running it skips regeneration if the CDG ZIP already exists in GCS and proceeds to any missing distribution steps (GDrive, Dropbox).
|
||||
|
||||
---
|
||||
|
||||
## GCE encoding worker on wrong wheel version
|
||||
|
||||
**Cause:** Worker picks up a new deploy but doesn't restart automatically.
|
||||
@@ -68,27 +46,3 @@ gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Google Drive uploads missing (gdrive_files empty)
|
||||
|
||||
**Symptoms:** Jobs complete successfully but `state_data.gdrive_files` is empty `{}`. Cloud Run logs show `BrokenPipeError` or `SSL: UNEXPECTED_EOF_WHILE_READING`.
|
||||
|
||||
**Cause:** Stale HTTP connections in the singleton `GoogleDriveService`. Since v0.119.7, this is handled automatically with retry + connection reset.
|
||||
|
||||
**Backfill affected jobs:**
|
||||
```bash
|
||||
# Dry run - list affected jobs
|
||||
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
|
||||
python scripts/backfill_gdrive_uploads.py --all-missing --dry-run
|
||||
|
||||
# Run for real
|
||||
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
|
||||
python scripts/backfill_gdrive_uploads.py --all-missing
|
||||
|
||||
# Specific jobs
|
||||
python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
|
||||
```
|
||||
@@ -1,109 +0,0 @@
|
||||
# GDrive Validator: Email Alerts, Manual Trigger, Post-Job Check
|
||||
|
||||
## Context
|
||||
|
||||
The GDrive validator cloud function checks the public Google Drive share for duplicate brand codes, invalid filenames, and sequence gaps. Currently it:
|
||||
- Runs once daily at 9 PM Eastern via Cloud Scheduler
|
||||
- Sends results via Pushbullet (easy to miss, no persistent record)
|
||||
- Cannot be easily triggered manually
|
||||
- Doesn't run after each job, so issues can persist for up to 24 hours before detection
|
||||
|
||||
The recent NOMAD-1271 duplicate brand code incident showed that daily checks aren't frequent enough — the duplicate existed for at least a day before manual discovery.
|
||||
|
||||
## Changes
|
||||
|
||||
### 1. Cloud Function: Replace Pushbullet with Email (SendGrid)
|
||||
|
||||
**File:** `infrastructure/functions/gdrive_validator/main.py`
|
||||
|
||||
- Replace `send_pushbullet_notification()` with `send_email_notification()` using SendGrid API
|
||||
- SendGrid API key already in Secret Manager as `sendgrid-api-key`
|
||||
- Send from `gen@nomadkaraoke.com` to `gen@nomadkaraoke.com`
|
||||
- Keep Pushbullet as a secondary fallback (both are cheap; belt + suspenders)
|
||||
- Add `SENDGRID_API_KEY` env var to the function
|
||||
|
||||
**File:** `infrastructure/functions/gdrive_validator/requirements.txt`
|
||||
|
||||
- Add `sendgrid>=6.0.0`
|
||||
|
||||
**File:** `infrastructure/__main__.py`
|
||||
|
||||
- Add `sendgrid-api-key` secret to the function's `secret_environment_variables`
|
||||
- Add `EMAIL_TO` env var = `gen@nomadkaraoke.com`
|
||||
|
||||
**File:** `infrastructure/functions/gdrive_validator/deploy.sh`
|
||||
|
||||
- Add `--set-secrets` entry for `SENDGRID_API_KEY=sendgrid-api-key:latest`
|
||||
- Add `--set-env-vars` entry for `EMAIL_TO=gen@nomadkaraoke.com`
|
||||
|
||||
### 2. Local Command: `check_public_share`
|
||||
|
||||
**File:** `scripts/check_public_share.py`
|
||||
|
||||
- Calls the Cloud Function via `gcloud functions call gdrive-validator --region=us-central1`
|
||||
- Parses the JSON response and prints formatted results to terminal
|
||||
- Exit code 0 = all clear, 1 = issues found, 2 = error
|
||||
- Supports `--json` flag for raw JSON output
|
||||
|
||||
### 3. Post-Job Trigger from Backend
|
||||
|
||||
**File:** `backend/services/gdrive_validator_client.py` (new)
|
||||
|
||||
- Lightweight client that calls the Cloud Function via HTTP with OIDC token
|
||||
- Uses `google.oauth2.id_token.fetch_id_token()` for authentication
|
||||
- Fire-and-forget pattern (never blocks or fails the job)
|
||||
- Logs the response but does not raise on validation issues (just notifies)
|
||||
|
||||
**File:** `backend/workers/video_worker_orchestrator.py`
|
||||
|
||||
- After `_run_notifications()` (line ~253), add a new call: `await self._trigger_gdrive_validation()`
|
||||
- Only triggers for non-private, non-test jobs (private jobs don't upload to public share)
|
||||
- Wrapped in try/except so validation failure never blocks job completion
|
||||
|
||||
**File:** `infrastructure/__main__.py`
|
||||
|
||||
- Add IAM binding: grant `karaoke-backend` service account `roles/cloudfunctions.invoker` on the gdrive-validator function
|
||||
- For Gen2 functions also need `roles/run.invoker` on the underlying Cloud Run service
|
||||
|
||||
**File:** `infrastructure/modules/iam/backend_sa.py`
|
||||
|
||||
- Add the Cloud Functions invoker permission
|
||||
|
||||
### 4. Pulumi Infrastructure Updates
|
||||
|
||||
All IAM and secret changes go through `infrastructure/__main__.py` — deployed automatically on merge to main.
|
||||
|
||||
## Comparison: Local Script vs Cloud Function
|
||||
|
||||
| Check | Local Script | Cloud Function |
|
||||
|-------|-------------|----------------|
|
||||
| Duplicate sequence numbers | ✅ | ✅ |
|
||||
| Invalid filenames | ✅ | ✅ |
|
||||
| Sequence gaps (with known gaps) | ✅ | ✅ |
|
||||
| Known gaps config | ✅ (identical) | ✅ (identical) |
|
||||
| ZIP contents (MP3+CDG) | ✅ | ❌ (expensive, needs file download) |
|
||||
| Video resolution (4K/720p) | ✅ | ❌ (expensive, needs file download) |
|
||||
| Render quality (pixel check) | ✅ | ❌ (expensive, needs ffmpeg) |
|
||||
| Bidirectional sync | ✅ (rclone) | ❌ (read-only) |
|
||||
|
||||
The cloud function correctly implements the "quick/cheap" checks (metadata-only via GDrive API). The expensive content checks (ZIP, resolution, pixel) belong in the local script since they require downloading files. No changes needed to align them.
|
||||
|
||||
## Files Modified
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `infrastructure/functions/gdrive_validator/main.py` | Add SendGrid email, keep Pushbullet as fallback |
|
||||
| `infrastructure/functions/gdrive_validator/requirements.txt` | Add `sendgrid` |
|
||||
| `infrastructure/functions/gdrive_validator/deploy.sh` | Add SendGrid secret + EMAIL_TO env var |
|
||||
| `infrastructure/__main__.py` | Add SendGrid secret to function, add backend invoker IAM |
|
||||
| `backend/services/gdrive_validator_client.py` | New: HTTP client to invoke cloud function |
|
||||
| `backend/workers/video_worker_orchestrator.py` | Add post-distribution GDrive validation trigger |
|
||||
| `scripts/check_public_share.py` | New: local command to trigger cloud function |
|
||||
|
||||
## Verification
|
||||
|
||||
1. Deploy cloud function with `./deploy.sh`
|
||||
2. Run `python scripts/check_public_share.py` — should print formatted results and receive email at gen@nomadkaraoke.com
|
||||
3. Trigger a test job or wait for the daily E2E test — after job completes, check Cloud Function logs to confirm it was invoked
|
||||
4. Check gen@nomadkaraoke.com inbox for the validation email
|
||||
5. Run `make test` to verify no regressions
|
||||
@@ -1,75 +0,0 @@
|
||||
# UX Overhaul - Master Plan
|
||||
|
||||
> **Status**: Phases 1-3 complete, Phase 4 remaining
|
||||
> **Created**: 2026-02-28
|
||||
> **Branch**: feat/sess-20260227-1637-ux-overhaul
|
||||
> **Worktree**: /Users/andrew/Projects/nomadkaraoke/karaoke-gen-ux-overhaul
|
||||
|
||||
## Overview
|
||||
|
||||
The karaoke generation platform was built for personal/power-user use. New users lack guidance at each stage of the multi-step process. This UX overhaul will improve guidance, simplify choices, and steer users toward the best outcomes.
|
||||
|
||||
## Phased Approach
|
||||
|
||||
The system has several distinct stages of human interaction, each requiring dedicated UX thought. We're breaking this into phases, with a detailed plan for each phase created through live UI walkthrough with screenshots and user feedback.
|
||||
|
||||
### Phase 1: Job Creation & Audio Input ✅
|
||||
**Plan**: [2026-02-28-ux-phase1-job-creation.md](2026-02-28-ux-phase1-job-creation.md)
|
||||
**Implementation**: [2026-02-28-ux-phase1-implementation.md](2026-02-28-ux-phase1-implementation.md)
|
||||
**Scope**: Restructure the job creation form as a guided flow. Steer users toward Search as the default path, with Upload/URL as fallbacks.
|
||||
**Done**: Removed "Skip lyrics review" checkbox, renamed Private label, built 3-step GuidedJobFlow wizard, title card preview, production E2E tests. Renamed "Find Audio" → "Choose Audio".
|
||||
|
||||
### Phase 2: Audio Source Selection ✅
|
||||
**Plan**: [2026-02-28-ux-phase2-audio-selection.md](2026-02-28-ux-phase2-audio-selection.md)
|
||||
**Scope**: Auto-select audio for simple cases, improve guidance for complex cases, build heuristics from real usage data.
|
||||
**Done**: 3-tier confidence system (perfect match / recommended / limited sources), guidance-first layout for Tier 3, validated against 41 production fixtures with unit tests.
|
||||
|
||||
### Phase 3: Lyrics Review ✅
|
||||
**Plan**: [2026-02-28-ux-phase3-lyrics-review.md](2026-02-28-ux-phase3-lyrics-review.md)
|
||||
**Scope**: Add onboarding, explain color coding, guide users through the correction workflow. This is the most complex screen.
|
||||
**Done**: Guidance panel replacing stats bar (collapsible, color coding legend, workflow tips), gap navigator with keyboard shortcuts (J/K), simplified toolbar with Advanced Mode toggle, hidden line numbers/delete icons by default, edit tracking system with low-friction feedback bar for transcription improvement data collection. 40 tests.
|
||||
|
||||
### Phase 4: Instrumental Review ← REMAINING
|
||||
**Plan**: [2026-02-28-ux-phase4-instrumental-review.md](2026-02-28-ux-phase4-instrumental-review.md)
|
||||
**Scope**: Explain what backing vocals are, guide the listen/decide flow, simplify the default case.
|
||||
|
||||
## Cross-Cutting Concerns
|
||||
|
||||
- **Remove "Skip lyrics review" checkbox** from UI (keep backend field for API/admin use)
|
||||
- **Rename "Private (non-published)"** to something clearer like "Private (no YouTube upload)"
|
||||
- **Auto-select heuristics training** - Pull last ~50 jobs, capture what audio the user would choose and why, codify into algorithm (may be a separate workstream touching flacfetch)
|
||||
|
||||
## Screenshots Captured
|
||||
|
||||
All screenshots saved in the worktree root during the walkthrough session:
|
||||
|
||||
### Phase 1: Job Creation
|
||||
- `phase1-job-creation-current.png` - Current job creation form
|
||||
- `phase1-filled-form.png` - Form filled with Coldplay - Parachutes
|
||||
- `phase1-job-created-awaiting-audio.png` - Job created, awaiting audio selection
|
||||
|
||||
### Phase 2: Audio Source Selection
|
||||
- `phase2-audio-search-results.png` - Audio search results dialog (Coldplay, top)
|
||||
- `phase2-audio-search-bottom.png` - Audio search results dialog (Coldplay, bottom)
|
||||
- `phase2-pony-bradshaw-results.png` - Audio search results for obscure track (Pony Bradshaw)
|
||||
|
||||
### Phase 3: Lyrics Review (Difficulty Spectrum)
|
||||
- `phase3-lyrics-review.png` / `phase3-lyrics-review-top.png` - Bon Jovi lyrics review (easy-medium, 94% anchored)
|
||||
- `phase3-lyrics-review-bottom.png` - Bon Jovi lyrics review (bottom/end of lyrics)
|
||||
- `phase3-bon-jovi-review.png` - Bon Jovi "It's My Life" (easy-medium: 94% anchored, 9 gaps, 18 words)
|
||||
- `phase3-silversun-pickups-review.png` - Silversun Pickups (medium: 84% anchored, 8 gaps, 32 words)
|
||||
- `phase3-steve-taylor-review.png` - Steve Taylor live (hard: 42% anchored, 20 gaps, 194 words, wrong reference lyrics)
|
||||
- `phase3-preview-dialog.png` - Preview Video dialog (transition from lyrics to instrumental review)
|
||||
|
||||
### Phase 4: Instrumental Review
|
||||
- `phase4-instrumental-review.png` - Instrumental review page (Coldplay - Parachutes, 4% backing vocals, Clean recommended)
|
||||
|
||||
## Test Jobs Used
|
||||
|
||||
| Track | ID | Difficulty | Stage |
|
||||
|-------|-----|-----------|-------|
|
||||
| Coldplay - Parachutes | a95023e8 | Easy | Progressed to instrumental review |
|
||||
| Bon Jovi - It's My Life | c235f6bd | Easy-Medium | At lyrics review |
|
||||
| Silversun Pickups - Well Thought Out Twinkles | 41026cfe | Medium | At lyrics review |
|
||||
| Pony Bradshaw - Jehovah | 3552d63d | Medium | At lyrics review |
|
||||
| Steve Taylor - Jim Morrisons Grave - Live | ce8f2901 | Hard | At lyrics review |
|
||||
@@ -1,58 +0,0 @@
|
||||
# Phase 1: Job Creation UX Overhaul - Implementation Record
|
||||
|
||||
Date: 2026-02-28
|
||||
|
||||
## What Was Done
|
||||
|
||||
### Increment 1: Quick Wins
|
||||
- Removed "Skip lyrics review (non-interactive)" checkbox from all 3 tabs in `JobSubmission.tsx`
|
||||
- Renamed "Private (non-published)" to "Private (no YouTube upload)" across all 3 tabs
|
||||
- Removed `nonInteractive` state variable and `non_interactive` from all submit handler payloads
|
||||
- Backend `non_interactive` field preserved for CLI/admin API use
|
||||
|
||||
### Increment 2: Guided Step Flow
|
||||
Replaced the tab-based `JobSubmission` with a new `GuidedJobFlow` wizard component.
|
||||
|
||||
#### New Files Created
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `lib/audio-search-utils.ts` | Extracted categorization logic shared between AudioSearchDialog and new flow |
|
||||
| `components/job/GuidedJobFlow.tsx` | Main orchestrator with step state management |
|
||||
| `components/job/steps/SongInfoStep.tsx` | Step 1: Artist & Title input |
|
||||
| `components/job/steps/AudioSourceStep.tsx` | Step 2: Auto-search + fallback upload/URL |
|
||||
| `components/job/steps/CustomizeStep.tsx` | Step 3: Title card preview + options |
|
||||
| `components/job/steps/ConfirmStep.tsx` | Step 4: Review & confirm |
|
||||
| `components/job/TitleCardPreview.tsx` | CSS mockup of title/end screens |
|
||||
|
||||
#### Modified Files
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `components/job/JobSubmission.tsx` | Quick wins only (kept as reference) |
|
||||
| `components/audio-search/AudioSearchDialog.tsx` | Refactored to import from shared utils |
|
||||
| `app/app/page.tsx` | Swapped JobSubmission for GuidedJobFlow |
|
||||
|
||||
### Architecture Decisions
|
||||
|
||||
1. **Display overrides in Step 1**: The `searchAudio` API sets display_artist/display_title at creation time (not updateable after). So the display override toggle stays in Step 1 as a collapsible section, before the search is triggered.
|
||||
|
||||
2. **Privacy setting timing**: For search path, `is_private` is set during the `searchAudio` call in Step 2. Step 3 (Customize) shows the current value but changes there would need a backend `updateJob` call (which supports `is_private`). For upload/URL fallback paths, `is_private` is set at creation time.
|
||||
|
||||
3. **Upload/URL skip customize**: When users choose upload or URL fallback in Step 2, they skip directly to Step 4 (Confirm) since the title card preview is less relevant for these paths.
|
||||
|
||||
4. **Search polling**: AudioSourceStep polls `getAudioSearchResults` every 2 seconds (max 30 attempts = 60s) while waiting for the backend search to complete.
|
||||
|
||||
5. **Error handling**: Backend errors during search show the error message and immediately offer fallback options (Upload file / YouTube URL).
|
||||
|
||||
## Visual Testing Results
|
||||
|
||||
Screenshots saved in `docs/images/`:
|
||||
- `phase1-step1-initial.png` - Empty step 1 form
|
||||
- `phase1-step1-filled.png` - Form with "Queen - Bohemian Rhapsody"
|
||||
- `phase1-step1-display-override.png` - Display override section expanded
|
||||
- `phase1-step2-searching.png` - Search loading state with spinner
|
||||
- `phase1-step2-error-with-fallbacks.png` - Error handling with fallback options
|
||||
|
||||
## Test Results
|
||||
- All 323 Jest tests pass
|
||||
- Next.js build succeeds with no errors
|
||||
- Visual testing confirms all Step 1 and Step 2 UI renders correctly
|
||||
@@ -1,93 +0,0 @@
|
||||
# Phase 1: Job Creation & Audio Input - UX Plan
|
||||
|
||||
> **Status**: Feedback captured, ready for detailed design
|
||||
> **Screenshots**: `phase1-job-creation-current.png`, `phase1-filled-form.png`
|
||||
|
||||
## Current State
|
||||
|
||||
The job creation form at `/app` has:
|
||||
- **Three equal tabs**: Search / Upload / URL - no indication which is preferred or when to use each
|
||||
- **"Search For Audio Online"** heading with Artist/Title fields
|
||||
- **Note**: "Format these exactly as you want them on the title card and video filename" - confusing for users who don't know what "title card" means
|
||||
- **"Use different artist/title for title screen"** - collapsible, but unclear what it does
|
||||
- **"Skip lyrics review (non-interactive)"** - admin-only but visible, confusing
|
||||
- **"Private (non-published)"** - useful but wording is unclear
|
||||
- **"Search & Create Job"** button - creates job AND searches, then user must find the job in Recent Jobs and click "Select Audio" separately (split interaction)
|
||||
|
||||
## User Feedback
|
||||
|
||||
### Search should be strongly preferred
|
||||
> "We need to strongly steer users towards trying Search first as it provides high quality lossless audio which makes for a better karaoke track. Ideally they should only use Upload for tracks which aren't commercially/generally available online, and they should only use YouTube if the specific version they want a karaoke track for doesn't come up in the Search results (e.g. if it's a bootleg or specific live version or something indie which is only on YouTube)"
|
||||
|
||||
### Title card note is confusing
|
||||
> "Honestly I'd imagine this is kinda confusing to new users who may not even know what 'title screen' means."
|
||||
|
||||
### Restructure as guided flow
|
||||
> "I'm now wondering if it would be better to restructure it as a series of questions which leads the user to the job creation. That way we could give the user clearer guidance for each step and make the order make sense (e.g. do the audio search first, only fall back to youtube/upload if they couldn't find the exact version in the search results). If we did that the question about whether there should be a different artist/title for the title card could be answered as a separate question in this flow, with a dynamically generated preview image showing roughly what the title card would look like to help the user understand what it is."
|
||||
|
||||
### Remove "Skip lyrics review"
|
||||
> "Honestly I can't even remember why I added 'Skip lyrics review' as an option, we should probably remove that as I don't really think there's ever a legit reason for anyone to use that."
|
||||
|
||||
**Investigation result**: Added Dec 25, 2025 as CLI `-y` equivalent, refined to admin-only per-job option Jan 3, 2026 (PR #162). It's an admin/testing power tool that auto-completes review stages. The backend `non_interactive` field should stay for API/admin use, but the checkbox should be removed from the job creation form.
|
||||
|
||||
### Rename "Private" option
|
||||
> "The 'Private' option is definitely useful and important, we can probably make it even easier to understand by changing '(non-published)' to '(no public upload on YouTube)' or something"
|
||||
|
||||
## Proposed Design: Guided Step Flow
|
||||
|
||||
Replace the current tab-based form with a step-by-step guided flow:
|
||||
|
||||
### Step 1: "What song do you want to make a karaoke track for?"
|
||||
- Artist & Title fields (simple, friendly)
|
||||
- This is the same regardless of input method
|
||||
|
||||
### Step 2: "Find the audio"
|
||||
- Auto-search runs immediately with the artist/title from Step 1
|
||||
- Results appear inline (not in a separate modal after job creation)
|
||||
- "Best Choice" is prominently recommended (or auto-selected - see Phase 2)
|
||||
- If nothing found or wrong version: "Can't find it? Try a YouTube URL or upload your own audio file"
|
||||
- Upload and URL become **fallback options**, not equal peers
|
||||
|
||||
### Step 3: "How should it look?"
|
||||
- Title card preview (dynamically rendered) showing roughly what the title/end screens will look like
|
||||
- Option to override artist/title for display
|
||||
- Private toggle with clearer label: "Private (no YouTube upload)"
|
||||
- This step gives context for what "title card" actually means
|
||||
|
||||
### Step 4: Confirm & Create
|
||||
|
||||
## Key Technical Considerations
|
||||
|
||||
### Current flow (split interaction):
|
||||
```
|
||||
Form → "Search & Create Job" → Job created in backend → Job appears in Recent Jobs list
|
||||
→ User clicks "Select Audio" on job card → Modal dialog opens → User picks result → Job progresses
|
||||
```
|
||||
|
||||
### Proposed flow (unified):
|
||||
```
|
||||
Step 1 (artist/title) → Step 2 (search results inline, or fallback to upload/URL)
|
||||
→ Step 3 (title card preview, private toggle) → Step 4 (confirm) → Job created & processing
|
||||
```
|
||||
|
||||
The key complexity: currently the backend creates the job when the search is initiated. The guided flow might need to either:
|
||||
1. Still create the job early but hide that from the user (keep current backend flow, change frontend presentation)
|
||||
2. Defer job creation until the user confirms everything (would require backend changes)
|
||||
|
||||
Option 1 is probably simpler and lower-risk.
|
||||
|
||||
### Components affected:
|
||||
- `frontend/components/job/JobSubmission.tsx` - Main form (3 tab state objects, submit handlers)
|
||||
- `frontend/components/audio-search/AudioSearchDialog.tsx` - Currently a modal, would become inline
|
||||
- `frontend/components/job/JobCard.tsx` - Currently shows "Select Audio" button for awaiting jobs
|
||||
- `frontend/app/app/page.tsx` - Main dashboard layout (2-column: form + recent jobs)
|
||||
- `frontend/lib/api.ts` - `searchAudio()`, `getAudioSearchResults()`, `selectAudioResult()`
|
||||
|
||||
## Changes to Ship
|
||||
|
||||
1. **Remove "Skip lyrics review" checkbox** from all 3 tabs in JobSubmission.tsx (lines 325-348, 447-470, 607-630). Keep backend `non_interactive` field.
|
||||
2. **Rename "Private (non-published)"** to "Private (no YouTube upload)" or similar
|
||||
3. **Restructure form** as guided step flow (major change - needs detailed component design)
|
||||
4. **Title card preview** - dynamically generated preview showing what title screen looks like
|
||||
5. **Inline audio search results** - move from modal dialog to inline step in guided flow
|
||||
6. **Fallback positioning** - Upload/URL presented as fallbacks when Search doesn't find the right track
|
||||
@@ -1,136 +0,0 @@
|
||||
# Phase 2: Audio Source Selection - UX Plan
|
||||
|
||||
> **Status**: Implemented and verified with 41 production fixtures
|
||||
> **Screenshots**: `phase2-audio-search-results.png`, `phase2-audio-search-bottom.png`, `phase2-pony-bradshaw-results.png`
|
||||
|
||||
## Implementation Summary (2026-02-28)
|
||||
|
||||
### 3-Tier Confidence System
|
||||
Built in `frontend/lib/audio-search-utils.ts` and `frontend/components/job/steps/AudioSourceStep.tsx`:
|
||||
|
||||
- **Tier 1 ("Perfect match found")**: Green card, best result is lossless with 50+ seeders and no filename mismatch
|
||||
- **Tier 2 ("Recommended")**: Amber card with reasoning — has lossless options but not clearly ideal
|
||||
- **Tier 3 ("Limited sources found")**: Guidance-first layout — upload/URL fallback shown above search results
|
||||
|
||||
### Key Features
|
||||
- **Filename mismatch detection**: Compares search title against `target_file` (torrent/Spotify) or `title` (YouTube). Handles underscores as word separators, skips non-Latin scripts gracefully. Shows "Title match" / "Wrong track?" badges.
|
||||
- **Spotify separated from YouTube**: Own category with green styling, higher priority than YouTube in best-result selection
|
||||
- **Dynamic guidance tips**: The "Limited sources found" box only shows tips relevant to the actual result types found
|
||||
- **Color-coded view counts**: Green (1M+), amber (100K+), neutral for YouTube/Spotify results
|
||||
- **Availability tooltips**: User-friendly language ("may take a bit more time to prepare")
|
||||
|
||||
### Testing
|
||||
- 75 unit tests for `audio-search-utils.ts` (96%+ coverage)
|
||||
- 47 fixture confidence tests against 41 production search results
|
||||
- Fixture review tooling: `npm run fixtures:review-ui` for visual verification
|
||||
- E2E regression tests (25 tests) and production E2E tests (7 tests)
|
||||
|
||||
## Current State
|
||||
|
||||
The "Select Audio Source" modal dialog shows:
|
||||
- **Title**: "Select Audio Source v0.119.8 (N results across M categories)"
|
||||
- **Categories** (up to 9): BEST CHOICE, HI-RES 24-BIT, STUDIO ALBUMS, SINGLES, LIVE VERSIONS, COMPILATIONS, VINYL RIPS, YOUTUBE/LOSSY, OTHER
|
||||
- Each result shows: index number, quality badges (LOSSLESS, VINYL, YouTube), artist, title, format details, file size, availability badge (High/Medium/Low color-coded), album metadata, target filename
|
||||
- Each category shows 2-3 results by default with "+N more" expand button
|
||||
- Each result has a "Select" button
|
||||
|
||||
## Problems Identified
|
||||
|
||||
### Too much information / too much choice
|
||||
> "It's just too much information and probably too much choice for most users who just know what song they want a karaoke version of."
|
||||
|
||||
### Wrong songs appear in results
|
||||
- Coldplay "Parachutes" search returned "Everything's Not Lost", "High Speed", "Spies" (other songs from the same album or artist)
|
||||
- Pony Bradshaw "Jehovah" search returned "Van Gogh", "Josephine" (other songs by same artist)
|
||||
- The compilation results (#27, #28 for Coldplay) showed filename "Parachutes/03 - Spies.flac" - a different track entirely
|
||||
- Users need domain knowledge to evaluate these
|
||||
|
||||
### Availability badges unexplained
|
||||
- High (green), Medium (yellow/orange), Low (red) availability badges are shown but never explained
|
||||
- Users don't know that availability directly affects download success rate
|
||||
|
||||
### No guidance on what matters for karaoke
|
||||
- 24-bit vs 16-bit doesn't matter much for karaoke (vocals get removed anyway)
|
||||
- Vinyl rips may have surface noise that affects separation quality
|
||||
- Availability matters more than bit depth for reliability
|
||||
- Live versions will sound different from studio versions
|
||||
|
||||
## User Feedback
|
||||
|
||||
### Auto-select for simple cases
|
||||
> "For those simple/standard users who are making karaoke tracks which have commercially available releases which are easy to download (like this Coldplay example), we should probably just make the choice for the user and only show them this more complex set of alternate options if they explicitly click something to show more advanced options."
|
||||
|
||||
### Better guidance for advanced view
|
||||
> "There's also several gotchas which aren't communicated on this view at all, e.g. the fact that vinyl versions, live versions, or other songs entirely may show up (you have to check the filename makes sense for the song you wanted) so even if we keep this view as an 'advanced' or 'show more options' view in the UX rework, we should add better guidance to it to help users know what to look for."
|
||||
|
||||
### Obscure tracks are trickier
|
||||
For Pony Bradshaw - Jehovah (less popular track):
|
||||
- No "BEST CHOICE" section appeared
|
||||
- Only 3 categories: HI-RES 24-BIT (1, Low availability), STUDIO ALBUMS (4, Medium/Low), YOUTUBE/LOSSY (5)
|
||||
- User's choice: Studio Album #1 (Medium availability, 16bit CD) because "it's the most available (and thus will download the fastest) and 24bit input audio is overkill for karaoke"
|
||||
|
||||
### Build auto-select heuristics from real data
|
||||
> "In order to make the system reliably make a good default choice for the user, we probably ought to run searches for a bunch of input tracks with a variety of popularities (we could just look at the last 50 tracks I've actually made through this karaoke generator as they're already a pretty diverse mix) and for every track, capture what audio I would choose in this 'Select Audio Source' modal AND WHY, then use that reasoning information to build a system which auto-chooses for the user."
|
||||
|
||||
## Proposed Design
|
||||
|
||||
### Tier 1: Auto-Select (Simple Cases)
|
||||
When there's a clear winner (BEST CHOICE category with High availability):
|
||||
- **Auto-select it** and show the user a simple confirmation:
|
||||
- "We found a high-quality lossless version of this track from [Album / Year / Label]"
|
||||
- Small "See all options" or "Choose a different version" link for power users
|
||||
- This covers the majority of popular/commercially available tracks
|
||||
|
||||
### Tier 2: Recommended Pick (Medium Confidence)
|
||||
When there's no BEST CHOICE but there are reasonable lossless options:
|
||||
- **Highlight the recommended pick** with clear reasoning: "Recommended: Studio album version with reliable availability"
|
||||
- Show the recommendation prominently, with other options below in a collapsed "Other options" section
|
||||
- Add brief explanation of why this was chosen
|
||||
|
||||
### Tier 3: Manual Selection Required (Low Confidence)
|
||||
When results are very limited, all low availability, or no lossless options:
|
||||
- Show all results with guidance
|
||||
- Add contextual tips at the top:
|
||||
- "Check the filename matches your song title"
|
||||
- "Higher availability = more reliable download"
|
||||
- "Studio album versions typically produce the best karaoke results"
|
||||
- "Vinyl rips may have surface noise"
|
||||
- "YouTube is lower quality but works for rare/live tracks"
|
||||
|
||||
### Advanced View (Always Accessible)
|
||||
Keep the current full category view as an "Advanced options" panel:
|
||||
- Add guidance header explaining the gotchas
|
||||
- Add tooltips on availability badges explaining what they mean
|
||||
- Flag potentially wrong tracks (filename doesn't match search title)
|
||||
- Consider dimming or warning on results where the filename suggests a different song
|
||||
|
||||
## Auto-Select Heuristics Training Plan
|
||||
|
||||
### Data Collection
|
||||
1. Pull the last ~50 completed jobs from Firestore
|
||||
2. For each job that went through audio search:
|
||||
- Retrieve the cached search results (what options were available)
|
||||
- Record which result index was selected
|
||||
- Have the user annotate WHY that choice was made
|
||||
3. Categorize by popularity/availability patterns
|
||||
|
||||
### Heuristic Rules to Codify
|
||||
Based on walkthrough observations:
|
||||
1. **Availability > bit depth** for karaoke (failed download = start over, 24-bit is wasted)
|
||||
2. **Filename must match song title** (compilation results often have wrong tracks)
|
||||
3. **Prefer studio albums** over compilations, vinyl rips, live versions
|
||||
4. **Avoid vinyl rips** for karaoke (surface noise affects vocal separation)
|
||||
5. **YouTube/lossy is last resort** (lower quality, may be different arrangements)
|
||||
6. **When in doubt, pick highest availability** among lossless results
|
||||
|
||||
### Implementation
|
||||
- Could live in flacfetch's ranking logic (already has some of this)
|
||||
- Or as a frontend/backend layer that post-processes flacfetch results
|
||||
- Should be testable: given a set of search results, predict the correct selection
|
||||
|
||||
## Components Affected
|
||||
|
||||
- `frontend/components/audio-search/AudioSearchDialog.tsx` - Major refactor to add tiers
|
||||
- `frontend/lib/api.ts` - May need new endpoint or parameter for auto-select
|
||||
- Possibly `flacfetch` ranking algorithm (separate repo/workstream)
|
||||
- Backend may need a "confidence score" or "recommended index" in search results response
|
||||
@@ -1,185 +0,0 @@
|
||||
# Phase 3: Lyrics Review - UX Plan
|
||||
|
||||
> **Status**: Implemented
|
||||
> **Screenshots**: `phase3-lyrics-review-top.png`, `phase3-lyrics-review-bottom.png`
|
||||
|
||||
## Implementation Summary (2026-03-01)
|
||||
|
||||
### Guidance Panel (replaces stats bar)
|
||||
- `GuidancePanel.tsx` — collapsible panel with color coding legend, workflow tips
|
||||
- Stats hidden behind toggle (previously always visible, overwhelming for new users)
|
||||
- Contextual tips for common correction types (phantom words, mis-heard words, etc.)
|
||||
|
||||
### Gap Navigator
|
||||
- `GapNavigator.tsx` — "Gap 3 of 9" with prev/next buttons
|
||||
- Keyboard shortcuts: J (next gap), K (previous gap)
|
||||
- Auto-scrolls to gap and flashes the relevant words
|
||||
- Scoped to uncorrected gaps only
|
||||
|
||||
### Simplified Toolbar
|
||||
- Advanced Mode toggle (persisted in localStorage)
|
||||
- Default: hides line numbers, delete icons, power-user tools
|
||||
- Advanced: shows Find/Replace, Edit All, Undo Auto Corrections, Timing Offset
|
||||
|
||||
### Edit Tracking & Feedback System
|
||||
- `editLog.ts` — session-based edit log capturing all user edits (word changes, deletions, additions, find/replace, segment operations, reverts)
|
||||
- `EditFeedbackBar.tsx` — slim feedback bar above sticky footer, appears after single-word edits with contextual "why?" buttons (Mis-heard word, Wrong lyrics, Spelling/punctuation, etc.)
|
||||
- Auto-dismisses after 10 seconds, pauses timer while hovered
|
||||
- Edit logs submitted to backend on review completion for transcription model improvement
|
||||
- Replaces the old high-friction `CorrectionAnnotationModal` (9 categories, confidence slider — nobody used it)
|
||||
- Backend endpoints: `POST /api/jobs/{job_id}/edit-log` (GCS storage), `POST /api/review/{job_id}/v1/annotations` (fixed from stub)
|
||||
- 40 tests across frontend and backend
|
||||
|
||||
### Word Component Improvements
|
||||
- Active gap ring indicator (persistent highlight for currently navigated gap)
|
||||
- Color coding preserved: blue = matched/confident, orange = needs review
|
||||
|
||||
## Current State
|
||||
|
||||
The lyrics review page at `/app/jobs#/{jobId}/review` is the most complex screen in the app. It's a combined review flow (lyrics + instrumental selection in one session).
|
||||
|
||||
### Top Stats Bar
|
||||
Four cards showing:
|
||||
- **Correction Handlers** - collapsed section (unclear what this means)
|
||||
- **Anchor Sequences: 19 (94%)** - "Matched sections between transcription and reference", sub-stats: "Words in Anchors: 266", "Multi-source Matches: 19"
|
||||
- **Corrected Gaps: 0 (0%)** - "Successfully corrected sections", sub-stats: "Words Replaced: 0", "Words Added/Deleted: +0/-0"
|
||||
- **Uncorrected Gaps: 9 (6%)** - "Sections that may need manual review", sub-stats: "Words Uncorrected: 18", "Number of Gaps: 9"
|
||||
|
||||
### Toolbar
|
||||
- **Mode buttons**: Edit (selected), Highlight, Delete
|
||||
- **Actions**: Undo All, undo/redo arrows, Find/Replace, Edit All
|
||||
- **Secondary row**: Undo Auto Corrections, Timing Offset, Feedback On
|
||||
- **Playback**: Play button with timeline slider (0:00 to 3:44)
|
||||
|
||||
### Left Panel: Corrected Transcription
|
||||
- Numbered lines (0-49 for Bon Jovi example)
|
||||
- Each line has: line number, delete icon, play icon, lyrics text
|
||||
- **Text/Timeline toggle** at top
|
||||
- Words are color-coded (see Color Coding section below)
|
||||
|
||||
### Right Panel: Reference Lyrics
|
||||
- **Source tabs**: Lrclib (selected), Genius, Spotify, + New
|
||||
- Copy button next to "Reference Lyrics" heading
|
||||
- Reference text with color-coded highlights matching the left panel
|
||||
|
||||
### Bottom Bar (Sticky)
|
||||
- "Lyrics look good?" text
|
||||
- **"Preview Video"** pink button
|
||||
- After preview, user clicks "Proceed to Instrumental Review" (green button) to move to Phase 4
|
||||
|
||||
### Flow: Lyrics → Preview → Instrumental
|
||||
The combined review flow is:
|
||||
1. User reviews/corrects lyrics on this page
|
||||
2. User clicks "Preview Video" to generate a preview with their corrections
|
||||
3. User watches preview to verify sync
|
||||
4. User clicks "Proceed to Instrumental Review" to move to instrumental selection (Phase 4)
|
||||
|
||||
## User Feedback
|
||||
|
||||
### Stats Bar
|
||||
> "This whole section could probably be removed or hidden behind a 'Stats' toggle button or something. Maybe we could use the space in this section to give the user guidance on how to use the tool instead?"
|
||||
|
||||
### Toolbar
|
||||
> "Agreed re. 'no guidance on when to use which' but I'm not really sure how best to resolve that without making the UI even more cluttered/overwhelming. Maybe the section above could be sufficient to give the user guidance on these buttons too, if we can make smart/efficient use of the space. We should also ensure all buttons have really rich, helpful tooltips (but also consider mobile users who may not have access to tooltips)."
|
||||
|
||||
### Left Panel
|
||||
> "All users definitely need the play button beside lines, but the line numbers and delete icons should probably be hidden unless the user enables 'Advanced Mode' or something"
|
||||
|
||||
### Color Coding (User's Explanation)
|
||||
> "Blue means 'matched with reference lyrics, so most likely correct'. Orange means 'unable to match with reference lyrics, so needs to be reviewed and either edited or deleted'."
|
||||
>
|
||||
> "Generally the user should be focusing on the Corrected Transcription panel. Words which are highlighted in blue are highly likely to be correct, so the user should focus on the words which are highlighted in orange (the 'gaps')."
|
||||
|
||||
### Correction Workflow
|
||||
> "I immediately focus on the gaps (highlighted in orange), typically I click the play icon beside those lines to listen to what the singer actually sings in each segment, while visually trying to find the relevant part of the reference lyrics to advise me on what action to take. Then I'll click on the segment and either edit, merge, delete words as necessary, adjust word timings etc. till the lyrics in that segment are correct and well synced, then press enter/click save. I'll repeat that for every gap until I'm confident I've reviewed and corrected (where necessary) all gaps, then I'll hit preview and listen to the whole track once to ensure the sync is fine before proceeding to instrumental review."
|
||||
|
||||
### Common Types of Corrections Needed
|
||||
|
||||
**1. Phantom words (delete)**
|
||||
> "The transcription very commonly puts 'And' at the start of lines during an instrumental section, in which case that word just needs to be deleted by clicking on the segment and clicking the delete icon beside the word."
|
||||
|
||||
**2. Mis-heard words (edit)**
|
||||
> "In many cases, the transcription just has some mistakes where it mis-heard things."
|
||||
|
||||
**3. Stylistic differences (no action needed)**
|
||||
> "In some cases, they may notice it's just a stylistic difference (e.g. the transcription writes '22' whereas reference lyrics write 'twenty two') and there's no action required."
|
||||
|
||||
**4. Reference lyrics are imperfect too**
|
||||
> "Lyrics fetched from the internet are also not 100% accurate, and in some cases are not available at all, so the user should use their best judgement when making these corrections."
|
||||
|
||||
### Difficulty Varies Hugely by Track
|
||||
|
||||
**Easy tracks** (acoustic, country, clear vocals):
|
||||
> "Acoustic or country tracks or pretty much anything with simple clear vocals tend to be transcribed really well and there may be no gaps / corrections to be made at all, or only a couple."
|
||||
|
||||
**Hard tracks** (rock, screamo, unclear vocals):
|
||||
> "Hard rock, screamo, or anything where the vocals aren't super clear can be a challenge - in some bad cases the transcription may be more than 50% incorrect and there can be quite a lot of work to do to get it corrected."
|
||||
|
||||
### Concrete Examples from Walkthrough
|
||||
|
||||
5 tracks at lyrics review stage, showing the full difficulty spectrum:
|
||||
|
||||
| Track | ID | Difficulty | Notes |
|
||||
|-------|-----|-----------|-------|
|
||||
| Coldplay - Parachutes | a95023e8 | Easy | Short song, only 2 mistakes: phantom "And" to delete, "I" → "I'll" |
|
||||
| Bon Jovi - It's My Life | c235f6bd | Easy-Medium | Few gaps, some need no action ("wanna", "calling"), but "Love can't even look, you gotta" is clearly mis-heard |
|
||||
| Silversun Pickups - Well Thought Out Twinkles | 41026cfe | Medium | Several clear transcription errors, e.g. "Share about elliptic views" → "We share apocalyptic views" |
|
||||
| Pony Bradshaw - Jehovah | 3552d63d | Medium | Several clear errors, e.g. "In Dilla, town on fire" → "A dilettante on fire" |
|
||||
| Steve Taylor - Jim Morrisons Grave - Live | ce8f2901 | Hard | Live version from YouTube, whole spoken section at start before singing begins (needs bulk deletion), plus many transcription mistakes e.g. "Jim Morrison, cryin'" → "Jim Morrison's Grave" |
|
||||
|
||||
## Proposed Design
|
||||
|
||||
### Replace Stats Bar with Guidance Panel
|
||||
Use the stats bar space for user guidance instead:
|
||||
- Brief explanation of what this page is for
|
||||
- Color coding legend (blue = matched/confident, orange = needs review)
|
||||
- Quick workflow tip: "Focus on the orange highlighted words. Click the play button to listen, then click the word to edit."
|
||||
- Collapsible "Stats" section for power users who want the numbers
|
||||
- Consider making this dismissible after first visit (remember in localStorage)
|
||||
|
||||
### Toolbar Improvements
|
||||
- Rich, helpful tooltips on all buttons (important: also consider mobile users who can't hover)
|
||||
- Consider "Advanced Mode" toggle that shows/hides power-user tools
|
||||
- Default view: Edit mode, play button, undo/redo, Preview Video
|
||||
- Advanced view: adds Highlight, Delete, Find/Replace, Timing Offset, Edit All
|
||||
|
||||
### Left Panel Simplification
|
||||
- **Hide by default**: Line numbers, delete icons
|
||||
- **Show by default**: Play button, lyrics text with color coding
|
||||
- **Advanced Mode**: Shows line numbers, delete icons, and other power tools
|
||||
- Play button is essential for all users (core to the correction workflow)
|
||||
|
||||
### Guided Gap Review Mode
|
||||
Based on the user's workflow of stepping through gaps:
|
||||
- "Jump to next gap" button/shortcut
|
||||
- Auto-scroll to the next uncorrected gap
|
||||
- Highlight the corresponding section in reference lyrics
|
||||
- Show a count: "Gap 3 of 9" with prev/next navigation
|
||||
|
||||
### Color Coding Legend
|
||||
Persistent but minimal:
|
||||
- Small bar or badge near the top: "🔵 Matched with reference lyrics" | "🟠 Needs your review"
|
||||
- Or integrated into the guidance panel
|
||||
|
||||
### Contextual Tips for Common Corrections
|
||||
Based on the user's experience, show tips like:
|
||||
- "Phantom words: If you see an extra word like 'And' at the start of a line during music, delete it"
|
||||
- "Listen first: Click the play button to hear what's actually sung before editing"
|
||||
- "Reference lyrics aren't perfect either - use your best judgement"
|
||||
- "Stylistic differences (e.g. '22' vs 'twenty two') don't need correcting"
|
||||
|
||||
### Preview & Submit Flow
|
||||
- After correcting gaps, user clicks "Preview Video"
|
||||
- Preview plays; user verifies sync
|
||||
- "Proceed to Instrumental Review" button moves to Phase 4
|
||||
- This flow is already in place - just needs clearer labeling/guidance
|
||||
|
||||
## Components Affected
|
||||
|
||||
- `frontend/components/` - Need to explore the review components in detail
|
||||
- The review UI was originally a separate React+Vite+MUI app (~14k lines) consolidated into the main Next.js frontend in Jan 2026
|
||||
- Key route: `/app/jobs#/{jobId}/review` (hash-based routing)
|
||||
- Stats panel component (replace with guidance panel)
|
||||
- Toolbar component (add tooltips, advanced mode toggle)
|
||||
- Transcription line component (hide line numbers/delete by default)
|
||||
- Need to identify the "gap navigation" mechanism if one exists
|
||||
@@ -1,147 +0,0 @@
|
||||
# Phase 4: Instrumental Review - UX Plan
|
||||
|
||||
> **Status**: User feedback captured, ready for detailed design
|
||||
> **Screenshots**: `phase4-instrumental-review.png`
|
||||
|
||||
## Current State
|
||||
|
||||
The instrumental review page at `/app/jobs#/{jobId}/instrumental` is the final human review stage before the video is generated. It's a significantly simpler interface than the lyrics review.
|
||||
|
||||
### Header Bar
|
||||
- Track name (e.g., "Coldplay - Parachutes")
|
||||
- Three stat badges:
|
||||
- **Segments count** (e.g., "1 segments")
|
||||
- **Backing vocals percentage** (e.g., "4% backing vocals")
|
||||
- **Recommendation badge** (e.g., "Clean recommended" in pink)
|
||||
|
||||
### Audio Player Controls
|
||||
- Play button with current time / total duration
|
||||
- **4 audio toggle buttons**: Original, Backing Vocals Only, Pure Instrumental, Instrumental + Backing
|
||||
- Upload button (for uploading a custom instrumental)
|
||||
- Zoom levels: 1x, 2x, 4x
|
||||
- Keyboard shortcuts: Shift+drag (select region), Space (play/pause)
|
||||
|
||||
### Waveform Visualization
|
||||
- Two waveform tracks displayed with timeline markers
|
||||
- Shows the audio waveform across the full track duration
|
||||
- Interactive - users can click/drag to select regions
|
||||
|
||||
### Mute Regions Panel (Bottom Left)
|
||||
- "Click segments below or Shift + drag on waveform"
|
||||
- Shows detected backing vocal segments as clickable buttons (e.g., "0:38 - 0:40")
|
||||
- Users can add custom mute regions by shift+dragging on the waveform
|
||||
|
||||
### Final Selection Panel (Bottom Right)
|
||||
Three options:
|
||||
1. **Clean Instrumental** - "No backing vocals" - shown with "Recommended" badge when backing vocals % is low
|
||||
2. **With Backing Vocals** - "All backing vocals included"
|
||||
3. **Original Audio** - "Full original with lead vocals"
|
||||
- **"Confirm & Continue"** button to finalize and proceed to video generation
|
||||
|
||||
## User Feedback
|
||||
|
||||
### No explanation of what this page is or how to use it
|
||||
> "The page doesn't explain to the user what it is and how to use it."
|
||||
|
||||
The page drops users in with no context about what they're looking at or what they should do.
|
||||
|
||||
### The Primary Workflow Users Should Follow
|
||||
|
||||
> "The primary thing they should start with is clicking on any pink sections in the waveform to listen to how the backing vocals sound, decide if the backing vocals should be kept or if we should use the clean instrumental, and if they want the backing vocals but they're mixed in with lead vocals for some sections of the song, they need to create a custom instrumental by shift-dragging on the waveform to mark sections for muting, clicking 'Create Custom', then selecting that."
|
||||
|
||||
The intended workflow is:
|
||||
1. **Listen to pink sections** - Click on any pink (backing vocal) segments in the waveform to hear what they sound like
|
||||
2. **Decide: keep or remove?** - Do the backing vocals add to the karaoke experience, or should they be removed?
|
||||
3. **If keeping backing vocals but some sections have lead vocal bleed**: Create a custom instrumental by shift+dragging on the waveform to mark problem sections for muting, click "Create Custom", then select that custom version
|
||||
4. **Confirm selection** and proceed to video generation
|
||||
|
||||
### Three Possible Outcomes
|
||||
|
||||
**Simple case (clean)**: Backing vocals are minimal or unwanted → select "Clean Instrumental" → Confirm
|
||||
|
||||
**Simple case (keep backing vocals)**: Backing vocals sound good throughout → select "With Backing Vocals" → Confirm
|
||||
|
||||
**Complex case (custom)**: Want backing vocals but some sections have lead vocal bleed → mute problem sections → "Create Custom" → select custom version → Confirm
|
||||
|
||||
## Observations
|
||||
|
||||
### What's Working Well
|
||||
- The page is much simpler than lyrics review - clear, focused decision
|
||||
- The recommendation badge ("Clean recommended") is helpful
|
||||
- Audio toggle buttons let users A/B test between instrumental options
|
||||
- Waveform visualization with pink backing vocal highlights is intuitive once you know what to do
|
||||
|
||||
### Potential Issues for New Users
|
||||
|
||||
#### 1. No onboarding or explanation
|
||||
- Users don't know what "backing vocals" are or why this review exists
|
||||
- No guidance on what to do first (click pink sections to listen)
|
||||
- The whole purpose of the page needs a brief introduction
|
||||
|
||||
#### 2. The workflow isn't communicated
|
||||
- Users should start by listening to backing vocal segments, but nothing tells them this
|
||||
- The decision tree (clean vs backing vocals vs custom) isn't explained
|
||||
- "Create Custom" workflow (shift+drag → mute → create) is completely hidden
|
||||
|
||||
#### 3. Mute Regions / Custom Instrumental flow is opaque
|
||||
- "Click segments below or Shift + drag on waveform" is the only guidance
|
||||
- Users don't know WHEN they'd want to mute regions (answer: when backing vocals are mixed with lead vocal bleed in specific sections)
|
||||
- The connection between muting sections and creating a "Custom" instrumental option isn't clear
|
||||
|
||||
#### 4. What does "Upload" do?
|
||||
- The Upload button near the audio toggles isn't explained
|
||||
- Needs a tooltip or brief explanation
|
||||
|
||||
#### 5. Stats badges are jargon-heavy
|
||||
- "1 segments" and "4% backing vocals" - what do these mean to a new user?
|
||||
- The recommendation badge is good, but the numbers without context may confuse
|
||||
|
||||
## Proposed Design
|
||||
|
||||
### Replace Stats Bar with Guided Onboarding (Consistent with Phase 3 Approach)
|
||||
Replace the stats badges area with a guidance panel that explains:
|
||||
- **What this page is**: "This is where you choose your karaoke backing track. The AI has separated the vocals from the music - now you decide which version sounds best."
|
||||
- **What backing vocals are**: "Backing vocals are the harmony/chorus voices that sing along with the lead singer. Some karaoke singers prefer to keep them for guidance, others prefer a pure instrumental."
|
||||
- **What to do first**: "Start by clicking the pink highlighted sections in the waveform to listen to the backing vocals. Then decide if you want to keep them or use a clean instrumental."
|
||||
- Collapsible/dismissible for returning users (localStorage)
|
||||
|
||||
### Guided Workflow Steps
|
||||
Present the decision as a clear flow:
|
||||
|
||||
**Step 1: Listen** - "Click the pink sections in the waveform to hear the backing vocals"
|
||||
|
||||
**Step 2: Decide** - "Do you want to keep the backing vocals?"
|
||||
- If no → "Select Clean Instrumental and confirm"
|
||||
- If yes → "Select With Backing Vocals. If some sections have unwanted lead vocal bleed, continue to Step 3"
|
||||
|
||||
**Step 3 (if needed): Customize** - "Shift+drag on the waveform to mark sections where lead vocals bleed through, then click Create Custom to generate a custom instrumental with those sections muted"
|
||||
|
||||
### Contextual Recommendations
|
||||
The system already recommends "Clean" when backing vocals are low (4%). Enhance this with:
|
||||
- Clear reasoning: "We recommend Clean Instrumental because this track has very few backing vocals (4%)"
|
||||
- For tracks with high backing vocal %, recommend "With Backing Vocals" and explain why
|
||||
|
||||
### Simplify for Default Users
|
||||
- For tracks where the recommendation is clear, the guidance could suggest just confirming
|
||||
- "This track has very little backing vocal content. We recommend the Clean Instrumental - confirm below to proceed!"
|
||||
- The "Confirm & Continue" button could be more prominent
|
||||
|
||||
### Improve Mute Regions / Custom Instrumental UX
|
||||
- Explain WHEN users need this: "If you want backing vocals but notice lead vocal bleed in certain sections, you can mute those sections to create a custom mix"
|
||||
- Make the shift+drag → Create Custom flow more discoverable
|
||||
- Consider a more guided approach: "Hear something that shouldn't be there? Shift+drag over that section to mark it for muting"
|
||||
|
||||
## Flow After Confirmation
|
||||
|
||||
After clicking "Confirm & Continue":
|
||||
- The job progresses to video generation
|
||||
- This is the final human review step
|
||||
- User then waits for the video to be rendered and can download it
|
||||
|
||||
## Components Affected
|
||||
|
||||
- Need to explore the instrumental review components in detail
|
||||
- Key route: `/app/jobs#/{jobId}/instrumental` (hash-based routing)
|
||||
- The audio player with waveform visualization
|
||||
- The backing vocal detection/mute regions system
|
||||
- The final selection radio group
|
||||
@@ -1,43 +0,0 @@
|
||||
# Feedback-for-Credits Mechanism — 2026-03-01
|
||||
|
||||
## Summary
|
||||
|
||||
Replaced the beta-only feedback flow with a general feedback-for-credits mechanism available to all users. Users who complete 2+ karaoke videos can submit product feedback to earn 2 free credits, bringing total possible free credits to 4 (2 welcome + 2 feedback).
|
||||
|
||||
This was PR 2 of 2 in the beta→credits transition:
|
||||
- PR #430: Removed beta program from homepage, promoted 2 free welcome credits
|
||||
- PR #431: Added feedback-for-credits for all users
|
||||
|
||||
## Key Changes
|
||||
|
||||
### Backend
|
||||
- **New models** in `backend/models/user.py`: `UserFeedback`, `UserFeedbackRequest`, `UserFeedbackResponse`, `FeedbackEligibilityResponse`
|
||||
- **New field** on `User` model: `has_submitted_feedback: bool` (for duplicate prevention)
|
||||
- **New field** on `UserPublic` model: `feedback_eligible: bool` (computed in `/me` endpoint)
|
||||
- **New endpoints** in `backend/api/routes/users.py`:
|
||||
- `GET /api/users/feedback/eligibility` — returns eligibility details
|
||||
- `POST /api/users/feedback` — submits feedback, grants 2 credits
|
||||
- **Updated `/me` endpoint** — computes `feedback_eligible` inline (no extra API call needed)
|
||||
- **New Firestore collection**: `user_feedback` (separate from `beta_feedback`)
|
||||
- **Updated welcome email** — credit-focused styling with feedback teaser
|
||||
|
||||
### Frontend
|
||||
- **FeedbackDialog component** (`frontend/components/feedback/FeedbackDialog.tsx`) — 4 star ratings, 3 text fields, 2 checkboxes, loading/success states
|
||||
- **Dashboard banner** — dismissible green banner when `user.feedback_eligible === true`
|
||||
- **User dropdown** — "Earn 2 Free Credits" menu item with Gift icon
|
||||
- **Types/API** — `feedback_eligible` on User type, `submitFeedback()` API method
|
||||
|
||||
## Decisions Made
|
||||
|
||||
- **Eligibility threshold**: 2 completed jobs. Low enough to be achievable, high enough that users have meaningful experience to share.
|
||||
- **Credit reward**: 2 credits (same as welcome credits). Enough to be compelling, not so much it undermines paid packages.
|
||||
- **One-time only**: `has_submitted_feedback` flag prevents duplicate submissions.
|
||||
- **Inline eligibility**: `feedback_eligible` computed in `/me` response avoids an extra API roundtrip.
|
||||
- **Separate collection**: `user_feedback` kept separate from `beta_feedback` to preserve historical beta data.
|
||||
- **Text validation**: At least one text field must have >50 characters to ensure substantive feedback.
|
||||
|
||||
## Future Considerations
|
||||
|
||||
- Analytics: Track feedback submission rates and banner click-through rates
|
||||
- Admin view: Consider adding an admin page to view user feedback submissions
|
||||
- Follow-up: Could send email prompts to eligible users who haven't submitted yet
|
||||
@@ -1,299 +0,0 @@
|
||||
# Decouple Audio Search from Job Creation
|
||||
|
||||
**Created:** 2026-03-02
|
||||
**Branch:** feat/sess-20260302-1716-guided-submission-flow
|
||||
**Status:** Implemented (v0.122.4)
|
||||
|
||||
---
|
||||
|
||||
## Background
|
||||
|
||||
### Phase 1 UX Plan (2026-02-28)
|
||||
|
||||
The Phase 1 UX overhaul plan (`docs/archive/2026-02-28-ux-phase1-job-creation.md`) identified this
|
||||
issue and noted two options:
|
||||
|
||||
> **Option 1 (simpler):** Still create the job early but hide that from the user (keep current backend flow, change frontend presentation)
|
||||
>
|
||||
> **Option 2 (proper):** Defer job creation until the user confirms everything (would require backend changes)
|
||||
>
|
||||
> Option 1 is probably simpler and lower-risk.
|
||||
|
||||
Option 1 was implemented. But it turned out to cause real UX problems in production, so we're now
|
||||
implementing Option 2 properly.
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
The guided job creation flow (3-step wizard: Song Info → Find Audio → Customize & Create) creates a
|
||||
backend job as soon as the user reaches Step 2 (audio search), before they have:
|
||||
- Set the private flag
|
||||
- Set display overrides (display_artist, display_title for the title card)
|
||||
- Actually confirmed they want a job at all
|
||||
|
||||
**Problems caused:**
|
||||
|
||||
**A) Orphan job records** — Abandoned searches (user goes back or closes tab) leave job records in
|
||||
Firestore. The "back" button calls `api.deleteJob()` as best-effort cleanup, but this fails silently
|
||||
and the browser may close before the call completes.
|
||||
|
||||
**B) Wrong field values at creation** — The job is created with `is_private: false` and no display
|
||||
overrides, because the user hasn't reached Step 3 yet. These are then patched via `selectAudioResult`
|
||||
overrides. The job briefly exists with incorrect values.
|
||||
|
||||
**C) Jobs appear in Recent Jobs list** — Despite being in `AWAITING_AUDIO_SELECTION` state, these
|
||||
jobs appear in the job list (`isInteractive` includes this status). Users see a confusing "ghost job"
|
||||
before they've confirmed creation.
|
||||
|
||||
**D) Notification chime fires** — State transitions on the temporary job trigger the in-browser
|
||||
action-required chime during what the user thinks is just a search step.
|
||||
|
||||
---
|
||||
|
||||
## Solution: Standalone Search Endpoint + Search Sessions
|
||||
|
||||
Add a stateless `POST /api/audio-search/search-standalone` endpoint that runs audio search without
|
||||
creating a job. Store results temporarily in a `search_sessions` Firestore collection with 30-minute
|
||||
TTL. Only create the job at Step 3 ("Customize & Create"), when the user has made all their choices
|
||||
and explicitly clicks "Create Karaoke Video".
|
||||
|
||||
The old `POST /api/audio-search/search` endpoint remains **unchanged** for CLI backward compatibility.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### Current Flow (problematic)
|
||||
|
||||
```
|
||||
Step 1: Enter artist/title
|
||||
Step 2: POST /audio-search/search → Creates job → Polls for results → User picks result
|
||||
Step 3: POST /audio-search/{job_id}/select → Triggers download
|
||||
Problem: Job exists from Step 2 onward with incomplete data
|
||||
```
|
||||
|
||||
### New Flow (correct)
|
||||
|
||||
```
|
||||
Step 1: Enter artist/title
|
||||
Step 2: POST /audio-search/search-standalone → Returns results + search_session_id (NO job)
|
||||
Step 3: POST /api/jobs/create-from-search → Creates job + selects audio + triggers download
|
||||
Better: Job only exists after user explicitly creates it, with all correct values from the start
|
||||
```
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
1. **Synchronous search** — The standalone endpoint runs the search synchronously and returns
|
||||
results directly (~5–15s response time). No polling loop needed. Simpler frontend code than the
|
||||
current create-then-poll pattern.
|
||||
|
||||
2. **Firestore `search_sessions` collection** — Required because Cloud Run has multiple instances:
|
||||
a search on instance A must be retrievable when the job creation hits instance B. In-memory cache
|
||||
won't work.
|
||||
|
||||
3. **30-minute TTL** — Firestore's built-in TTL feature auto-deletes stale sessions. Same pattern as
|
||||
worker logs TTL in `infrastructure/modules/database.py`. No cleanup code needed.
|
||||
|
||||
4. **Security** — Frontend sends `search_session_id + selection_index`, not raw download URLs.
|
||||
Backend retrieves the trusted search results from Firestore. This prevents URL injection.
|
||||
|
||||
5. **`remote_search_id` preserved** — The flacfetch torrent download service uses this for
|
||||
concurrent-safe request routing. It's stored in the session doc and copied to the job at creation.
|
||||
|
||||
6. **No-results returns `[]`** — Empty search results return `{ results: [], results_count: 0 }`
|
||||
rather than a 404 error. This naturally removes the need for any special 404 error handling in the
|
||||
frontend `NoResultsSection` component.
|
||||
|
||||
---
|
||||
|
||||
## Implementation
|
||||
|
||||
### Phase 1: Backend — Search Session Storage
|
||||
|
||||
**Modify `backend/services/firestore_service.py`**
|
||||
|
||||
Add session CRUD methods (stays in the existing service, no new file needed):
|
||||
```python
|
||||
def create_search_session(self, session_data: dict) -> str
|
||||
# Stores in `search_sessions` collection, returns session_id
|
||||
def get_search_session(self, session_id: str) -> Optional[dict]
|
||||
# Returns None if expired or not found
|
||||
def delete_search_session(self, session_id: str) -> None
|
||||
```
|
||||
|
||||
Session document schema:
|
||||
```json
|
||||
{
|
||||
"session_id": "<uuid>",
|
||||
"user_email": "user@example.com",
|
||||
"tenant_id": null,
|
||||
"artist": "The Beatles",
|
||||
"title": "Come Together",
|
||||
"results": [...],
|
||||
"remote_search_id": "...",
|
||||
"created_at": "<timestamp>",
|
||||
"ttl_expiry": "<timestamp + 30min>"
|
||||
}
|
||||
```
|
||||
|
||||
**Modify `infrastructure/modules/database.py`**
|
||||
|
||||
Add TTL policy (same pattern as existing worker logs TTL):
|
||||
```python
|
||||
resources["firestore_field_search_sessions_ttl"] = firestore.Field(
|
||||
"firestore-field-search-sessions-ttl",
|
||||
project=PROJECT_ID,
|
||||
database=firestore_db.name,
|
||||
collection="search_sessions",
|
||||
field="ttl_expiry",
|
||||
ttl_config={}, # Empty block enables TTL on this field
|
||||
index_config={}, # Disable indexing on TTL field
|
||||
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
|
||||
)
|
||||
```
|
||||
|
||||
### Phase 2: Backend — Standalone Search Endpoint
|
||||
|
||||
**Modify `backend/routers/audio_search.py`**
|
||||
|
||||
Add `POST /api/audio-search/search-standalone`:
|
||||
```
|
||||
Request: { artist: str, title: str }
|
||||
Auth: Required (same tenant/auth handling as existing /search endpoint)
|
||||
Response: { status, search_session_id, results: AudioSearchResultResponse[], results_count }
|
||||
|
||||
- Runs audio_search_service.search_async(artist, title) synchronously (await inline)
|
||||
- On no results: returns { results: [], results_count: 0 } — NOT a 404 error
|
||||
- On results: creates search session in Firestore with ttl_expiry = now + 30min
|
||||
- Returns results directly in response (no polling needed)
|
||||
```
|
||||
|
||||
Credit check: verify user has credits but do NOT deduct yet (deduction happens at job creation).
|
||||
|
||||
### Phase 3: Backend — Create Job from Search Session
|
||||
|
||||
**Modify `backend/routers/audio_search.py`** (or `backend/routers/jobs.py`)
|
||||
|
||||
Add `POST /api/jobs/create-from-search`:
|
||||
```
|
||||
Request: {
|
||||
search_session_id: str,
|
||||
selection_index: int,
|
||||
artist: str,
|
||||
title: str,
|
||||
display_artist?: str,
|
||||
display_title?: str,
|
||||
is_private?: bool,
|
||||
theme_id?: str (default: tenant/system default)
|
||||
}
|
||||
Auth: Required (owner check — must match session's user_email)
|
||||
|
||||
- Retrieves search session from Firestore (404 if expired/not found)
|
||||
- Validates selection_index is in range
|
||||
- Creates job via job_manager.create_job() with ALL final values (no overrides needed later)
|
||||
- Job starts with correct is_private, display_artist, display_title from the beginning
|
||||
- Copies remote_search_id and results to job.state_data
|
||||
- Sets audio_source_type, source_name, source_id, etc.
|
||||
- Triggers _download_audio_and_trigger_workers() as background task
|
||||
- Job goes directly to DOWNLOADING_AUDIO (skips AWAITING_AUDIO_SELECTION entirely)
|
||||
- Deletes the search session (consumed)
|
||||
- Returns { status, job_id }
|
||||
- Error: 404 with "Search session expired — please search again" if session missing
|
||||
```
|
||||
|
||||
### Phase 4: Frontend — API Client
|
||||
|
||||
**Modify `frontend/lib/api.ts`**
|
||||
|
||||
Add new methods (keep old `searchAudio`, `getAudioSearchResults`, `selectAudioResult` for backward compat):
|
||||
```typescript
|
||||
async searchStandalone(
|
||||
artist: string,
|
||||
title: string
|
||||
): Promise<{ search_session_id: string; results: AudioSearchResult[]; results_count: number }>
|
||||
|
||||
async createJobFromSearch(params: {
|
||||
search_session_id: string
|
||||
selection_index: number
|
||||
artist: string
|
||||
title: string
|
||||
display_artist?: string
|
||||
display_title?: string
|
||||
is_private?: boolean
|
||||
}): Promise<{ job_id: string }>
|
||||
```
|
||||
|
||||
### Phase 5: Frontend — AudioSourceStep
|
||||
|
||||
**Modify `frontend/components/job/steps/AudioSourceStep.tsx`**
|
||||
|
||||
- Replace `api.searchAudio()` → `api.searchStandalone()`
|
||||
- Remove `pollForResults()` — results returned synchronously in initial response
|
||||
- Remove `jobId` local state (no job created during search step)
|
||||
- Change `onJobCreated` callback → `onSearchCompleted(searchSessionId: string)` for search path
|
||||
- Back button: remove `jobIdToCleanup` parameter — no job to clean up, sessions expire naturally
|
||||
- NoResultsSection renders naturally when `results.length === 0 && !isSearching && !searchError`
|
||||
(no special 404 error code handling needed)
|
||||
- Upload/URL fallback tabs: **unchanged** — still create jobs immediately in Step 2 (correct)
|
||||
|
||||
### Phase 6: Frontend — GuidedJobFlow
|
||||
|
||||
**Modify `frontend/components/job/GuidedJobFlow.tsx`**
|
||||
|
||||
- Add `searchSessionId: string | null` state (alongside existing `selectedResultIndex`)
|
||||
- Add `handleSearchCompleted(sessionId: string)` callback
|
||||
- Update `handleConfirm()`: call `api.createJobFromSearch({ search_session_id: searchSessionId, selection_index: selectedResultIndex, artist, title, display_artist, display_title, is_private })` to get `job_id`
|
||||
- Simplify `handleBackFromAudio()`: just reset `searchSessionId` to null — no `api.deleteJob()` call
|
||||
- Upload/URL `onFallbackComplete` callbacks: unchanged
|
||||
|
||||
### Phase 7: Testing
|
||||
|
||||
**Backend unit tests:**
|
||||
- `search-standalone`: happy path, no results (returns `[]`), auth required
|
||||
- `create-from-search`: happy path, expired session returns 404, invalid index, credit deduction
|
||||
- Session Firestore CRUD (create, get, delete)
|
||||
- Owner validation (can't access another user's session)
|
||||
|
||||
**Frontend unit tests (Jest):**
|
||||
- `AudioSourceStep`: mock `api.searchStandalone`, verify no job ID, no polling
|
||||
- `GuidedJobFlow`: mock `api.createJobFromSearch`, verify job created only on confirm
|
||||
- NoResultsSection renders when `results.length === 0` (no 404 error handling)
|
||||
|
||||
**E2E regression (Playwright):**
|
||||
- Full guided flow: verify 0 jobs created until "Create Karaoke Video" clicked
|
||||
- Back at Step 2: confirm no job in Firestore
|
||||
- Created job: verify `is_private`, `display_artist`, `display_title` correct from creation (not patched)
|
||||
|
||||
---
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `backend/services/firestore_service.py` | Add search session CRUD methods |
|
||||
| `backend/routers/audio_search.py` | Add `POST /api/audio-search/search-standalone` |
|
||||
| `backend/routers/jobs.py` | Add `POST /api/jobs/create-from-search` |
|
||||
| `infrastructure/modules/database.py` | Add TTL policy for `search_sessions` collection |
|
||||
| `frontend/lib/api.ts` | Add `searchStandalone`, `createJobFromSearch` |
|
||||
| `frontend/components/job/steps/AudioSourceStep.tsx` | Use standalone search, remove polling/job |
|
||||
| `frontend/components/job/GuidedJobFlow.tsx` | Add session state, defer job creation |
|
||||
|
||||
**Unchanged:** Old `POST /api/audio-search/search` (CLI compat), upload/URL paths, `AWAITING_AUDIO_SELECTION` status (still used by CLI).
|
||||
|
||||
---
|
||||
|
||||
## Risks & Mitigations
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|-----------|
|
||||
| Search session expires before user confirms | Return 404 with "Search expired — please search again", frontend shows retry prompt |
|
||||
| Firestore TTL takes up to 72h to actually delete | Acceptable — documents are small, TTL is courtesy cleanup |
|
||||
| Old browser cache hits old endpoints | Old endpoints remain functional — fully backward compatible |
|
||||
| `search-standalone` blocks for 5–15s | Same latency as current `/search`, just no polling loop |
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Old endpoints remain functional — no breaking changes to existing API
|
||||
- If issues arise, revert `AudioSourceStep` to use `api.searchAudio()` (old endpoint)
|
||||
- `search_sessions` Firestore collection can be dropped without any impact
|
||||
|
Before Width: | Height: | Size: 162 KiB |
|
Before Width: | Height: | Size: 150 KiB |
|
Before Width: | Height: | Size: 161 KiB |
|
Before Width: | Height: | Size: 131 KiB |
|
Before Width: | Height: | Size: 141 KiB |
|
Before Width: | Height: | Size: 132 KiB |
|
Before Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 154 KiB |
|
Before Width: | Height: | Size: 91 KiB |
|
Before Width: | Height: | Size: 185 KiB |
|
Before Width: | Height: | Size: 155 KiB |
|
Before Width: | Height: | Size: 155 KiB |
|
Before Width: | Height: | Size: 83 KiB |
|
Before Width: | Height: | Size: 168 KiB |
|
Before Width: | Height: | Size: 167 KiB |
|
Before Width: | Height: | Size: 59 KiB |
@@ -1,19 +1,6 @@
|
||||
playwright-report-prod/
|
||||
playwright-report-demo/
|
||||
|
||||
# Demo video output and raw recordings (large files, not for git)
|
||||
demo-output/
|
||||
docs/images/e2e-happy-path/video/
|
||||
|
||||
# Local debug scripts (may contain tokens - never commit)
|
||||
# Use this pattern for ad-hoc testing: test-*.local.{js,cjs,mjs,ts}
|
||||
test-*.local.*
|
||||
debug-*.local.*
|
||||
|
||||
# Search result fixtures (large raw data, regenerate with fetch-search-fixtures.mjs)
|
||||
# The index.json is tracked for reference; individual result files are gitignored
|
||||
e2e/fixtures/data/search-results/*.json
|
||||
!e2e/fixtures/data/search-results/index.json
|
||||
|
||||
# Chrome profile for interactive fixture review (auto-created by playwright.review.config.ts)
|
||||
.review-profile/
|
||||
@@ -1,262 +0,0 @@
|
||||
/**
|
||||
* Tests for the decoupled guided job creation flow.
|
||||
*
|
||||
* Key invariants verified:
|
||||
* - api.searchStandalone is called during Step 2 (not api.searchAudio / api.createJob)
|
||||
* - api.createJobFromSearch is called at Step 3 confirm with correct params
|
||||
* - api.deleteJob is never called when going back from search
|
||||
* - AudioSourceStep receives onSearchCompleted (not onJobCreated) for the search path
|
||||
*/
|
||||
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock the api module
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
searchStandalone: jest.fn(),
|
||||
searchAudio: jest.fn(),
|
||||
createJobFromSearch: jest.fn(),
|
||||
createJob: jest.fn(),
|
||||
deleteJob: jest.fn(),
|
||||
uploadFile: jest.fn(),
|
||||
submitUrl: jest.fn(),
|
||||
getJob: jest.fn(),
|
||||
selectAudioResult: jest.fn(),
|
||||
pollAudioSearchResults: jest.fn(),
|
||||
},
|
||||
ApiError: class ApiError extends Error {
|
||||
status: number
|
||||
constructor(status: number, message: string) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
const mockApi = api as jest.Mocked<typeof api>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API module contract tests — verifies the new API methods exist and work
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('api module — standalone search methods', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('exports searchStandalone function', () => {
|
||||
expect(typeof api.searchStandalone).toBe('function')
|
||||
})
|
||||
|
||||
it('exports createJobFromSearch function', () => {
|
||||
expect(typeof api.createJobFromSearch).toBe('function')
|
||||
})
|
||||
|
||||
it('searchStandalone returns search_session_id and results', async () => {
|
||||
mockApi.searchStandalone.mockResolvedValue({
|
||||
search_session_id: 'sess-abc',
|
||||
results: [],
|
||||
results_count: 0,
|
||||
})
|
||||
|
||||
const result = await api.searchStandalone('ABBA', 'Waterloo')
|
||||
|
||||
expect(result).toHaveProperty('search_session_id')
|
||||
expect(result).toHaveProperty('results')
|
||||
expect(result).toHaveProperty('results_count')
|
||||
})
|
||||
|
||||
it('createJobFromSearch returns job_id', async () => {
|
||||
mockApi.createJobFromSearch.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'job-xyz',
|
||||
message: 'Created',
|
||||
})
|
||||
|
||||
const result = await api.createJobFromSearch({
|
||||
search_session_id: 'sess-abc',
|
||||
selection_index: 0,
|
||||
artist: 'ABBA',
|
||||
title: 'Waterloo',
|
||||
})
|
||||
|
||||
expect(result).toHaveProperty('job_id')
|
||||
})
|
||||
|
||||
it('searchStandalone does NOT create a job', async () => {
|
||||
mockApi.searchStandalone.mockResolvedValue({
|
||||
search_session_id: 'sess-new',
|
||||
results: [
|
||||
{
|
||||
index: 0,
|
||||
title: 'Waterloo',
|
||||
artist: 'ABBA',
|
||||
provider: 'YouTube',
|
||||
url: 'https://youtube.com/watch?v=abc',
|
||||
},
|
||||
],
|
||||
results_count: 1,
|
||||
})
|
||||
|
||||
await api.searchStandalone('ABBA', 'Waterloo')
|
||||
|
||||
// Verify that searchStandalone is called but createJob/createJobFromSearch are NOT
|
||||
expect(mockApi.searchStandalone).toHaveBeenCalledTimes(1)
|
||||
expect(mockApi.createJob).not.toHaveBeenCalled()
|
||||
expect(mockApi.createJobFromSearch).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// AudioSourceStep component — prop interface contract tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('AudioSourceStep — component interface', () => {
|
||||
it('exports AudioSourceStep as a named export', async () => {
|
||||
const mod = await import('@/components/job/steps/AudioSourceStep')
|
||||
expect(typeof mod.AudioSourceStep).toBe('function')
|
||||
})
|
||||
|
||||
it('AudioSourceStep accepts onSearchCompleted prop (search path does not use onJobCreated)', async () => {
|
||||
const { AudioSourceStep } = await import('@/components/job/steps/AudioSourceStep')
|
||||
|
||||
// We verify the component's prop interface by checking it accepts onSearchCompleted
|
||||
// TypeScript compilation enforces the type; here we just verify the component exists.
|
||||
expect(AudioSourceStep).toBeDefined()
|
||||
expect(typeof AudioSourceStep).toBe('function')
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Guided flow: job creation contract
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Guided flow — job creation deferred to Step 3', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('createJobFromSearch is called with all Step 3 values', async () => {
|
||||
mockApi.createJobFromSearch.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'new-job-456',
|
||||
message: 'Job created',
|
||||
})
|
||||
|
||||
// Simulate what GuidedJobFlow.handleConfirm() does
|
||||
const response = await api.createJobFromSearch({
|
||||
search_session_id: 'sess-test-123',
|
||||
selection_index: 0,
|
||||
artist: 'ABBA',
|
||||
title: 'Waterloo',
|
||||
display_artist: undefined,
|
||||
display_title: undefined,
|
||||
is_private: false,
|
||||
})
|
||||
|
||||
expect(response.job_id).toBe('new-job-456')
|
||||
expect(mockApi.createJobFromSearch).toHaveBeenCalledWith({
|
||||
search_session_id: 'sess-test-123',
|
||||
selection_index: 0,
|
||||
artist: 'ABBA',
|
||||
title: 'Waterloo',
|
||||
display_artist: undefined,
|
||||
display_title: undefined,
|
||||
is_private: false,
|
||||
})
|
||||
// createJob is NOT the method used
|
||||
expect(mockApi.createJob).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('createJobFromSearch includes is_private and display overrides', async () => {
|
||||
mockApi.createJobFromSearch.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'private-job-789',
|
||||
message: 'Job created',
|
||||
})
|
||||
|
||||
await api.createJobFromSearch({
|
||||
search_session_id: 'sess-test-456',
|
||||
selection_index: 1,
|
||||
artist: 'ABBA',
|
||||
title: 'Waterloo',
|
||||
display_artist: 'Abba (Karaoke)',
|
||||
display_title: 'Waterloo (Karaoke)',
|
||||
is_private: true,
|
||||
})
|
||||
|
||||
expect(mockApi.createJobFromSearch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
is_private: true,
|
||||
display_artist: 'Abba (Karaoke)',
|
||||
display_title: 'Waterloo (Karaoke)',
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('deleteJob is never called when going back from audio search', () => {
|
||||
// In the old flow, deleteJob was called with jobIdToCleanup on back.
|
||||
// In the new flow, sessions expire naturally — no deleteJob call.
|
||||
// This test verifies that no deleteJob call is made in the search phase.
|
||||
|
||||
// Simulate: user reaches step 2, search completes, user goes back
|
||||
// No job was created during the search, so deleteJob should not be called.
|
||||
expect(mockApi.deleteJob).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('searchStandalone is called instead of searchAudio in guided flow', async () => {
|
||||
mockApi.searchStandalone.mockResolvedValue({
|
||||
search_session_id: 'sess-fresh',
|
||||
results: [],
|
||||
results_count: 0,
|
||||
})
|
||||
|
||||
// Simulate what AudioSourceStep.triggerSearch() does
|
||||
const result = await api.searchStandalone('The Beatles', 'Hey Jude')
|
||||
|
||||
expect(mockApi.searchStandalone).toHaveBeenCalledWith('The Beatles', 'Hey Jude')
|
||||
expect(result.search_session_id).toBeDefined()
|
||||
expect(mockApi.searchAudio).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('no-results search returns session with empty results (not an error)', async () => {
|
||||
// Old flow raised 404 on no results; new flow returns empty results list
|
||||
mockApi.searchStandalone.mockResolvedValue({
|
||||
search_session_id: 'sess-empty',
|
||||
results: [],
|
||||
results_count: 0,
|
||||
})
|
||||
|
||||
const result = await api.searchStandalone('Unknown Artist', 'Unknown Song 12345')
|
||||
|
||||
// Should resolve successfully with empty results, not reject
|
||||
expect(result.results).toEqual([])
|
||||
expect(result.results_count).toBe(0)
|
||||
expect(result.search_session_id).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GuidedJobFlow — component interface
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Mock deps needed to import GuidedJobFlow without side effects
|
||||
jest.mock('@/lib/auth', () => ({
|
||||
useAuth: jest.fn(() => ({ user: null, isLoading: false })),
|
||||
getAccessToken: jest.fn(() => null),
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/tenant', () => ({
|
||||
useTenant: jest.fn(() => ({ tenant: null })),
|
||||
}))
|
||||
|
||||
describe('GuidedJobFlow — component interface', () => {
|
||||
it('exports GuidedJobFlow as a named export', async () => {
|
||||
const mod = await import('@/components/job/GuidedJobFlow')
|
||||
expect(typeof mod.GuidedJobFlow).toBe('function')
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,7 @@
|
||||
* Unit tests for job-status.ts utility functions
|
||||
*/
|
||||
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, getDisplayJobs, JobStep } from '../lib/job-status';
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, getJobProgressPercent, getJobPriority, sortJobsByPriority, getDisplayJobs, JobStep } from '../lib/job-status';
|
||||
import type { Job } from '../lib/api';
|
||||
|
||||
// Helper to create a minimal Job object for testing
|
||||
@@ -426,41 +426,6 @@ describe('isBlockingStatus', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('isNotifiableBlockingStatus', () => {
|
||||
it('returns true for awaiting_review', () => {
|
||||
expect(isNotifiableBlockingStatus('awaiting_review')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for in_review', () => {
|
||||
expect(isNotifiableBlockingStatus('in_review')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for awaiting_instrumental_selection', () => {
|
||||
expect(isNotifiableBlockingStatus('awaiting_instrumental_selection')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false for awaiting_audio_selection (user already engaged)', () => {
|
||||
expect(isNotifiableBlockingStatus('awaiting_audio_selection')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for non-blocking statuses', () => {
|
||||
expect(isNotifiableBlockingStatus('pending')).toBe(false);
|
||||
expect(isNotifiableBlockingStatus('downloading')).toBe(false);
|
||||
expect(isNotifiableBlockingStatus('complete')).toBe(false);
|
||||
expect(isNotifiableBlockingStatus('failed')).toBe(false);
|
||||
});
|
||||
|
||||
it('handles case insensitivity', () => {
|
||||
expect(isNotifiableBlockingStatus('AWAITING_REVIEW')).toBe(true);
|
||||
expect(isNotifiableBlockingStatus('AWAITING_AUDIO_SELECTION')).toBe(false);
|
||||
});
|
||||
|
||||
it('handles null/undefined gracefully', () => {
|
||||
expect(isNotifiableBlockingStatus(null as unknown as string)).toBe(false);
|
||||
expect(isNotifiableBlockingStatus(undefined as unknown as string)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getJobProgressPercent', () => {
|
||||
it('returns 0 for terminal states (step 0)', () => {
|
||||
const job = createJob('failed');
|
||||
@@ -493,7 +458,38 @@ describe('getJobProgressPercent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('sortJobsByDate', () => {
|
||||
describe('getJobPriority', () => {
|
||||
it('returns 0 for blocking statuses (user action needed)', () => {
|
||||
expect(getJobPriority(createJob('awaiting_review'))).toBe(0);
|
||||
expect(getJobPriority(createJob('awaiting_audio_selection'))).toBe(0);
|
||||
expect(getJobPriority(createJob('awaiting_instrumental_selection'))).toBe(0);
|
||||
expect(getJobPriority(createJob('in_review'))).toBe(0);
|
||||
});
|
||||
|
||||
it('returns 1 for active/processing statuses', () => {
|
||||
expect(getJobPriority(createJob('pending'))).toBe(1);
|
||||
expect(getJobPriority(createJob('downloading'))).toBe(1);
|
||||
expect(getJobPriority(createJob('rendering_video'))).toBe(1);
|
||||
expect(getJobPriority(createJob('separating_stage1'))).toBe(1);
|
||||
});
|
||||
|
||||
it('returns 2 for completed statuses', () => {
|
||||
expect(getJobPriority(createJob('complete'))).toBe(2);
|
||||
expect(getJobPriority(createJob('prep_complete'))).toBe(2);
|
||||
});
|
||||
|
||||
it('returns 3 for failed/cancelled statuses', () => {
|
||||
expect(getJobPriority(createJob('failed'))).toBe(3);
|
||||
expect(getJobPriority(createJob('cancelled'))).toBe(3);
|
||||
});
|
||||
|
||||
it('handles case insensitivity', () => {
|
||||
expect(getJobPriority(createJob('AWAITING_REVIEW'))).toBe(0);
|
||||
expect(getJobPriority(createJob('COMPLETE'))).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sortJobsByPriority', () => {
|
||||
// Helper to create job with specific date
|
||||
function createJobWithDate(status: string, createdAt: string): Job {
|
||||
return {
|
||||
@@ -505,77 +501,123 @@ describe('sortJobsByDate', () => {
|
||||
};
|
||||
}
|
||||
|
||||
it('sorts by created_at descending (newest first)', () => {
|
||||
it('sorts blocking jobs before completed jobs', () => {
|
||||
const jobs = [
|
||||
createJobWithDate('complete', '2024-01-01T12:00:00Z'),
|
||||
createJobWithDate('awaiting_review', '2024-01-01T12:00:00Z'),
|
||||
];
|
||||
const sorted = sortJobsByPriority(jobs);
|
||||
expect(sorted[0].status).toBe('awaiting_review');
|
||||
expect(sorted[1].status).toBe('complete');
|
||||
});
|
||||
|
||||
it('sorts blocking jobs before processing jobs', () => {
|
||||
const jobs = [
|
||||
createJobWithDate('rendering_video', '2024-01-01T12:00:00Z'),
|
||||
createJobWithDate('awaiting_review', '2024-01-01T12:00:00Z'),
|
||||
];
|
||||
const sorted = sortJobsByPriority(jobs);
|
||||
expect(sorted[0].status).toBe('awaiting_review');
|
||||
expect(sorted[1].status).toBe('rendering_video');
|
||||
});
|
||||
|
||||
it('sorts processing jobs before completed jobs', () => {
|
||||
const jobs = [
|
||||
createJobWithDate('complete', '2024-01-01T12:00:00Z'),
|
||||
createJobWithDate('rendering_video', '2024-01-01T12:00:00Z'),
|
||||
];
|
||||
const sorted = sortJobsByPriority(jobs);
|
||||
expect(sorted[0].status).toBe('rendering_video');
|
||||
expect(sorted[1].status).toBe('complete');
|
||||
});
|
||||
|
||||
it('sorts completed jobs before failed jobs', () => {
|
||||
const jobs = [
|
||||
createJobWithDate('failed', '2024-01-01T12:00:00Z'),
|
||||
createJobWithDate('complete', '2024-01-01T12:00:00Z'),
|
||||
];
|
||||
const sorted = sortJobsByPriority(jobs);
|
||||
expect(sorted[0].status).toBe('complete');
|
||||
expect(sorted[1].status).toBe('failed');
|
||||
});
|
||||
|
||||
it('sorts by created_at (newest first) within same priority', () => {
|
||||
const jobs = [
|
||||
createJobWithDate('complete', '2024-01-01T10:00:00Z'),
|
||||
createJobWithDate('complete', '2024-01-01T14:00:00Z'),
|
||||
createJobWithDate('complete', '2024-01-01T12:00:00Z'),
|
||||
];
|
||||
const sorted = sortJobsByDate(jobs);
|
||||
const sorted = sortJobsByPriority(jobs);
|
||||
expect(sorted[0].created_at).toBe('2024-01-01T14:00:00Z');
|
||||
expect(sorted[1].created_at).toBe('2024-01-01T12:00:00Z');
|
||||
expect(sorted[2].created_at).toBe('2024-01-01T10:00:00Z');
|
||||
});
|
||||
|
||||
it('does not use priority bucketing - all jobs sorted by date only', () => {
|
||||
const jobs = [
|
||||
createJobWithDate('complete', '2024-01-01T14:00:00Z'),
|
||||
createJobWithDate('failed', '2024-01-01T11:00:00Z'),
|
||||
createJobWithDate('awaiting_review', '2024-01-01T09:00:00Z'),
|
||||
createJobWithDate('rendering_video', '2024-01-01T12:00:00Z'),
|
||||
];
|
||||
const sorted = sortJobsByDate(jobs);
|
||||
// Pure date order, regardless of status
|
||||
expect(sorted[0].created_at).toBe('2024-01-01T14:00:00Z');
|
||||
expect(sorted[1].created_at).toBe('2024-01-01T12:00:00Z');
|
||||
expect(sorted[2].created_at).toBe('2024-01-01T11:00:00Z');
|
||||
expect(sorted[3].created_at).toBe('2024-01-01T09:00:00Z');
|
||||
});
|
||||
|
||||
it('does not mutate the original array', () => {
|
||||
const jobs = [
|
||||
createJobWithDate('complete', '2024-01-01T12:00:00Z'),
|
||||
createJobWithDate('awaiting_review', '2024-01-01T14:00:00Z'),
|
||||
createJobWithDate('awaiting_review', '2024-01-01T12:00:00Z'),
|
||||
];
|
||||
const originalOrder = [...jobs];
|
||||
sortJobsByDate(jobs);
|
||||
sortJobsByPriority(jobs);
|
||||
expect(jobs[0].status).toBe(originalOrder[0].status);
|
||||
expect(jobs[1].status).toBe(originalOrder[1].status);
|
||||
});
|
||||
|
||||
it('handles empty array', () => {
|
||||
const sorted = sortJobsByDate([]);
|
||||
const sorted = sortJobsByPriority([]);
|
||||
expect(sorted).toEqual([]);
|
||||
});
|
||||
|
||||
it('handles single job', () => {
|
||||
const jobs = [createJobWithDate('complete', '2024-01-01T12:00:00Z')];
|
||||
const sorted = sortJobsByDate(jobs);
|
||||
const sorted = sortJobsByPriority(jobs);
|
||||
expect(sorted.length).toBe(1);
|
||||
expect(sorted[0].status).toBe('complete');
|
||||
});
|
||||
|
||||
it('correctly orders a realistic job list', () => {
|
||||
const jobs = [
|
||||
createJobWithDate('complete', '2024-01-01T10:00:00Z'),
|
||||
createJobWithDate('failed', '2024-01-01T11:00:00Z'),
|
||||
createJobWithDate('awaiting_review', '2024-01-01T09:00:00Z'),
|
||||
createJobWithDate('rendering_video', '2024-01-01T12:00:00Z'),
|
||||
createJobWithDate('complete', '2024-01-01T14:00:00Z'),
|
||||
];
|
||||
const sorted = sortJobsByPriority(jobs);
|
||||
// Priority order: blocking (0), processing (1), complete (2), failed (3)
|
||||
expect(sorted[0].status).toBe('awaiting_review'); // blocking
|
||||
expect(sorted[1].status).toBe('rendering_video'); // processing
|
||||
expect(sorted[2].status).toBe('complete'); // complete, newer
|
||||
expect(sorted[2].created_at).toBe('2024-01-01T14:00:00Z');
|
||||
expect(sorted[3].status).toBe('complete'); // complete, older
|
||||
expect(sorted[3].created_at).toBe('2024-01-01T10:00:00Z');
|
||||
expect(sorted[4].status).toBe('failed'); // failed
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDisplayJobs', () => {
|
||||
// Helper: create jobs sorted by date (newest first)
|
||||
function createDateSortedJobs(jobSpecs: Array<{ status: string; date: string }>): Job[] {
|
||||
return jobSpecs
|
||||
.map((spec, i) => ({
|
||||
job_id: `job-${i}`,
|
||||
status: spec.status,
|
||||
progress: spec.status === 'complete' ? 100 : 0,
|
||||
created_at: spec.date,
|
||||
updated_at: spec.date,
|
||||
}))
|
||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
||||
// Helper: pre-sorted jobs (blocking, processing, complete, failed)
|
||||
function createSortedJobs(counts: { blocking?: number; processing?: number; complete?: number; failed?: number }): Job[] {
|
||||
const jobs: Job[] = [];
|
||||
let t = 20; // descending timestamp within each priority group
|
||||
for (let i = 0; i < (counts.blocking ?? 0); i++) {
|
||||
jobs.push({ job_id: `blocking-${i}`, status: 'awaiting_review', progress: 0, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
|
||||
}
|
||||
for (let i = 0; i < (counts.processing ?? 0); i++) {
|
||||
jobs.push({ job_id: `processing-${i}`, status: 'rendering_video', progress: 0, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
|
||||
}
|
||||
for (let i = 0; i < (counts.complete ?? 0); i++) {
|
||||
jobs.push({ job_id: `complete-${i}`, status: 'complete', progress: 100, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
|
||||
}
|
||||
for (let i = 0; i < (counts.failed ?? 0); i++) {
|
||||
jobs.push({ job_id: `failed-${i}`, status: 'failed', progress: 0, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
it('returns all jobs when fewer than display limit', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'complete', date: '2024-01-01T10:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-01T11:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-01T12:00:00Z' },
|
||||
]);
|
||||
const jobs = createSortedJobs({ complete: 3 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
|
||||
expect(displayedJobs).toHaveLength(3);
|
||||
expect(totalFetched).toBe(3);
|
||||
@@ -587,121 +629,104 @@ describe('getDisplayJobs', () => {
|
||||
expect(totalFetched).toBe(0);
|
||||
});
|
||||
|
||||
it('limits to displayLimit', () => {
|
||||
const jobs = createDateSortedJobs(
|
||||
Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
|
||||
);
|
||||
it('limits to displayLimit when no incomplete jobs', () => {
|
||||
const jobs = createSortedJobs({ complete: 10 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
|
||||
expect(displayedJobs).toHaveLength(5);
|
||||
expect(totalFetched).toBe(10);
|
||||
});
|
||||
|
||||
it('expands beyond limit when more incomplete than limit', () => {
|
||||
const jobs = createSortedJobs({ blocking: 3, processing: 4, complete: 5 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5);
|
||||
// 7 incomplete > limit of 5, so show all 7
|
||||
expect(displayedJobs).toHaveLength(7);
|
||||
expect(displayedJobs.filter(j => j.status === 'awaiting_review')).toHaveLength(3);
|
||||
expect(displayedJobs.filter(j => j.status === 'rendering_video')).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('fills remaining slots with completed when fewer incomplete than limit', () => {
|
||||
const jobs = createSortedJobs({ blocking: 1, processing: 1, complete: 10 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5);
|
||||
// 2 incomplete < 5 limit, so show 5 total (2 incomplete + 3 completed)
|
||||
expect(displayedJobs).toHaveLength(5);
|
||||
expect(displayedJobs[0].status).toBe('awaiting_review');
|
||||
expect(displayedJobs[1].status).toBe('rendering_video');
|
||||
expect(displayedJobs[2].status).toBe('complete');
|
||||
});
|
||||
|
||||
it('returns all jobs when displayLimit is -1 (All mode)', () => {
|
||||
const jobs = createDateSortedJobs(
|
||||
Array.from({ length: 22 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
|
||||
);
|
||||
const jobs = createSortedJobs({ blocking: 2, complete: 20 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1);
|
||||
expect(displayedJobs).toHaveLength(22);
|
||||
expect(totalFetched).toBe(22);
|
||||
});
|
||||
|
||||
it('preserves date sort order from input', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
|
||||
{ status: 'failed', date: '2024-01-04T12:00:00Z' },
|
||||
{ status: 'awaiting_review', date: '2024-01-02T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-05T12:00:00Z' },
|
||||
]);
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 10);
|
||||
// Should be newest first
|
||||
expect(displayedJobs[0].created_at).toBe('2024-01-05T12:00:00Z');
|
||||
expect(displayedJobs[1].created_at).toBe('2024-01-04T12:00:00Z');
|
||||
expect(displayedJobs[2].created_at).toBe('2024-01-03T12:00:00Z');
|
||||
expect(displayedJobs[3].created_at).toBe('2024-01-02T12:00:00Z');
|
||||
it('preserves sort order from input', () => {
|
||||
const jobs = createSortedJobs({ blocking: 1, processing: 1, complete: 3 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5);
|
||||
expect(displayedJobs[0].status).toBe('awaiting_review');
|
||||
expect(displayedJobs[1].status).toBe('rendering_video');
|
||||
expect(displayedJobs[2].status).toBe('complete');
|
||||
expect(displayedJobs[3].status).toBe('complete');
|
||||
expect(displayedJobs[4].status).toBe('complete');
|
||||
});
|
||||
|
||||
describe('hideCompleted filter', () => {
|
||||
it('filters out only complete and prep_complete when hideCompleted is true (keeps failed)', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'awaiting_review', date: '2024-01-05T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-04T12:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
|
||||
{ status: 'failed', date: '2024-01-02T12:00:00Z' },
|
||||
{ status: 'prep_complete', date: '2024-01-01T12:00:00Z' },
|
||||
]);
|
||||
it('filters out complete and failed jobs when hideCompleted is true', () => {
|
||||
const jobs = createSortedJobs({ blocking: 1, processing: 2, complete: 5, failed: 3 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1, true);
|
||||
expect(totalFetched).toBe(5);
|
||||
expect(displayedJobs).toHaveLength(3); // blocking + processing + failed
|
||||
expect(displayedJobs.some(j => j.status === 'failed')).toBe(true);
|
||||
expect(displayedJobs.some(j => j.status === 'complete')).toBe(false);
|
||||
expect(displayedJobs.some(j => j.status === 'prep_complete')).toBe(false);
|
||||
expect(totalFetched).toBe(11);
|
||||
expect(displayedJobs).toHaveLength(3);
|
||||
expect(displayedJobs.every(j => j.status === 'awaiting_review' || j.status === 'rendering_video')).toBe(true);
|
||||
});
|
||||
|
||||
it('respects display limit after filtering', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'rendering_video', date: '2024-01-10T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-09T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-08T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-07T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-06T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-05T12:00:00Z' },
|
||||
{ status: 'rendering_video', date: '2024-01-04T12:00:00Z' },
|
||||
...Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T10:00:00Z` })),
|
||||
]);
|
||||
const jobs = createSortedJobs({ blocking: 2, processing: 5, complete: 10 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5, true);
|
||||
// 7 non-complete jobs after filtering, but limit is 5
|
||||
expect(displayedJobs).toHaveLength(5);
|
||||
// 7 incomplete jobs, all visible since incomplete count (7) > limit (5)
|
||||
expect(displayedJobs).toHaveLength(7);
|
||||
});
|
||||
|
||||
it('returns empty when all jobs are complete and hideCompleted is true', () => {
|
||||
const jobs = createDateSortedJobs(
|
||||
Array.from({ length: 10 }, (_, i) => ({ status: 'complete', date: `2024-01-${String(i + 1).padStart(2, '0')}T12:00:00Z` }))
|
||||
);
|
||||
const jobs = createSortedJobs({ complete: 10 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5, true);
|
||||
expect(displayedJobs).toHaveLength(0);
|
||||
expect(totalFetched).toBe(10);
|
||||
});
|
||||
|
||||
it('does not filter when hideCompleted is false', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'awaiting_review', date: '2024-01-04T12:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-03T12:00:00Z' },
|
||||
{ status: 'complete', date: '2024-01-02T12:00:00Z' },
|
||||
{ status: 'failed', date: '2024-01-01T12:00:00Z' },
|
||||
]);
|
||||
const jobs = createSortedJobs({ blocking: 1, complete: 5, failed: 2 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, -1, false);
|
||||
expect(displayedJobs).toHaveLength(4);
|
||||
expect(displayedJobs).toHaveLength(8);
|
||||
});
|
||||
|
||||
it('defaults to showing all when hideCompleted is omitted', () => {
|
||||
const jobs = createDateSortedJobs([
|
||||
{ status: 'complete', date: '2024-01-02T12:00:00Z' },
|
||||
{ status: 'failed', date: '2024-01-01T12:00:00Z' },
|
||||
]);
|
||||
const jobs = createSortedJobs({ complete: 5, failed: 2 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, -1);
|
||||
expect(displayedJobs).toHaveLength(2);
|
||||
expect(displayedJobs).toHaveLength(7);
|
||||
});
|
||||
});
|
||||
|
||||
it('core bug fix: recently failed job appears at top of list', () => {
|
||||
// The original bug: a newly failed job was invisible because priority sorting
|
||||
// put all 45 complete jobs above it, and the limit of 10 truncated it.
|
||||
// With date-based sorting, the newest job (failed) appears first.
|
||||
const jobs = sortJobsByDate([
|
||||
{ job_id: 'new-failed', status: 'failed', progress: 0, created_at: '2024-01-10T15:00:00Z', updated_at: '2024-01-10T15:00:00Z' },
|
||||
...Array.from({ length: 45 }, (_, i) => ({
|
||||
job_id: `complete-${i}`,
|
||||
status: 'complete',
|
||||
progress: 100,
|
||||
created_at: `2024-01-${String(10 - Math.floor(i / 5)).padStart(2, '0')}T${String(12 - (i % 5)).padStart(2, '0')}:00:00Z`,
|
||||
updated_at: '2024-01-01T00:00:00Z',
|
||||
})),
|
||||
it('core bug: old incomplete job visible even when recent jobs are all completed', () => {
|
||||
// Simulate the bug scenario: 5 recent completed jobs + 1 older blocking job
|
||||
// With old behavior (LIMIT 5 at query), the blocking job would never be fetched.
|
||||
// With new behavior, all 6 are fetched and display limit of 5 expands to show blocking.
|
||||
const jobs = sortJobsByPriority([
|
||||
{ job_id: 'old-blocking', status: 'awaiting_review', progress: 0, created_at: '2024-01-01T01:00:00Z', updated_at: '2024-01-01T01:00:00Z' },
|
||||
{ job_id: 'new-1', status: 'complete', progress: 100, created_at: '2024-01-10T01:00:00Z', updated_at: '2024-01-10T01:00:00Z' },
|
||||
{ job_id: 'new-2', status: 'complete', progress: 100, created_at: '2024-01-09T01:00:00Z', updated_at: '2024-01-09T01:00:00Z' },
|
||||
{ job_id: 'new-3', status: 'complete', progress: 100, created_at: '2024-01-08T01:00:00Z', updated_at: '2024-01-08T01:00:00Z' },
|
||||
{ job_id: 'new-4', status: 'complete', progress: 100, created_at: '2024-01-07T01:00:00Z', updated_at: '2024-01-07T01:00:00Z' },
|
||||
{ job_id: 'new-5', status: 'complete', progress: 100, created_at: '2024-01-06T01:00:00Z', updated_at: '2024-01-06T01:00:00Z' },
|
||||
]);
|
||||
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 10);
|
||||
// The failed job should be first (newest)
|
||||
expect(displayedJobs[0].job_id).toBe('new-failed');
|
||||
expect(displayedJobs[0].status).toBe('failed');
|
||||
expect(displayedJobs).toHaveLength(10);
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5);
|
||||
// The blocking job must be visible
|
||||
const blockingJobs = displayedJobs.filter(j => j.status === 'awaiting_review');
|
||||
expect(blockingJobs).toHaveLength(1);
|
||||
expect(blockingJobs[0].job_id).toBe('old-blocking');
|
||||
// Should show 5 total (1 incomplete + 4 completed, since limit is 5 and max(5, 1) = 5)
|
||||
expect(displayedJobs).toHaveLength(5);
|
||||
});
|
||||
});
|
||||
@@ -1534,9 +1534,8 @@ function AdminJobsPageContent() {
|
||||
This will permanently delete:
|
||||
<ul className="list-disc list-inside mt-2 space-y-1">
|
||||
<li>YouTube video (if uploaded)</li>
|
||||
<li>Dropbox folder (if uploaded)</li>
|
||||
<li>Dropbox folder (frees brand code for reuse)</li>
|
||||
<li>Google Drive files (if uploaded)</li>
|
||||
<li>Brand code (recycled for reuse if cleanup succeeds)</li>
|
||||
</ul>
|
||||
<br />
|
||||
The job record will be preserved with a timestamp marking when outputs were deleted.
|
||||
@@ -1654,33 +1653,6 @@ function AdminJobsPageContent() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Brand Code */}
|
||||
{deleteOutputsResult.deleted_services.brand_code && (
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className={`w-2 h-2 rounded-full mt-1.5 ${
|
||||
deleteOutputsResult.deleted_services.brand_code.status === "recycled"
|
||||
? "bg-green-500"
|
||||
: deleteOutputsResult.deleted_services.brand_code.status === "skipped"
|
||||
? "bg-gray-400"
|
||||
: "bg-red-500"
|
||||
}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm">Brand Code</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{deleteOutputsResult.deleted_services.brand_code.status === "recycled" && (
|
||||
<>Recycled <code className="text-xs bg-muted px-1 rounded">{deleteOutputsResult.deleted_services.brand_code.code}</code> for reuse</>
|
||||
)}
|
||||
{deleteOutputsResult.deleted_services.brand_code.status === "skipped" && (
|
||||
<>{deleteOutputsResult.deleted_services.brand_code.reason}</>
|
||||
)}
|
||||
{deleteOutputsResult.deleted_services.brand_code.status === "failed" && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.brand_code.error}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{deleteOutputsResult.cleared_state_data.length > 0 && (
|
||||
|
||||
@@ -22,16 +22,6 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
@@ -44,7 +34,6 @@ import {
|
||||
CreditCard,
|
||||
Briefcase,
|
||||
Clock,
|
||||
Trash2,
|
||||
} from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
@@ -58,9 +47,6 @@ export default function AdminUserDetailPage() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [actionLoading, setActionLoading] = useState(false)
|
||||
|
||||
// Delete dialog
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
|
||||
// Credit dialog
|
||||
const [creditDialogOpen, setCreditDialogOpen] = useState(false)
|
||||
const [creditAmount, setCreditAmount] = useState("")
|
||||
@@ -156,28 +142,6 @@ export default function AdminUserDetailPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteUser = async () => {
|
||||
if (!user) return
|
||||
|
||||
try {
|
||||
setActionLoading(true)
|
||||
await adminApi.deleteUser(email)
|
||||
toast({
|
||||
title: "User Deleted",
|
||||
description: `User ${email} has been permanently deleted`,
|
||||
})
|
||||
router.push("/admin/users")
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: err.message || "Failed to delete user",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setActionLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const formatDate = (dateStr?: string) => {
|
||||
if (!dateStr) return "Never"
|
||||
return new Date(dateStr).toLocaleString()
|
||||
@@ -265,16 +229,6 @@ export default function AdminUserDetailPage() {
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{user.role !== "admin" && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => setDeleteDialogOpen(true)}
|
||||
disabled={actionLoading}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Delete User
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Stats Grid */}
|
||||
@@ -484,31 +438,6 @@ export default function AdminUserDetailPage() {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete User Confirmation Dialog */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete User</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to permanently delete user {email}? This action
|
||||
cannot be undone. All sessions and authentication data will be removed.
|
||||
Jobs will be preserved as historical records.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteUser}
|
||||
disabled={actionLoading}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{actionLoading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
Delete User
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -15,16 +15,15 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Music2, RefreshCw, Loader2, Moon, Sun, Eye, EyeOff, Gift, X, Shield, ShieldOff } from "lucide-react"
|
||||
import { sortJobsByDate, getDisplayJobs } from "@/lib/job-status"
|
||||
import { Music2, RefreshCw, Loader2, Moon, Sun, Eye, EyeOff } from "lucide-react"
|
||||
import { sortJobsByPriority, getDisplayJobs } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
import { JobSubmission } from "@/components/job/JobSubmission"
|
||||
import { AuthStatus } from "@/components/auth"
|
||||
import { AutoProcessor } from "@/components/AutoProcessor"
|
||||
import { VersionFooter } from "@/components/version-footer"
|
||||
import { PushNotificationPrompt } from "@/components/push-notification-prompt"
|
||||
import { FeedbackDialog } from "@/components/feedback/FeedbackDialog"
|
||||
import { useTheme } from "@/lib/theme"
|
||||
import {
|
||||
Tooltip,
|
||||
@@ -54,26 +53,14 @@ function AppPageContent() {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-karaoke-hide-completed") === "true"
|
||||
})
|
||||
const [showAdminControls, setShowAdminControls] = useState<boolean>(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-karaoke-admin-controls") === "true"
|
||||
})
|
||||
const [feedbackBannerDismissed, setFeedbackBannerDismissed] = useState(false)
|
||||
const [showFeedbackDialog, setShowFeedbackDialog] = useState(false)
|
||||
|
||||
// Check if user is admin (for exclude_test parameter)
|
||||
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
|
||||
|
||||
// Filter out in-progress search jobs (managed by the guided flow, not standalone cards)
|
||||
const visibleJobs = useMemo(
|
||||
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
|
||||
[allJobs]
|
||||
)
|
||||
|
||||
// Derive displayed jobs from visibleJobs + display limit + filter (instant, no re-fetch)
|
||||
// Derive displayed jobs from allJobs + display limit + filter (instant, no re-fetch)
|
||||
const { displayedJobs: jobs, totalFetched } = useMemo(
|
||||
() => getDisplayJobs(visibleJobs, jobLimit, hideCompleted),
|
||||
[visibleJobs, jobLimit, hideCompleted]
|
||||
() => getDisplayJobs(allJobs, jobLimit, hideCompleted),
|
||||
[allJobs, jobLimit, hideCompleted]
|
||||
)
|
||||
|
||||
// Memoize loadJobs for use with visibility refresh
|
||||
@@ -91,8 +78,8 @@ function AppPageContent() {
|
||||
fields: 'summary',
|
||||
hide_completed: hideCompleted,
|
||||
})
|
||||
// Sort by creation date (newest first)
|
||||
setAllJobs(sortJobsByDate(data))
|
||||
// Sort: blocking jobs first, then processing, then completed
|
||||
setAllJobs(sortJobsByPriority(data))
|
||||
} catch (err: any) {
|
||||
// Don't log auth errors - user just needs to authenticate
|
||||
if (err?.status !== 401) {
|
||||
@@ -210,30 +197,6 @@ function AppPageContent() {
|
||||
<RefreshCw className={`w-4 h-4 sm:mr-2 ${isLoadingJobs ? 'animate-spin' : ''}`} />
|
||||
<span className="hidden sm:inline">Refresh</span>
|
||||
</Button>
|
||||
{isAdmin && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const next = !showAdminControls
|
||||
setShowAdminControls(next)
|
||||
localStorage.setItem("nomad-karaoke-admin-controls", String(next))
|
||||
}}
|
||||
className={`min-h-[40px] px-2 sm:px-3 ${showAdminControls ? 'text-amber-400' : ''}`}
|
||||
style={showAdminControls ? undefined : { color: 'var(--text-muted)' }}
|
||||
>
|
||||
{showAdminControls ? <Shield className="w-4 h-4" /> : <ShieldOff className="w-4 h-4" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
<p>{showAdminControls ? "Hide admin controls" : "Show admin controls"}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
<AuthStatus />
|
||||
{mounted && (
|
||||
<TooltipProvider>
|
||||
@@ -263,64 +226,21 @@ function AppPageContent() {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Feedback dialog */}
|
||||
<FeedbackDialog
|
||||
open={showFeedbackDialog}
|
||||
onClose={() => setShowFeedbackDialog(false)}
|
||||
/>
|
||||
|
||||
<main className="px-4 pt-24 pb-8 space-y-6">
|
||||
{/* Push notification prompt - shows once when appropriate */}
|
||||
<PushNotificationPrompt />
|
||||
|
||||
{/* Feedback-for-credits banner */}
|
||||
{user?.feedback_eligible && !feedbackBannerDismissed && (
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border px-4 py-3"
|
||||
style={{
|
||||
borderColor: 'var(--accent)',
|
||||
backgroundColor: 'rgba(34, 197, 94, 0.05)',
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<Gift className="w-5 h-5 text-green-500 shrink-0" />
|
||||
<p className="text-sm" style={{ color: 'var(--text)' }}>
|
||||
<strong>Earn 2 free credits!</strong>{' '}
|
||||
<span style={{ color: 'var(--text-muted)' }}>
|
||||
Share your feedback on the karaoke creation experience.
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setShowFeedbackDialog(true)}
|
||||
className="text-green-500 border-green-500/30 hover:bg-green-500/10"
|
||||
>
|
||||
Give Feedback
|
||||
</Button>
|
||||
<button
|
||||
onClick={() => setFeedbackBannerDismissed(true)}
|
||||
className="p-1 rounded hover:bg-secondary transition-colors"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid lg:grid-cols-2 gap-8">
|
||||
{/* Submit Job Card */}
|
||||
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
|
||||
<CardHeader>
|
||||
<CardTitle style={{ color: 'var(--text)' }}>Create Karaoke Video</CardTitle>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
Turn any song into a karaoke video with synced lyrics
|
||||
Upload an audio file, provide a YouTube URL, or search for audio by artist & title
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
<JobSubmission onJobCreated={loadJobs} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -387,7 +307,7 @@ function AppPageContent() {
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{jobs.map((job) => (
|
||||
<JobCard key={job.job_id} job={job} onRefresh={loadJobs} showAdminControls={isAdmin && showAdminControls} />
|
||||
<JobCard key={job.job_id} job={job} onRefresh={loadJobs} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type React from "react"
|
||||
import type { Metadata } from "next"
|
||||
import localFont from "next/font/local"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { TenantProvider } from "@/components/tenant-provider"
|
||||
import { ImpersonationBannerWrapper } from "@/components/impersonation-banner-wrapper"
|
||||
@@ -8,14 +7,6 @@ import { ServiceWorkerRegistration } from "@/components/service-worker-registrat
|
||||
import { GoogleAnalytics } from "@/components/google-analytics"
|
||||
import "./globals.css"
|
||||
|
||||
// AvenirNext Bold - matches the font used in actual Nomad theme title card generation
|
||||
// (karaoke_gen/resources/AvenirNext-Bold.ttf)
|
||||
const titleCardFont = localFont({
|
||||
src: "../public/fonts/AvenirNext-Bold.ttf",
|
||||
display: "swap",
|
||||
variable: "--font-title-card",
|
||||
})
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Nomad Karaoke: Generator",
|
||||
description: "Generate professional karaoke videos with AI-powered vocal separation and synchronized lyrics",
|
||||
@@ -37,7 +28,7 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body className={`font-sans antialiased ${titleCardFont.variable}`} style={{ background: 'var(--bg)', color: 'var(--text)' }}>
|
||||
<body className="font-sans antialiased" style={{ background: 'var(--bg)', color: 'var(--text)' }}>
|
||||
<GoogleAnalytics />
|
||||
<ServiceWorkerRegistration />
|
||||
<ThemeProvider
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Image from 'next/image';
|
||||
import {
|
||||
@@ -8,8 +8,10 @@ import {
|
||||
Sparkles,
|
||||
Video,
|
||||
Youtube,
|
||||
ChevronDown,
|
||||
Check,
|
||||
Gift,
|
||||
MessageSquare,
|
||||
Mail,
|
||||
Loader2,
|
||||
Search,
|
||||
@@ -19,7 +21,7 @@ import {
|
||||
FileVideo,
|
||||
CreditCard,
|
||||
} from 'lucide-react';
|
||||
import { api, setAccessToken, getAccessToken, CreditPackage } from '@/lib/api';
|
||||
import { api, setAccessToken, getAccessToken, CreditPackage, BetaEnrollResponse } from '@/lib/api';
|
||||
import { AuthDialog } from '@/components/auth/AuthDialog';
|
||||
import { WarmingUpLoader } from '@/components/WarmingUpLoader';
|
||||
import { ThemeToggle } from '@/components/ThemeToggle';
|
||||
@@ -64,6 +66,16 @@ export default function LandingPage() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Beta form state
|
||||
const [showBetaForm, setShowBetaForm] = useState(false);
|
||||
const [betaEmail, setBetaEmail] = useState('');
|
||||
const [betaPromise, setBetaPromise] = useState('');
|
||||
const [betaAccept, setBetaAccept] = useState(false);
|
||||
const [betaLoading, setBetaLoading] = useState(false);
|
||||
const [betaError, setBetaError] = useState<string | null>(null);
|
||||
const [betaSuccess, setBetaSuccess] = useState(false);
|
||||
const [betaWillRedirect, setBetaWillRedirect] = useState(false);
|
||||
|
||||
// Made For You form state
|
||||
const [mfyArtist, setMfyArtist] = useState('');
|
||||
const [mfyTitle, setMfyTitle] = useState('');
|
||||
@@ -77,6 +89,18 @@ export default function LandingPage() {
|
||||
// Auth dialog state
|
||||
const [showAuthDialog, setShowAuthDialog] = useState(false);
|
||||
|
||||
// Ref for redirect timeout cleanup
|
||||
const redirectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// Cleanup timeout on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (redirectTimeoutRef.current) {
|
||||
clearTimeout(redirectTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Check if already logged in and redirect to app
|
||||
useEffect(() => {
|
||||
const token = getAccessToken();
|
||||
@@ -135,6 +159,55 @@ export default function LandingPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Handle beta enrollment
|
||||
const handleBetaEnroll = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBetaError(null);
|
||||
|
||||
// Validation
|
||||
if (!betaEmail) {
|
||||
setBetaError('Please enter your email address');
|
||||
return;
|
||||
}
|
||||
if (!betaAccept) {
|
||||
setBetaError('Please accept the corrections work agreement');
|
||||
return;
|
||||
}
|
||||
if (!betaPromise || betaPromise.length < 10) {
|
||||
setBetaError('Please write a sentence about a song you want to make into karaoke');
|
||||
return;
|
||||
}
|
||||
|
||||
setBetaLoading(true);
|
||||
|
||||
try {
|
||||
const response: BetaEnrollResponse = await api.enrollBetaTester(
|
||||
betaEmail,
|
||||
betaPromise,
|
||||
betaAccept
|
||||
);
|
||||
|
||||
// If we got a session token, store it and redirect to main app
|
||||
if (response.session_token) {
|
||||
setAccessToken(response.session_token);
|
||||
setBetaSuccess(true);
|
||||
setBetaWillRedirect(true);
|
||||
// Redirect to main app after showing success message
|
||||
redirectTimeoutRef.current = setTimeout(() => {
|
||||
router.push('/app');
|
||||
}, 2000);
|
||||
} else {
|
||||
// No token means email verification needed
|
||||
setBetaSuccess(true);
|
||||
setBetaWillRedirect(false);
|
||||
}
|
||||
} catch (err) {
|
||||
setBetaError(err instanceof Error ? err.message : 'Failed to enroll in beta program');
|
||||
} finally {
|
||||
setBetaLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle Made For You checkout
|
||||
const handleMadeForYouSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -212,7 +285,7 @@ export default function LandingPage() {
|
||||
</nav>
|
||||
|
||||
{/* Hero Section */}
|
||||
<section className="pt-32 pb-6 px-4">
|
||||
<section className="pt-32 pb-16 px-4">
|
||||
<div className="max-w-4xl mx-auto text-center">
|
||||
<h1 className="text-4xl sm:text-5xl md:text-6xl font-extrabold mb-6 leading-tight">
|
||||
Create a <span className="gradient-text">Karaoke Video</span> for Any Song
|
||||
@@ -225,15 +298,15 @@ export default function LandingPage() {
|
||||
{/* Two pricing options */}
|
||||
<div className="flex flex-col sm:flex-row items-center justify-center gap-6 mb-6">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<button
|
||||
onClick={() => setShowAuthDialog(true)}
|
||||
<a
|
||||
href="#pricing"
|
||||
className="inline-flex items-center gap-2 bg-primary-500 hover:bg-primary-600 text-white font-semibold px-8 py-4 rounded-xl transition-all btn-glow"
|
||||
>
|
||||
<Video className="w-5 h-5" />
|
||||
Create It Yourself
|
||||
<span className="ml-1 px-2 py-0.5 bg-white/20 rounded-full text-sm">$5</span>
|
||||
</button>
|
||||
<span className="text-green-400 text-sm">2 free credits included - no payment required</span>
|
||||
</a>
|
||||
<span className="text-dark-400 text-sm">Review lyrics yourself in ~10 min</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<a
|
||||
@@ -242,12 +315,19 @@ export default function LandingPage() {
|
||||
>
|
||||
<Gift className="w-5 h-5" />
|
||||
We'll Make It For You
|
||||
<span className="ml-1 px-2 py-0.5 bg-yellow-500/20 rounded-full text-sm">$50</span>
|
||||
<span className="ml-1 px-2 py-0.5 bg-yellow-500/20 rounded-full text-sm">$15</span>
|
||||
</a>
|
||||
<span className="text-yellow-400/70 text-sm">We handle everything, delivered in 24h</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a
|
||||
href="#beta"
|
||||
className="inline-flex items-center gap-1 text-primary-400 hover:text-primary-300 text-sm font-medium transition-colors"
|
||||
>
|
||||
Or try it free as a beta tester
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -258,7 +338,7 @@ export default function LandingPage() {
|
||||
<div className="aspect-video">
|
||||
<iframe
|
||||
className="w-full h-full rounded-xl"
|
||||
src="https://www.youtube.com/embed/RLkIEHGwFcU"
|
||||
src="https://www.youtube.com/embed/uvKtLOUiqz8?si=K06hw2B-QJ81Loeo"
|
||||
title="Nomad Karaoke Demo"
|
||||
frameBorder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
@@ -290,29 +370,6 @@ export default function LandingPage() {
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Full Tutorial Video */}
|
||||
<div className="mt-12 text-center">
|
||||
<h3 className="text-xl font-semibold mb-2">Want a deeper walkthrough?</h3>
|
||||
<p className="text-dark-400 text-sm mb-6 max-w-xl mx-auto">
|
||||
Watch the full tutorial to see every step in detail — from creating a job to downloading your finished video.
|
||||
</p>
|
||||
<div className="max-w-3xl mx-auto">
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-2xl p-2 overflow-hidden">
|
||||
<div className="aspect-video">
|
||||
<iframe
|
||||
className="w-full h-full rounded-xl"
|
||||
src="https://www.youtube.com/embed/-dI3r7qXo3A"
|
||||
title="Nomad Karaoke Full Tutorial"
|
||||
frameBorder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
referrerPolicy="strict-origin-when-cross-origin"
|
||||
allowFullScreen
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -346,20 +403,20 @@ export default function LandingPage() {
|
||||
Here's what the process looks like at each step
|
||||
</p>
|
||||
<div className="grid md:grid-cols-2 gap-8">
|
||||
{/* Job Creation Screenshot */}
|
||||
{/* Job Dashboard Screenshot */}
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-xl overflow-hidden">
|
||||
<div className="aspect-video bg-dark-900 relative">
|
||||
<Image
|
||||
src="/screenshots/job-dashboard.avif"
|
||||
alt="Guided job creation flow with artist and title entry"
|
||||
alt="Job Dashboard showing karaoke video projects with status indicators"
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold mb-1">Create Your Video</h3>
|
||||
<p className="text-dark-400 text-sm">Enter any song and we find the best audio automatically</p>
|
||||
<h3 className="font-semibold mb-1">Job Dashboard</h3>
|
||||
<p className="text-dark-400 text-sm">Track progress of all your karaoke video projects</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -368,15 +425,15 @@ export default function LandingPage() {
|
||||
<div className="aspect-video bg-dark-900 relative">
|
||||
<Image
|
||||
src="/screenshots/lyrics-review.avif"
|
||||
alt="Lyrics review with synced lyrics alongside reference lyrics for correction"
|
||||
alt="Lyrics Review UI with word-by-word editing and timing controls"
|
||||
fill
|
||||
className="object-cover object-top"
|
||||
className="object-cover"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold mb-1">Review Lyrics</h3>
|
||||
<p className="text-dark-400 text-sm">Compare synced lyrics with references and fix any errors</p>
|
||||
<h3 className="font-semibold mb-1">Lyrics Review</h3>
|
||||
<p className="text-dark-400 text-sm">Correct any transcription errors before generating your video</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -385,15 +442,15 @@ export default function LandingPage() {
|
||||
<div className="aspect-video bg-dark-900 relative">
|
||||
<Image
|
||||
src="/screenshots/instrumental-review.avif"
|
||||
alt="Instrumental review with waveform visualization and backing vocal options"
|
||||
alt="Instrumental Selection UI with audio player and backing vocals options"
|
||||
fill
|
||||
className="object-cover object-top"
|
||||
className="object-cover"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold mb-1">Choose Your Instrumental</h3>
|
||||
<p className="text-dark-400 text-sm">Listen to audio options and pick the best backing track</p>
|
||||
<h3 className="font-semibold mb-1">Instrumental Selection</h3>
|
||||
<p className="text-dark-400 text-sm">Pick the sound that works best for your karaoke</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -402,41 +459,127 @@ export default function LandingPage() {
|
||||
<div className="aspect-video bg-dark-900 relative">
|
||||
<Image
|
||||
src="/screenshots/example-output.avif"
|
||||
alt="Completed karaoke job with download options for 4K, 720p, CDG, and more"
|
||||
alt="Example karaoke video output with synchronized lyrics"
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold mb-1">Download & Share</h3>
|
||||
<p className="text-dark-400 text-sm">Get your 4K video, 720p, CDG, and more in minutes</p>
|
||||
<h3 className="font-semibold mb-1">Final Video</h3>
|
||||
<p className="text-dark-400 text-sm">4K karaoke video ready for your next singing session</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Beta Tester Program */}
|
||||
<section id="beta" className="py-12 px-4">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<div className="bg-gradient-to-r from-pink-500/10 to-purple-500/10 border border-primary/30 rounded-2xl p-8 text-center">
|
||||
<div className="inline-flex items-center gap-2 bg-primary-500/20 text-primary-400 px-4 py-2 rounded-full text-sm font-medium mb-4">
|
||||
<Gift className="w-4 h-4" />
|
||||
Beta Tester Program
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold mb-3">Try It Free!</h3>
|
||||
<p className="text-dark-300 mb-6">
|
||||
Help us improve by testing the tool and sharing your feedback. Beta testers get{' '}
|
||||
<span className="text-green-400 font-semibold">up to 5 free karaoke videos</span>{' '}
|
||||
in exchange for providing feedback on each one.
|
||||
</p>
|
||||
|
||||
{!showBetaForm && !betaSuccess && (
|
||||
<button
|
||||
onClick={() => setShowBetaForm(true)}
|
||||
className="inline-flex items-center gap-2 bg-primary-500 hover:bg-primary-600 text-white font-semibold px-6 py-3 rounded-xl transition-all btn-glow"
|
||||
>
|
||||
Join Beta Program
|
||||
<MessageSquare className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{showBetaForm && !betaSuccess && (
|
||||
<form onSubmit={handleBetaEnroll} className="mt-6 text-left space-y-4">
|
||||
<div>
|
||||
<label htmlFor="beta-email" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
Email address
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
id="beta-email"
|
||||
value={betaEmail}
|
||||
onChange={(e) => setBetaEmail(e.target.value)}
|
||||
placeholder="you@example.com"
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary text-foreground placeholder:text-muted-foreground"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="beta-promise" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
What song do you want to make into karaoke?
|
||||
</label>
|
||||
<textarea
|
||||
id="beta-promise"
|
||||
value={betaPromise}
|
||||
onChange={(e) => setBetaPromise(e.target.value)}
|
||||
placeholder="Tell us about a song you'd love to sing..."
|
||||
rows={3}
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary text-foreground placeholder:text-muted-foreground resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="beta-accept"
|
||||
checked={betaAccept}
|
||||
onChange={(e) => setBetaAccept(e.target.checked)}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary text-primary focus:ring-primary"
|
||||
/>
|
||||
<label htmlFor="beta-accept" className="text-sm text-muted-foreground">
|
||||
I understand that I'll need to review and correct any lyrics transcription errors, and provide feedback after each video
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{betaError && (
|
||||
<p className="text-red-400 text-sm">{betaError}</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={betaLoading}
|
||||
className="w-full bg-primary-500 hover:bg-primary-600 disabled:bg-primary-500/50 text-white font-semibold py-3 rounded-xl transition-all btn-glow flex items-center justify-center gap-2"
|
||||
>
|
||||
{betaLoading ? 'Enrolling...' : 'Get My Free Credit'}
|
||||
{!betaLoading && <Gift className="w-5 h-5" />}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{betaSuccess && (
|
||||
<div className="mt-6 p-4 bg-green-500/20 border border-green-500/30 rounded-xl">
|
||||
<p className="text-green-400 font-semibold">
|
||||
Welcome to the beta program!{' '}
|
||||
{betaWillRedirect
|
||||
? 'Redirecting to the app...'
|
||||
: 'Check your email for a sign-in link.'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Pricing */}
|
||||
<section id="pricing" className="py-20 px-4">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-center mb-4">Simple Pricing</h2>
|
||||
<p className="text-dark-400 text-center mb-4 max-w-xl mx-auto">
|
||||
Start with 2 free credits, then buy more to save more.
|
||||
<p className="text-dark-400 text-center mb-12 max-w-xl mx-auto">
|
||||
One credit = one karaoke video. Buy more to save more.
|
||||
</p>
|
||||
|
||||
<div className="bg-green-500/10 border border-green-500/30 rounded-2xl p-6 text-center mb-10 max-w-sm mx-auto">
|
||||
<div className="text-sm text-green-400 font-medium mb-1">Every new account includes</div>
|
||||
<div className="text-4xl font-bold text-green-400 mb-1">2 Free Credits</div>
|
||||
<div className="text-sm text-dark-400 mb-4">No payment required</div>
|
||||
<button
|
||||
onClick={() => setShowAuthDialog(true)}
|
||||
className="inline-flex items-center gap-2 bg-green-500 hover:bg-green-600 text-white font-semibold px-6 py-3 rounded-xl transition-all"
|
||||
>
|
||||
Sign Up Free
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Package Selection */}
|
||||
{packagesLoading && (
|
||||
<WarmingUpLoader className="py-8" />
|
||||
@@ -549,7 +692,7 @@ export default function LandingPage() {
|
||||
<h2 className="text-3xl font-bold mb-4">We'll Make It For You</h2>
|
||||
<p className="text-dark-400 max-w-2xl mx-auto mb-4">
|
||||
Don't want to use the Generator and review the lyrics yourself? No problem.
|
||||
Tell us the song, pay $50, and we'll deliver your karaoke video within 24 hours.
|
||||
Tell us the song, pay $15, and we'll deliver your karaoke video within 24 hours.
|
||||
</p>
|
||||
<p className="text-dark-500 text-sm max-w-xl mx-auto">
|
||||
Don't want to spend 10 minutes reviewing lyrics? For just $10 more than DIY, we handle everything.
|
||||
@@ -644,7 +787,7 @@ export default function LandingPage() {
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-2xl p-6 sm:p-8">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h3 className="text-xl font-semibold">Order a Video</h3>
|
||||
<div className="text-2xl font-bold text-primary-400">$50</div>
|
||||
<div className="text-2xl font-bold text-primary-400">$15</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleMadeForYouSubmit} className="space-y-5">
|
||||
@@ -794,7 +937,7 @@ export default function LandingPage() {
|
||||
) : (
|
||||
<>
|
||||
<CreditCard className="w-5 h-5" />
|
||||
Pay $50 & Order
|
||||
Pay $15 & Order
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* Tests for AdminJobActions component
|
||||
*/
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { AdminJobActions } from '../job/AdminJobActions'
|
||||
import { Job } from '@/lib/api'
|
||||
|
||||
// Mock the API module
|
||||
jest.mock('@/lib/api', () => ({
|
||||
adminApi: {
|
||||
resetJob: jest.fn(),
|
||||
deleteJobOutputs: jest.fn(),
|
||||
regenerateScreens: jest.fn(),
|
||||
restartJob: jest.fn(),
|
||||
overrideAudioSource: jest.fn(),
|
||||
deleteJob: jest.fn(),
|
||||
}
|
||||
}))
|
||||
|
||||
describe('AdminJobActions', () => {
|
||||
const mockOnRefresh = jest.fn()
|
||||
|
||||
const mockJob: Job = {
|
||||
job_id: '123',
|
||||
status: 'complete',
|
||||
progress: 100,
|
||||
created_at: '2025-01-01T00:00:00Z',
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders all admin action buttons', () => {
|
||||
render(<AdminJobActions job={mockJob} onRefresh={mockOnRefresh} />)
|
||||
|
||||
// Reset buttons
|
||||
expect(screen.getByText('Audio')).toBeInTheDocument()
|
||||
expect(screen.getByText('Review')).toBeInTheDocument()
|
||||
expect(screen.getByText('Reprocess')).toBeInTheDocument()
|
||||
|
||||
// Other action buttons
|
||||
expect(screen.getByText('Del Outputs')).toBeInTheDocument()
|
||||
expect(screen.getByText('Regen Screens')).toBeInTheDocument()
|
||||
expect(screen.getByText('Full Restart')).toBeInTheDocument()
|
||||
expect(screen.getByText('Audio Search')).toBeInTheDocument()
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders Reset label', () => {
|
||||
render(<AdminJobActions job={mockJob} onRefresh={mockOnRefresh} />)
|
||||
|
||||
expect(screen.getByText('Reset:')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('stops event propagation on click', () => {
|
||||
const { container } = render(<AdminJobActions job={mockJob} onRefresh={mockOnRefresh} />)
|
||||
|
||||
const wrapper = container.firstChild as HTMLElement
|
||||
const event = new MouseEvent('click', { bubbles: true })
|
||||
const stopPropagation = jest.spyOn(event, 'stopPropagation')
|
||||
|
||||
wrapper.dispatchEvent(event)
|
||||
expect(stopPropagation).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -10,7 +10,7 @@ import { Job } from '@/lib/api'
|
||||
jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
retryJob: jest.fn(),
|
||||
deleteJob: jest.fn(),
|
||||
cancelJob: jest.fn(),
|
||||
}
|
||||
}))
|
||||
|
||||
@@ -42,7 +42,7 @@ describe('JobActions', () => {
|
||||
expect(screen.getByText('Retry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show retry button for cancelled jobs (legacy status)', () => {
|
||||
it('shows retry button for cancelled jobs', () => {
|
||||
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
@@ -51,8 +51,7 @@ describe('JobActions', () => {
|
||||
/>
|
||||
)
|
||||
|
||||
// Cancelled is no longer retryable - cancel now deletes the job
|
||||
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Retry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show retry button for pending jobs', () => {
|
||||
@@ -92,8 +91,8 @@ describe('JobActions', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Delete button visibility', () => {
|
||||
it('shows delete button for pending jobs', () => {
|
||||
describe('Cancel button visibility', () => {
|
||||
it('shows cancel button for pending jobs', () => {
|
||||
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
@@ -102,10 +101,10 @@ describe('JobActions', () => {
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument()
|
||||
expect(screen.getByText('Cancel')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show delete button for failed jobs', () => {
|
||||
it('does not show cancel button for failed jobs', () => {
|
||||
const failedJob = { ...baseJob, status: 'failed' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
@@ -114,24 +113,24 @@ describe('JobActions', () => {
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Delete')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Cancel')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show delete button for complete jobs', () => {
|
||||
const completeJob = { ...baseJob, status: 'complete' } as Job
|
||||
it('does not show cancel button for cancelled jobs', () => {
|
||||
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
||||
render(
|
||||
<JobActions
|
||||
job={completeJob}
|
||||
job={cancelledJob}
|
||||
onRefresh={mockOnRefresh}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Delete')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Cancel')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Renders nothing when no actions available', () => {
|
||||
it('returns null for complete jobs (no delete, no retry)', () => {
|
||||
it('returns null for complete jobs (no cancel, no retry)', () => {
|
||||
const completeJob = { ...baseJob, status: 'complete' } as Job
|
||||
const { container } = render(
|
||||
<JobActions
|
||||
|
||||
@@ -13,10 +13,6 @@ jest.mock('../job/JobActions', () => ({
|
||||
JobActions: () => <div data-testid="job-actions">Job Actions</div>
|
||||
}))
|
||||
|
||||
jest.mock('../job/AdminJobActions', () => ({
|
||||
AdminJobActions: () => <div data-testid="admin-job-actions">Admin Job Actions</div>
|
||||
}))
|
||||
|
||||
jest.mock('../job/JobLogs', () => ({
|
||||
JobLogs: () => <div data-testid="job-logs">Job Logs</div>
|
||||
}))
|
||||
@@ -191,24 +187,4 @@ describe('JobCard', () => {
|
||||
|
||||
expect(screen.getByText('Test Artist - Unknown')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
describe('admin controls', () => {
|
||||
it('shows admin job actions when showAdminControls is true', () => {
|
||||
render(<JobCard job={mockJob} onRefresh={mockOnRefresh} showAdminControls={true} />)
|
||||
|
||||
expect(screen.getByTestId('admin-job-actions')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show admin job actions when showAdminControls is false', () => {
|
||||
render(<JobCard job={mockJob} onRefresh={mockOnRefresh} showAdminControls={false} />)
|
||||
|
||||
expect(screen.queryByTestId('admin-job-actions')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show admin job actions by default', () => {
|
||||
render(<JobCard job={mockJob} onRefresh={mockOnRefresh} />)
|
||||
|
||||
expect(screen.queryByTestId('admin-job-actions')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,20 +1,10 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useMemo } from "react"
|
||||
import { api } from "@/lib/api"
|
||||
import {
|
||||
ExtendedAudioSearchResult,
|
||||
groupResults,
|
||||
getDisplayName,
|
||||
formatCount,
|
||||
formatMetadata,
|
||||
formatQuality,
|
||||
getAvailabilityLabel,
|
||||
checkFilenameMismatch,
|
||||
} from "@/lib/audio-search-utils"
|
||||
import { api, AudioSearchResult } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Loader2, Music2, ChevronDown, ChevronUp, Lightbulb } from "lucide-react"
|
||||
import { Loader2, Music2, ChevronDown, ChevronUp } from "lucide-react"
|
||||
|
||||
// Version from pyproject.toml (single source of truth)
|
||||
const APP_VERSION = process.env.NEXT_PUBLIC_APP_VERSION || "0.0.0"
|
||||
@@ -24,16 +14,117 @@ interface AudioSearchDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSelect: () => void
|
||||
searchTitle?: string
|
||||
}
|
||||
|
||||
export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle }: AudioSearchDialogProps) {
|
||||
// Extended result type to include all backend fields
|
||||
interface ExtendedAudioSearchResult extends AudioSearchResult {
|
||||
channel?: string
|
||||
view_count?: number
|
||||
formatted_duration?: string
|
||||
formatted_size?: string
|
||||
release_type?: string
|
||||
label?: string
|
||||
edition_info?: string
|
||||
target_file?: string
|
||||
quality_data?: {
|
||||
format?: string
|
||||
bit_depth?: number
|
||||
sample_rate?: number
|
||||
bitrate?: number
|
||||
media?: string
|
||||
}
|
||||
}
|
||||
|
||||
// Category configuration matching flacfetch
|
||||
interface CategoryConfig {
|
||||
name: string
|
||||
maxDisplay: number
|
||||
color: string
|
||||
borderColor: string
|
||||
}
|
||||
|
||||
const CATEGORY_CONFIG: Record<string, CategoryConfig> = {
|
||||
'BEST CHOICE': { name: 'BEST CHOICE', maxDisplay: 3, color: 'text-amber-400', borderColor: 'border-amber-500/30' },
|
||||
'HI-RES 24-BIT': { name: 'HI-RES 24-BIT', maxDisplay: 3, color: 'text-purple-400', borderColor: 'border-purple-500/30' },
|
||||
'STUDIO ALBUMS': { name: 'STUDIO ALBUMS', maxDisplay: 3, color: 'text-blue-400', borderColor: 'border-blue-500/30' },
|
||||
'SINGLES': { name: 'SINGLES', maxDisplay: 2, color: 'text-cyan-400', borderColor: 'border-cyan-500/30' },
|
||||
'LIVE VERSIONS': { name: 'LIVE VERSIONS', maxDisplay: 2, color: 'text-pink-400', borderColor: 'border-pink-500/30' },
|
||||
'COMPILATIONS': { name: 'COMPILATIONS', maxDisplay: 2, color: 'text-teal-400', borderColor: 'border-teal-500/30' },
|
||||
'VINYL RIPS': { name: 'VINYL RIPS', maxDisplay: 2, color: 'text-orange-400', borderColor: 'border-orange-500/30' },
|
||||
'YOUTUBE/LOSSY': { name: 'YOUTUBE/LOSSY', maxDisplay: 3, color: 'text-red-400', borderColor: 'border-red-500/30' },
|
||||
'OTHER': { name: 'OTHER', maxDisplay: 3, color: 'text-muted-foreground', borderColor: 'border-border' },
|
||||
}
|
||||
|
||||
const CATEGORY_ORDER = [
|
||||
'BEST CHOICE',
|
||||
'HI-RES 24-BIT',
|
||||
'STUDIO ALBUMS',
|
||||
'SINGLES',
|
||||
'LIVE VERSIONS',
|
||||
'COMPILATIONS',
|
||||
'VINYL RIPS',
|
||||
'YOUTUBE/LOSSY',
|
||||
'OTHER'
|
||||
]
|
||||
|
||||
// Categorize a single result based on flacfetch logic
|
||||
function categorizeResult(result: ExtendedAudioSearchResult): string {
|
||||
const isLossless = result.is_lossless === true
|
||||
const is24Bit = result.quality_data?.bit_depth === 24
|
||||
const seeders = result.seeders ?? 0
|
||||
const provider = result.provider?.toLowerCase() ?? ''
|
||||
const releaseType = result.release_type?.toLowerCase() ?? ''
|
||||
const media = result.quality_data?.media?.toLowerCase() ?? ''
|
||||
|
||||
// YouTube and lossy sources
|
||||
if (provider === 'youtube' || !isLossless) {
|
||||
return 'YOUTUBE/LOSSY'
|
||||
}
|
||||
|
||||
// Best choice (50+ seeders, lossless)
|
||||
if (isLossless && seeders >= 50) {
|
||||
return 'BEST CHOICE'
|
||||
}
|
||||
|
||||
// Hi-res 24-bit
|
||||
if (isLossless && is24Bit) {
|
||||
return 'HI-RES 24-BIT'
|
||||
}
|
||||
|
||||
// Vinyl rips
|
||||
if (isLossless && media === 'vinyl') {
|
||||
return 'VINYL RIPS'
|
||||
}
|
||||
|
||||
// Live versions
|
||||
if (isLossless && (releaseType === 'live album' || releaseType === 'bootleg' || releaseType.includes('live'))) {
|
||||
return 'LIVE VERSIONS'
|
||||
}
|
||||
|
||||
// Compilations
|
||||
if (isLossless && (releaseType === 'compilation' || releaseType === 'soundtrack' || releaseType === 'anthology')) {
|
||||
return 'COMPILATIONS'
|
||||
}
|
||||
|
||||
// Singles/EPs
|
||||
if (isLossless && (releaseType === 'single' || releaseType === 'ep')) {
|
||||
return 'SINGLES'
|
||||
}
|
||||
|
||||
// Studio albums
|
||||
if (isLossless && (releaseType === 'album' || !releaseType)) {
|
||||
return 'STUDIO ALBUMS'
|
||||
}
|
||||
|
||||
return 'OTHER'
|
||||
}
|
||||
|
||||
export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearchDialogProps) {
|
||||
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isSelecting, setIsSelecting] = useState<number | null>(null)
|
||||
const [error, setError] = useState("")
|
||||
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
|
||||
const [showGuidance, setShowGuidance] = useState(false)
|
||||
|
||||
// Debug: Log component version on mount
|
||||
useEffect(() => {
|
||||
@@ -46,7 +137,6 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
console.log(`[AudioSearchDialog v${APP_VERSION}] Dialog opened for job: ${jobId}`)
|
||||
loadResults()
|
||||
setExpandedCategories(new Set()) // Reset expanded state
|
||||
setShowGuidance(false)
|
||||
}
|
||||
}, [open, jobId])
|
||||
|
||||
@@ -68,7 +158,31 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
}
|
||||
|
||||
// Group results by category
|
||||
const groupedResults = useMemo(() => groupResults(results), [results])
|
||||
const groupedResults = useMemo(() => {
|
||||
const groups: Record<string, ExtendedAudioSearchResult[]> = {}
|
||||
|
||||
for (const result of results) {
|
||||
const category = categorizeResult(result)
|
||||
if (!groups[category]) {
|
||||
groups[category] = []
|
||||
}
|
||||
groups[category].push(result)
|
||||
}
|
||||
|
||||
// Sort by category order
|
||||
const sortedGroups: Array<{ category: string; results: ExtendedAudioSearchResult[]; config: CategoryConfig }> = []
|
||||
for (const cat of CATEGORY_ORDER) {
|
||||
if (groups[cat] && groups[cat].length > 0) {
|
||||
sortedGroups.push({
|
||||
category: cat,
|
||||
results: groups[cat],
|
||||
config: CATEGORY_CONFIG[cat]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return sortedGroups
|
||||
}, [results])
|
||||
|
||||
// Count total categories
|
||||
const totalCategories = groupedResults.length
|
||||
@@ -100,6 +214,51 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
})
|
||||
}
|
||||
|
||||
// Get display name - use channel for YouTube, artist for others
|
||||
function getDisplayName(result: ExtendedAudioSearchResult): string {
|
||||
if (result.provider === "YouTube" && result.channel) {
|
||||
return result.channel
|
||||
}
|
||||
return result.artist || ""
|
||||
}
|
||||
|
||||
// Format views/seeders compactly
|
||||
function formatCount(count?: number): string {
|
||||
if (!count && count !== 0) return "-"
|
||||
if (count >= 1000000) return `${(count / 1000000).toFixed(1)}M`
|
||||
if (count >= 1000) return `${(count / 1000).toFixed(1)}K`
|
||||
return count.toString()
|
||||
}
|
||||
|
||||
// Format release metadata line
|
||||
function formatMetadata(result: ExtendedAudioSearchResult): string {
|
||||
const parts: string[] = []
|
||||
|
||||
if (result.release_type) parts.push(result.release_type)
|
||||
if (result.year) parts.push(result.year.toString())
|
||||
if (result.label) parts.push(result.label)
|
||||
if (result.edition_info) parts.push(result.edition_info)
|
||||
if (result.quality_data?.media) parts.push(result.quality_data.media)
|
||||
|
||||
return parts.length > 0 ? `[${parts.join(' / ')}]` : ''
|
||||
}
|
||||
|
||||
// Get quality display string
|
||||
function formatQuality(result: ExtendedAudioSearchResult): string {
|
||||
if (result.quality) return result.quality
|
||||
|
||||
const qd = result.quality_data
|
||||
if (!qd) return '-'
|
||||
|
||||
const parts: string[] = []
|
||||
if (qd.format) parts.push(qd.format)
|
||||
if (qd.bit_depth) parts.push(`${qd.bit_depth}bit`)
|
||||
if (qd.bitrate) parts.push(`${qd.bitrate}kbps`)
|
||||
if (qd.media) parts.push(qd.media)
|
||||
|
||||
return parts.join(' ') || '-'
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-7xl w-[95vw] max-h-[90vh] flex flex-col bg-card border-border !p-0 gap-0 overflow-hidden">
|
||||
@@ -113,29 +272,6 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
</DialogTitle>
|
||||
</div>
|
||||
|
||||
{/* Guidance header (collapsed by default) */}
|
||||
{!isLoading && results.length > 0 && (
|
||||
<div className="px-4 py-1.5 border-b border-border bg-secondary/30">
|
||||
<button
|
||||
onClick={() => setShowGuidance(!showGuidance)}
|
||||
className="flex items-center gap-1.5 text-[10px] text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Lightbulb className="w-3 h-3" />
|
||||
Tips for choosing
|
||||
{showGuidance ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
|
||||
</button>
|
||||
{showGuidance && (
|
||||
<ul className="text-[10px] text-muted-foreground mt-1.5 ml-5 space-y-0.5 pb-1">
|
||||
<li>Check the filename matches your song title</li>
|
||||
<li>Green availability badge = more reliable download</li>
|
||||
<li>Studio album versions produce the best karaoke results</li>
|
||||
<li>Avoid vinyl rips (surface noise affects separation)</li>
|
||||
<li>YouTube is a last resort — lossless sources sound better</li>
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="px-4 py-2 text-xs text-red-400 bg-red-500/10 border-b border-border">
|
||||
{error}
|
||||
@@ -186,112 +322,89 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
|
||||
{/* Results in category */}
|
||||
<div className="divide-y divide-slate-700/50">
|
||||
{displayResults.map((result) => {
|
||||
const mismatch = searchTitle ? checkFilenameMismatch(searchTitle, result) : null
|
||||
const hasMismatch = mismatch?.isMismatch ?? false
|
||||
{displayResults.map((result) => (
|
||||
<div
|
||||
key={result.index}
|
||||
className="px-3 py-1.5 hover:bg-secondary/50 flex items-center gap-2 text-xs"
|
||||
>
|
||||
{/* Index */}
|
||||
<span className="w-5 text-muted-foreground font-mono shrink-0 text-[10px]">
|
||||
{result.index + 1}.
|
||||
</span>
|
||||
|
||||
return (
|
||||
<div
|
||||
key={result.index}
|
||||
className={`px-3 py-1.5 hover:bg-secondary/50 flex items-center gap-2 text-xs ${
|
||||
hasMismatch ? 'opacity-60' : ''
|
||||
}`}
|
||||
>
|
||||
{/* Index */}
|
||||
<span className="w-5 text-muted-foreground font-mono shrink-0 text-[10px]">
|
||||
{result.index + 1}.
|
||||
</span>
|
||||
|
||||
{/* Main content - 2 lines */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{/* Line 1: badges + artist + title + quality + size + availability */}
|
||||
<div className="flex items-center gap-1 flex-wrap">
|
||||
{result.is_lossless && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
|
||||
LOSSLESS
|
||||
</span>
|
||||
)}
|
||||
{result.quality_data?.media?.toLowerCase() === 'vinyl' && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-red-600/20 text-red-400 font-medium">
|
||||
VINYL
|
||||
</span>
|
||||
)}
|
||||
{result.provider === "YouTube" && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
|
||||
YouTube
|
||||
</span>
|
||||
)}
|
||||
{hasMismatch && (
|
||||
<span
|
||||
title={`Expected "${searchTitle}" but filename is "${mismatch!.filename}"${mismatch!.suggestedTrack ? ` (looks like "${mismatch!.suggestedTrack}")` : ''}`}
|
||||
className="text-[8px] px-1 py-0.5 rounded font-medium bg-yellow-600/20 text-yellow-400 cursor-help"
|
||||
>
|
||||
Wrong track?
|
||||
</span>
|
||||
)}
|
||||
<span className="text-green-400 font-medium">{getDisplayName(result)}</span>
|
||||
<span className="text-muted-foreground">-</span>
|
||||
<span className="text-foreground">{result.title}</span>
|
||||
<span className={`text-[10px] ${result.is_lossless ? "text-green-400" : "text-muted-foreground"}`}>
|
||||
({formatQuality(result)})
|
||||
{/* Main content - 2 lines */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{/* Line 1: badges + artist + title + quality + size + availability */}
|
||||
<div className="flex items-center gap-1 flex-wrap">
|
||||
{result.is_lossless && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-green-600/20 text-green-400 font-medium">
|
||||
LOSSLESS
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground">{result.formatted_size || '-'}</span>
|
||||
{result.seeders !== undefined && result.seeders !== null ? (
|
||||
(() => {
|
||||
const { text, tooltip } = getAvailabilityLabel(result.seeders)
|
||||
return (
|
||||
<span
|
||||
title={tooltip}
|
||||
className={`text-[8px] px-1 py-0.5 rounded font-medium cursor-help ${
|
||||
result.seeders >= 50 ? 'bg-green-600/20 text-green-400' :
|
||||
result.seeders >= 10 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-red-600/20 text-red-400'
|
||||
}`}
|
||||
>
|
||||
{text} availability
|
||||
</span>
|
||||
)
|
||||
})()
|
||||
) : result.view_count !== undefined ? (
|
||||
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
|
||||
result.view_count >= 1000000 ? 'bg-green-600/20 text-green-400' :
|
||||
result.view_count >= 10000 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-muted text-muted-foreground'
|
||||
}`}>
|
||||
{formatCount(result.view_count)} views
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Line 2: metadata + filename */}
|
||||
{(formatMetadata(result) || result.target_file) && (
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
{formatMetadata(result) && (
|
||||
<span className="truncate">{formatMetadata(result)}</span>
|
||||
)}
|
||||
{result.target_file && (
|
||||
<span className="font-mono truncate">"{result.target_file}"</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{result.quality_data?.media?.toLowerCase() === 'vinyl' && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded bg-red-600/20 text-red-400 font-medium">
|
||||
VINYL
|
||||
</span>
|
||||
)}
|
||||
{result.provider === "YouTube" && (
|
||||
<span className="text-[8px] px-1 py-0.5 rounded font-medium bg-red-600/20 text-red-400">
|
||||
YouTube
|
||||
</span>
|
||||
)}
|
||||
<span className="text-green-400 font-medium">{getDisplayName(result)}</span>
|
||||
<span className="text-muted-foreground">-</span>
|
||||
<span className="text-foreground">{result.title}</span>
|
||||
<span className={`text-[10px] ${result.is_lossless ? "text-green-400" : "text-muted-foreground"}`}>
|
||||
({formatQuality(result)})
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground">{result.formatted_size || '-'}</span>
|
||||
{result.seeders !== undefined && result.seeders !== null ? (
|
||||
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
|
||||
result.seeders >= 50 ? 'bg-green-600/20 text-green-400' :
|
||||
result.seeders >= 10 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-red-600/20 text-red-400'
|
||||
}`}>
|
||||
{result.seeders >= 50 ? 'High' : result.seeders >= 10 ? 'Medium' : 'Low'} availability
|
||||
</span>
|
||||
) : result.view_count !== undefined ? (
|
||||
<span className={`text-[8px] px-1 py-0.5 rounded font-medium ${
|
||||
result.view_count >= 1000000 ? 'bg-green-600/20 text-green-400' :
|
||||
result.view_count >= 10000 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-muted text-muted-foreground'
|
||||
}`}>
|
||||
{formatCount(result.view_count)} views
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Select button */}
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSelect(result.index)}
|
||||
disabled={isSelecting !== null}
|
||||
className="w-14 h-6 text-[9px] bg-amber-600 hover:bg-amber-500 text-foreground px-2 shrink-0"
|
||||
>
|
||||
{isSelecting === result.index ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : (
|
||||
"Select"
|
||||
)}
|
||||
</Button>
|
||||
{/* Line 2: metadata + filename */}
|
||||
{(formatMetadata(result) || result.target_file) && (
|
||||
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
|
||||
{formatMetadata(result) && (
|
||||
<span className="truncate">{formatMetadata(result)}</span>
|
||||
)}
|
||||
{result.target_file && (
|
||||
<span className="font-mono truncate">"{result.target_file}"</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Select button */}
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSelect(result.index)}
|
||||
disabled={isSelecting !== null}
|
||||
className="w-14 h-6 text-[9px] bg-amber-600 hover:bg-amber-500 text-foreground px-2 shrink-0"
|
||||
>
|
||||
{isSelecting === result.index ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : (
|
||||
"Select"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical, Gift } from "lucide-react"
|
||||
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
@@ -16,8 +16,6 @@ import { Switch } from "@/components/ui/switch"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { AuthDialog } from "./AuthDialog"
|
||||
import { FeedbackDialog } from "@/components/feedback/FeedbackDialog"
|
||||
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
|
||||
|
||||
interface AuthStatusProps {
|
||||
onAuthChange?: () => void
|
||||
@@ -27,8 +25,6 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
const { user, logout } = useAuth()
|
||||
const { showTestData, setShowTestData } = useAdminSettings()
|
||||
const [showAuthDialog, setShowAuthDialog] = useState(false)
|
||||
const [showFeedbackDialog, setShowFeedbackDialog] = useState(false)
|
||||
const [showBuyCreditsDialog, setShowBuyCreditsDialog] = useState(false)
|
||||
const [mounted, setMounted] = useState(false)
|
||||
|
||||
// Avoid hydration mismatch
|
||||
@@ -49,7 +45,12 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
}
|
||||
|
||||
const handleBuyCredits = () => {
|
||||
setShowBuyCreditsDialog(true)
|
||||
// Navigate to landing page pricing section with email prefilled if available
|
||||
const buyUrl = new URL('/#pricing', window.location.origin)
|
||||
if (user?.email) {
|
||||
buyUrl.searchParams.set("email", user.email)
|
||||
}
|
||||
window.location.href = buyUrl.toString()
|
||||
}
|
||||
|
||||
// Don't render until mounted (avoids hydration issues)
|
||||
@@ -59,7 +60,6 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
|
||||
if (user) {
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
@@ -71,14 +71,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
<span className="hidden sm:inline max-w-[150px] truncate">
|
||||
{user.display_name || user.email}
|
||||
</span>
|
||||
<span
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleBuyCredits()
|
||||
}}
|
||||
className="flex items-center gap-1 text-warning font-medium hover:text-warning/80 transition-colors cursor-pointer"
|
||||
title="Buy more credits"
|
||||
>
|
||||
<span className="flex items-center gap-1 text-warning font-medium">
|
||||
<Coins className="w-3 h-3" />
|
||||
{user.credits} {user.credits === 1 ? 'credit' : 'credits'}
|
||||
</span>
|
||||
@@ -108,15 +101,6 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
<CreditCard className="w-4 h-4 mr-2" />
|
||||
<span>Buy More Credits</span>
|
||||
</DropdownMenuItem>
|
||||
{user.feedback_eligible && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => setShowFeedbackDialog(true)}
|
||||
className="text-green-500 focus:text-green-400 focus:bg-secondary"
|
||||
>
|
||||
<Gift className="w-4 h-4 mr-2" />
|
||||
<span>Earn 2 Free Credits</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
|
||||
<>
|
||||
<DropdownMenuSeparator className="bg-border" />
|
||||
@@ -150,15 +134,6 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<FeedbackDialog
|
||||
open={showFeedbackDialog}
|
||||
onClose={() => setShowFeedbackDialog(false)}
|
||||
/>
|
||||
<BuyCreditsDialog
|
||||
open={showBuyCreditsDialog}
|
||||
onClose={() => setShowBuyCreditsDialog(false)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { CreditCard, Loader2 } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { api, CreditPackage } from '@/lib/api'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
|
||||
interface BuyCreditsDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const formatPrice = (cents: number) => `$${(cents / 100).toFixed(0)}`
|
||||
const pricePerVideo = (pkg: CreditPackage) =>
|
||||
`$${(pkg.price_cents / 100 / pkg.credits).toFixed(2)}`
|
||||
|
||||
export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
const { user } = useAuth()
|
||||
const [packages, setPackages] = useState<CreditPackage[]>([])
|
||||
const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [checkoutLoading, setCheckoutLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setError('')
|
||||
setLoading(true)
|
||||
api.getCreditPackages()
|
||||
.then((pkgs) => {
|
||||
setPackages(pkgs)
|
||||
// Pre-select best value package (5 credits) or first
|
||||
const bestValue = pkgs.find((p) => p.credits === 5) || pkgs[0]
|
||||
setSelectedPackage(bestValue)
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load packages')
|
||||
})
|
||||
.finally(() => setLoading(false))
|
||||
}, [open])
|
||||
|
||||
const handleCheckout = async () => {
|
||||
if (!selectedPackage || !user?.email) return
|
||||
setCheckoutLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const checkoutUrl = await api.createCheckout(selectedPackage.id, user.email)
|
||||
window.location.href = checkoutUrl
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create checkout session')
|
||||
setCheckoutLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
|
||||
<DialogContent className="sm:max-w-md bg-card border-border">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<CreditCard className="w-5 h-5 text-primary" />
|
||||
Buy More Credits
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-muted-foreground">
|
||||
Each credit creates one karaoke video. Pick a package below.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 mt-2">
|
||||
{loading && (
|
||||
<div className="flex justify-center py-8">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="text-center py-4 text-sm text-destructive">{error}</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && packages.length > 0 && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{packages.map((pkg) => {
|
||||
const isSelected = selectedPackage?.id === pkg.id
|
||||
const isBestValue = pkg.credits === 5
|
||||
const savings = pkg.credits > 1
|
||||
? Math.round((1 - pkg.price_cents / (pkg.credits * 500)) * 100)
|
||||
: 0
|
||||
|
||||
return (
|
||||
<button
|
||||
key={pkg.id}
|
||||
onClick={() => setSelectedPackage(pkg)}
|
||||
className={`relative p-4 rounded-xl border-2 transition-all text-left ${
|
||||
isSelected
|
||||
? 'border-primary bg-primary/10'
|
||||
: 'border-border hover:border-muted-foreground/50 bg-secondary/50'
|
||||
}`}
|
||||
>
|
||||
{isBestValue && (
|
||||
<span className="absolute -top-2.5 left-1/2 -translate-x-1/2 bg-primary text-primary-foreground text-xs font-semibold px-2 py-0.5 rounded-full">
|
||||
Best Value
|
||||
</span>
|
||||
)}
|
||||
<div className="text-2xl font-bold">{pkg.credits}</div>
|
||||
<div className="text-sm text-muted-foreground mb-1">
|
||||
{pkg.credits === 1 ? 'credit' : 'credits'}
|
||||
</div>
|
||||
<div className="text-lg font-semibold text-primary">
|
||||
{formatPrice(pkg.price_cents)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">{pricePerVideo(pkg)}/video</div>
|
||||
{savings > 0 && (
|
||||
<div className="text-xs text-green-500 mt-1">Save {savings}%</div>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleCheckout}
|
||||
disabled={!selectedPackage || checkoutLoading}
|
||||
className="w-full"
|
||||
>
|
||||
{checkoutLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Redirecting to payment...
|
||||
</>
|
||||
) : selectedPackage ? (
|
||||
`Continue to Payment — ${formatPrice(selectedPackage.price_cents)}`
|
||||
) : (
|
||||
'Select a package'
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Star, Loader2, CheckCircle, Gift } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { api } from '@/lib/api'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
|
||||
interface FeedbackDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
function StarRating({ value, onChange, label }: {
|
||||
value: number
|
||||
onChange: (v: number) => void
|
||||
label: string
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<Label className="text-sm">{label}</Label>
|
||||
<div className="flex gap-1">
|
||||
{[1, 2, 3, 4, 5].map((star) => (
|
||||
<button
|
||||
key={star}
|
||||
type="button"
|
||||
onClick={() => onChange(star)}
|
||||
className="p-0.5 transition-colors"
|
||||
>
|
||||
<Star
|
||||
className={`w-5 h-5 ${
|
||||
star <= value
|
||||
? 'fill-yellow-400 text-yellow-400'
|
||||
: 'text-muted-foreground'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
|
||||
const { fetchUser } = useAuth()
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [isSuccess, setIsSuccess] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [creditsGranted, setCreditsGranted] = useState(0)
|
||||
|
||||
// Ratings
|
||||
const [overallRating, setOverallRating] = useState(0)
|
||||
const [easeOfUseRating, setEaseOfUseRating] = useState(0)
|
||||
const [lyricsAccuracyRating, setLyricsAccuracyRating] = useState(0)
|
||||
const [correctionRating, setCorrectionRating] = useState(0)
|
||||
|
||||
// Text fields
|
||||
const [whatWentWell, setWhatWentWell] = useState('')
|
||||
const [whatCouldImprove, setWhatCouldImprove] = useState('')
|
||||
const [additionalComments, setAdditionalComments] = useState('')
|
||||
|
||||
// Checkboxes
|
||||
const [wouldRecommend, setWouldRecommend] = useState(true)
|
||||
const [wouldUseAgain, setWouldUseAgain] = useState(true)
|
||||
|
||||
const hasDetailedFeedback =
|
||||
whatWentWell.length > 50 ||
|
||||
whatCouldImprove.length > 50 ||
|
||||
additionalComments.length > 50
|
||||
|
||||
const allRatingsSet =
|
||||
overallRating > 0 &&
|
||||
easeOfUseRating > 0 &&
|
||||
lyricsAccuracyRating > 0 &&
|
||||
correctionRating > 0
|
||||
|
||||
const canSubmit = allRatingsSet && hasDetailedFeedback && !isSubmitting
|
||||
|
||||
const longestText = Math.max(
|
||||
whatWentWell.length,
|
||||
whatCouldImprove.length,
|
||||
additionalComments.length
|
||||
)
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setError('')
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const result = await api.submitFeedback({
|
||||
overall_rating: overallRating,
|
||||
ease_of_use_rating: easeOfUseRating,
|
||||
lyrics_accuracy_rating: lyricsAccuracyRating,
|
||||
correction_experience_rating: correctionRating,
|
||||
what_went_well: whatWentWell || undefined,
|
||||
what_could_improve: whatCouldImprove || undefined,
|
||||
additional_comments: additionalComments || undefined,
|
||||
would_recommend: wouldRecommend,
|
||||
would_use_again: wouldUseAgain,
|
||||
})
|
||||
setCreditsGranted(result.credits_granted)
|
||||
setIsSuccess(true)
|
||||
// Refresh user data to update credits and feedback_eligible
|
||||
fetchUser()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to submit feedback')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
if (isSuccess) {
|
||||
// Reset form state for next time
|
||||
setOverallRating(0)
|
||||
setEaseOfUseRating(0)
|
||||
setLyricsAccuracyRating(0)
|
||||
setCorrectionRating(0)
|
||||
setWhatWentWell('')
|
||||
setWhatCouldImprove('')
|
||||
setAdditionalComments('')
|
||||
setWouldRecommend(true)
|
||||
setWouldUseAgain(true)
|
||||
setIsSuccess(false)
|
||||
setCreditsGranted(0)
|
||||
}
|
||||
setError('')
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && handleClose()}>
|
||||
<DialogContent className="sm:max-w-lg bg-card border-border max-h-[90vh] overflow-y-auto">
|
||||
{isSuccess ? (
|
||||
<div className="text-center py-6 space-y-4">
|
||||
<CheckCircle className="w-16 h-16 text-green-500 mx-auto" />
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground text-xl">Thank You!</DialogTitle>
|
||||
<DialogDescription className="text-muted-foreground text-base">
|
||||
Your feedback helps us improve Nomad Karaoke for everyone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="bg-green-500/10 border border-green-500/30 rounded-lg p-4 mx-auto max-w-xs">
|
||||
<p className="text-2xl font-bold text-green-500">+{creditsGranted}</p>
|
||||
<p className="text-sm text-muted-foreground">credits added to your account</p>
|
||||
</div>
|
||||
<Button onClick={handleClose} className="mt-4">
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<Gift className="w-5 h-5 text-green-500" />
|
||||
Share Your Feedback — Earn 2 Free Credits
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-muted-foreground">
|
||||
Tell us about your experience creating karaoke videos. Your feedback directly shapes what we build next.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-5 mt-2">
|
||||
{/* Star Ratings */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<StarRating
|
||||
label="Overall Experience"
|
||||
value={overallRating}
|
||||
onChange={setOverallRating}
|
||||
/>
|
||||
<StarRating
|
||||
label="Ease of Use"
|
||||
value={easeOfUseRating}
|
||||
onChange={setEaseOfUseRating}
|
||||
/>
|
||||
<StarRating
|
||||
label="Lyrics Accuracy"
|
||||
value={lyricsAccuracyRating}
|
||||
onChange={setLyricsAccuracyRating}
|
||||
/>
|
||||
<StarRating
|
||||
label="Correction Experience"
|
||||
value={correctionRating}
|
||||
onChange={setCorrectionRating}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Text Fields */}
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="went-well">What went well?</Label>
|
||||
<Textarea
|
||||
id="went-well"
|
||||
value={whatWentWell}
|
||||
onChange={(e) => setWhatWentWell(e.target.value)}
|
||||
placeholder="What did you enjoy about creating karaoke videos?"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="could-improve">What could be better?</Label>
|
||||
<Textarea
|
||||
id="could-improve"
|
||||
value={whatCouldImprove}
|
||||
onChange={(e) => setWhatCouldImprove(e.target.value)}
|
||||
placeholder="What would make the experience better?"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="additional">Additional comments</Label>
|
||||
<Textarea
|
||||
id="additional"
|
||||
value={additionalComments}
|
||||
onChange={(e) => setAdditionalComments(e.target.value)}
|
||||
placeholder="Anything else you'd like us to know?"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
{!hasDetailedFeedback && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Please write at least 50 characters in one of the fields above ({longestText}/50)
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Checkboxes */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="would-recommend"
|
||||
checked={wouldRecommend}
|
||||
onCheckedChange={(checked) => setWouldRecommend(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="would-recommend" className="text-sm font-normal cursor-pointer">
|
||||
I would recommend Nomad Karaoke to others
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="would-use-again"
|
||||
checked={wouldUseAgain}
|
||||
onCheckedChange={(checked) => setWouldUseAgain(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="would-use-again" className="text-sm font-normal cursor-pointer">
|
||||
I would use Nomad Karaoke again
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
)}
|
||||
|
||||
{/* Submit */}
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!canSubmit}
|
||||
className="w-full"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Submitting...
|
||||
</>
|
||||
) : (
|
||||
'Submit Feedback & Earn 2 Credits'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { ExternalLink, Lightbulb, X } from "lucide-react"
|
||||
import type { BackingVocalAnalysis, AudibleSegment } from "@/lib/api"
|
||||
|
||||
interface InstrumentalGuidancePanelProps {
|
||||
analysis: BackingVocalAnalysis
|
||||
audibleSegments: AudibleSegment[]
|
||||
}
|
||||
|
||||
export function InstrumentalGuidancePanel({
|
||||
analysis,
|
||||
audibleSegments,
|
||||
}: InstrumentalGuidancePanelProps) {
|
||||
const [guidanceDismissed, setGuidanceDismissed] = useState(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("instrumentalReviewGuidanceDismissed") === "true"
|
||||
})
|
||||
|
||||
const handleDismiss = () => {
|
||||
setGuidanceDismissed(true)
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("instrumentalReviewGuidanceDismissed", "true")
|
||||
}
|
||||
}
|
||||
|
||||
const handleShowTips = () => {
|
||||
setGuidanceDismissed(false)
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.removeItem("instrumentalReviewGuidanceDismissed")
|
||||
}
|
||||
}
|
||||
|
||||
const isCleanRecommended = analysis.recommended_selection === "clean"
|
||||
const percentage = analysis.audible_percentage
|
||||
const hasSegments = audibleSegments.length > 0
|
||||
|
||||
if (guidanceDismissed) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<button
|
||||
className="text-amber-500 hover:text-amber-400 transition-colors"
|
||||
onClick={handleShowTips}
|
||||
>
|
||||
Show tips
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Simple case: clean recommended with low backing vocals
|
||||
if (isCleanRecommended && percentage < 10) {
|
||||
return (
|
||||
<div className="flex items-start gap-2 p-2.5 rounded-md bg-amber-500/10 border border-amber-500/20">
|
||||
<Lightbulb className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-muted-foreground flex-1 leading-relaxed space-y-1.5">
|
||||
<p>
|
||||
<strong>Choose your karaoke backing track.</strong> The AI separated
|
||||
the vocals from the music — now pick which version sounds best.
|
||||
</p>
|
||||
<p>
|
||||
This track has very little backing vocal content ({percentage.toFixed(0)}%).
|
||||
We recommend the <strong>Clean Instrumental</strong> — just confirm
|
||||
below to proceed.
|
||||
</p>
|
||||
<p className="text-muted-foreground/70">
|
||||
Want to hear the difference? Use the audio buttons above to compare,
|
||||
or click the{" "}
|
||||
<span className="inline-block w-2 h-2 rounded-full bg-pink-500/60 align-middle" />{" "}
|
||||
pink sections in the waveform to listen to the backing vocals.
|
||||
</p>
|
||||
<a
|
||||
href="https://www.youtube.com/watch?v=-dI3r7qXo3A"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-amber-500 hover:text-amber-400 transition-colors mt-1"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
Watch full tutorial
|
||||
</a>
|
||||
</div>
|
||||
<button
|
||||
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
onClick={handleDismiss}
|
||||
aria-label="Dismiss tip"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Complex case: backing vocals present, needs review
|
||||
return (
|
||||
<div className="flex items-start gap-2 p-2.5 rounded-md bg-amber-500/10 border border-amber-500/20">
|
||||
<Lightbulb className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-muted-foreground flex-1 leading-relaxed space-y-1.5">
|
||||
<p>
|
||||
<strong>Choose your karaoke backing track.</strong> The AI separated
|
||||
the vocals from the music — now pick which version sounds best.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Backing vocals</strong> are the harmony/chorus voices that sing
|
||||
along with the lead. Some karaoke singers prefer to keep them for guidance,
|
||||
others prefer a clean instrumental.
|
||||
</p>
|
||||
<div className="space-y-1 pl-2 border-l-2 border-amber-500/30">
|
||||
<p>
|
||||
<strong>Step 1:</strong> Click the{" "}
|
||||
<span className="inline-block w-2 h-2 rounded-full bg-pink-500/60 align-middle" />{" "}
|
||||
pink sections in the waveform to hear the backing vocals
|
||||
{hasSegments && ` (${audibleSegments.length} detected)`}.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Step 2:</strong> Decide — keep them or use the clean
|
||||
instrumental? Use the audio toggle buttons above to compare.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Step 3</strong> (if needed): If you want backing vocals but
|
||||
some sections have unwanted lead vocal bleed,{" "}
|
||||
<kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">
|
||||
Shift
|
||||
</kbd>
|
||||
+drag on the waveform to mark those sections, then click{" "}
|
||||
<strong>Create Custom</strong>.
|
||||
</p>
|
||||
</div>
|
||||
<a
|
||||
href="https://www.youtube.com/watch?v=-dI3r7qXo3A"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-amber-500 hover:text-amber-400 transition-colors mt-1"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
Watch full tutorial
|
||||
</a>
|
||||
</div>
|
||||
<button
|
||||
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
onClick={handleDismiss}
|
||||
aria-label="Dismiss tip"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import { WaveformViewer } from "./WaveformViewer"
|
||||
import { MuteRegionEditor } from "./MuteRegionEditor"
|
||||
import { SelectionOptions } from "./SelectionOptions"
|
||||
import { CustomUpload } from "./CustomUpload"
|
||||
import { InstrumentalGuidancePanel } from "./InstrumentalGuidancePanel"
|
||||
|
||||
interface InstrumentalSelectorProps {
|
||||
job: Job
|
||||
@@ -79,12 +78,6 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
const [isShiftHeld, setIsShiftHeld] = useState(false)
|
||||
const [isAudioLoading, setIsAudioLoading] = useState(false)
|
||||
|
||||
// Hover highlight state
|
||||
const [hoveredItem, setHoveredItem] = useState<{
|
||||
type: "region" | "segment"
|
||||
index: number
|
||||
} | null>(null)
|
||||
|
||||
// Derived state
|
||||
const hasOriginal = analysisData?.has_original ?? false
|
||||
const hasWithBacking = !!analysisData?.audio_urls.with_backing
|
||||
@@ -93,13 +86,6 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
[analysisData?.analysis.audible_segments]
|
||||
)
|
||||
|
||||
const highlightedTimeRange = useMemo(() => {
|
||||
if (!hoveredItem) return null
|
||||
const source = hoveredItem.type === "region" ? muteRegions : audibleSegments
|
||||
const item = source[hoveredItem.index]
|
||||
return item ? { start: item.start_seconds, end: item.end_seconds } : null
|
||||
}, [hoveredItem, muteRegions, audibleSegments])
|
||||
|
||||
// Toggle play/pause - defined early so it can be used in keyboard shortcuts
|
||||
const togglePlayPause = useCallback(() => {
|
||||
const audio = audioRef.current
|
||||
@@ -557,27 +543,36 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
const amplitudes = waveformData?.amplitudes ?? []
|
||||
|
||||
return (
|
||||
<div className="flex flex-col min-h-screen bg-background p-2 md:p-4 gap-2 md:gap-3">
|
||||
<div className="flex flex-col h-screen bg-background p-4 gap-3 overflow-hidden">
|
||||
{/* Header */}
|
||||
<header className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between flex-shrink-0">
|
||||
<header className="flex items-center justify-between flex-shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-lg font-semibold flex items-center gap-2">
|
||||
<img
|
||||
src="https://gen.nomadkaraoke.com/nomad-karaoke-logo.svg"
|
||||
alt="Nomad Karaoke"
|
||||
className="h-8 md:h-10"
|
||||
className="h-10"
|
||||
onError={(e) => {
|
||||
e.currentTarget.style.display = "none"
|
||||
}}
|
||||
/>
|
||||
<span className="sm:hidden">Review</span>
|
||||
<span className="hidden sm:inline">Instrumental Review</span>
|
||||
Instrumental Review
|
||||
</span>
|
||||
<span className="text-xs md:text-sm text-muted-foreground truncate">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{job.artist} {job.artist && job.title ? "-" : ""} {job.title}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{audibleSegments.length > 0 && (
|
||||
<>
|
||||
<span className="px-2.5 py-1 rounded-full text-xs bg-secondary text-muted-foreground">
|
||||
{audibleSegments.length} segments
|
||||
</span>
|
||||
<span className="px-2.5 py-1 rounded-full text-xs bg-secondary text-muted-foreground">
|
||||
{analysisData?.analysis.audible_percentage.toFixed(0)}% backing vocals
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<span
|
||||
className={`px-2.5 py-1 rounded-full text-xs ${
|
||||
analysisData?.analysis.recommended_selection === "clean"
|
||||
@@ -587,28 +582,20 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
>
|
||||
{analysisData?.analysis.recommended_selection === "clean"
|
||||
? "Clean recommended"
|
||||
: "Review backing vocals"}
|
||||
: "Review needed"}
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Guidance panel */}
|
||||
{analysisData && (
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={analysisData.analysis}
|
||||
audibleSegments={audibleSegments}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Waveform Player */}
|
||||
<div className="min-h-[200px] md:min-h-[250px] lg:flex-1 lg:min-h-0 flex flex-col bg-card border border-border rounded-xl overflow-hidden">
|
||||
<div className="flex-1 flex flex-col bg-card border border-border rounded-xl overflow-hidden min-h-0">
|
||||
{/* Toolbar */}
|
||||
<div className="flex items-center justify-between px-2 md:px-4 py-2 md:py-2.5 bg-secondary border-b border-border gap-3 flex-shrink-0 flex-wrap">
|
||||
<div className="flex items-center justify-between px-4 py-2.5 bg-secondary border-b border-border gap-3 flex-shrink-0 flex-wrap">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="icon"
|
||||
onClick={togglePlayPause}
|
||||
className="rounded-full w-9 h-9 md:w-8 md:h-8"
|
||||
className="rounded-full w-8 h-8"
|
||||
>
|
||||
{isPlaying ? (
|
||||
<Pause className="w-4 h-4" />
|
||||
@@ -633,6 +620,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
uploadedFilename={uploadedFilename}
|
||||
isLoading={isAudioLoading}
|
||||
/>
|
||||
<CustomUpload onUpload={handleUpload} isUploading={isUploading} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -642,7 +630,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
key={level}
|
||||
type="button"
|
||||
onClick={() => setZoomLevel(level)}
|
||||
className={`w-9 h-9 md:w-7 md:h-7 rounded text-xs font-medium transition-colors ${
|
||||
className={`w-7 h-7 rounded text-xs font-medium transition-colors ${
|
||||
zoomLevel === level
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "text-muted-foreground hover:bg-secondary hover:text-foreground"
|
||||
@@ -652,13 +640,13 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className="hidden md:inline text-[10px] text-muted-foreground">
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
<kbd className="px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
|
||||
Shift
|
||||
</kbd>
|
||||
+drag
|
||||
</span>
|
||||
<kbd className="hidden md:inline px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
|
||||
<kbd className="px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
|
||||
Space
|
||||
</kbd>
|
||||
</div>
|
||||
@@ -676,7 +664,6 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
onSeek={seekTo}
|
||||
onRegionCreate={addRegion}
|
||||
isShiftHeld={isShiftHeld}
|
||||
highlightedTimeRange={highlightedTimeRange}
|
||||
/>
|
||||
{isAudioLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/50 backdrop-blur-sm">
|
||||
@@ -687,54 +674,37 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Time axis */}
|
||||
<div className="flex justify-between px-3 py-1 text-[10px] text-muted-foreground bg-black/40 flex-shrink-0">
|
||||
<span>0:00</span>
|
||||
<span>{formatTime(duration * 0.25)}</span>
|
||||
<span>{formatTime(duration * 0.5)}</span>
|
||||
<span>{formatTime(duration * 0.75)}</span>
|
||||
<span>{formatTime(duration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hidden audio element */}
|
||||
<audio ref={audioRef} src={getAudioUrl()} className="hidden" />
|
||||
|
||||
{/* Bottom section */}
|
||||
<div className="flex flex-col lg:flex-row gap-2 md:gap-3 flex-shrink-0">
|
||||
{/* Left column: Custom Mix + Alternate Instrumental */}
|
||||
<div className="flex flex-col gap-2 md:gap-3 lg:flex-1 lg:min-w-0">
|
||||
<MuteRegionEditor
|
||||
regions={muteRegions}
|
||||
audibleSegments={audibleSegments}
|
||||
hasCustom={hasCustom}
|
||||
isCreatingCustom={isCreatingCustom}
|
||||
onRemoveRegion={removeRegion}
|
||||
onClearAll={clearAllRegions}
|
||||
onCreateCustom={handleCreateCustom}
|
||||
onSeekTo={seekTo}
|
||||
onAddSegment={addSegmentAsRegion}
|
||||
onHoverRegion={(index) =>
|
||||
setHoveredItem(index !== null ? { type: "region", index } : null)
|
||||
}
|
||||
onHoverSegment={(index) =>
|
||||
setHoveredItem(index !== null ? { type: "segment", index } : null)
|
||||
}
|
||||
/>
|
||||
<div className="flex gap-3 flex-shrink-0">
|
||||
{/* Mute regions panel */}
|
||||
<MuteRegionEditor
|
||||
regions={muteRegions}
|
||||
audibleSegments={audibleSegments}
|
||||
hasCustom={hasCustom}
|
||||
isCreatingCustom={isCreatingCustom}
|
||||
onRemoveRegion={removeRegion}
|
||||
onClearAll={clearAllRegions}
|
||||
onCreateCustom={handleCreateCustom}
|
||||
onSeekTo={seekTo}
|
||||
onAddSegment={addSegmentAsRegion}
|
||||
/>
|
||||
|
||||
{/* Alternate Instrumental section */}
|
||||
<div className="bg-card border border-border rounded-lg p-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-semibold">Alternate Instrumental</span>
|
||||
<CustomUpload onUpload={handleUpload} isUploading={isUploading} />
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1.5">
|
||||
Have your own instrumental track? Upload it here. The file must be the
|
||||
same duration as the original audio ({formatTime(duration)}) so the
|
||||
synced lyrics stay aligned.
|
||||
</p>
|
||||
{hasUploaded && uploadedFilename && (
|
||||
<p className="text-xs text-green-500 mt-1">
|
||||
✓ Using: {uploadedFilename}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right column: Selection panel */}
|
||||
<div className="w-full lg:w-[340px] lg:flex-shrink-0 bg-card border border-border rounded-lg p-3 flex flex-col gap-2">
|
||||
{/* Selection panel */}
|
||||
<div className="w-[340px] bg-card border border-border rounded-lg p-3 flex flex-col gap-2">
|
||||
<SelectionOptions
|
||||
value={selectedOption}
|
||||
onChange={setSelectedOption}
|
||||
@@ -750,10 +720,9 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
id="submit-btn"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
size="lg"
|
||||
className="mt-auto w-full min-h-[44px] text-base font-semibold"
|
||||
className="mt-auto w-full"
|
||||
>
|
||||
<Check className="w-5 h-5 mr-2" />
|
||||
<Check className="w-4 h-4 mr-2" />
|
||||
{isSubmitting ? "Submitting..." : "Confirm & Continue"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -14,8 +14,6 @@ interface MuteRegionEditorProps {
|
||||
onCreateCustom: () => void
|
||||
onSeekTo: (time: number) => void
|
||||
onAddSegment: (index: number) => void
|
||||
onHoverRegion?: (index: number | null) => void
|
||||
onHoverSegment?: (index: number | null) => void
|
||||
}
|
||||
|
||||
function formatTime(seconds: number): string {
|
||||
@@ -35,18 +33,16 @@ export function MuteRegionEditor({
|
||||
onCreateCustom,
|
||||
onSeekTo,
|
||||
onAddSegment,
|
||||
onHoverRegion,
|
||||
onHoverSegment,
|
||||
}: MuteRegionEditorProps) {
|
||||
const hasRegions = regions.length > 0
|
||||
const hasSegments = audibleSegments.length > 0
|
||||
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-lg p-3 flex flex-col gap-2 max-h-[180px] lg:max-h-[140px]">
|
||||
<div className="flex-1 bg-card border border-border rounded-lg p-3 flex flex-col gap-2 max-h-[140px]">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-semibold">
|
||||
Custom Mix {hasRegions && `(${regions.length} muted)`}
|
||||
Mute Regions {hasRegions && `(${regions.length})`}
|
||||
</span>
|
||||
{hasRegions && (
|
||||
<div className="flex gap-1.5">
|
||||
@@ -79,8 +75,6 @@ export function MuteRegionEditor({
|
||||
<div
|
||||
key={index}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 bg-secondary rounded text-xs"
|
||||
onMouseEnter={() => onHoverRegion?.(index)}
|
||||
onMouseLeave={() => onHoverRegion?.(null)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -100,24 +94,10 @@ export function MuteRegionEditor({
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
{hasSegments ? (
|
||||
<>
|
||||
<p>
|
||||
Want backing vocals but hear lead vocal bleed in some sections?
|
||||
Mute those sections to create a custom mix.
|
||||
</p>
|
||||
<p className="text-muted-foreground/70">
|
||||
Click a segment below to mute it, or{" "}
|
||||
<kbd className="px-1 py-0.5 rounded bg-muted text-[0.65rem] font-mono">
|
||||
Shift
|
||||
</kbd>
|
||||
+drag on the waveform to mark a custom region.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p>No backing vocals detected — clean instrumental recommended.</p>
|
||||
)}
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{hasSegments
|
||||
? "Click segments below or Shift + drag on waveform"
|
||||
: "No backing vocals detected - clean instrumental recommended"}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -129,8 +109,6 @@ export function MuteRegionEditor({
|
||||
key={index}
|
||||
type="button"
|
||||
onClick={() => onAddSegment(index)}
|
||||
onMouseEnter={() => onHoverSegment?.(index)}
|
||||
onMouseLeave={() => onHoverSegment?.(null)}
|
||||
title="Add to mute regions"
|
||||
className="px-1.5 py-0.5 bg-background border border-border rounded text-[10px] text-muted-foreground hover:border-primary hover:text-primary transition-colors"
|
||||
>
|
||||
|
||||
@@ -110,13 +110,6 @@ export function SelectionOptions({
|
||||
<div className="text-xs text-muted-foreground truncate">
|
||||
{option.description}
|
||||
</div>
|
||||
{backingVocalAnalysis?.recommended_selection === option.value && (
|
||||
<div className="text-[10px] text-green-500/80 mt-0.5">
|
||||
{option.value === "clean"
|
||||
? `Very few backing vocals detected (${backingVocalAnalysis.audible_percentage.toFixed(0)}%)`
|
||||
: `Significant backing vocals (${backingVocalAnalysis.audible_percentage.toFixed(0)}%) — may enhance the karaoke experience`}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -13,42 +13,6 @@ interface WaveformViewerProps {
|
||||
onSeek: (time: number) => void
|
||||
onRegionCreate: (start: number, end: number) => void
|
||||
isShiftHeld: boolean
|
||||
highlightedTimeRange?: { start: number; end: number } | null
|
||||
}
|
||||
|
||||
function formatTime(seconds: number): string {
|
||||
if (!Number.isFinite(seconds)) return "0:00"
|
||||
const mins = Math.floor(seconds / 60)
|
||||
const secs = Math.floor(seconds % 60)
|
||||
return `${mins}:${secs.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
const RULER_HEIGHT = 20
|
||||
const NICE_INTERVALS = [1, 2, 5, 10, 15, 30, 60]
|
||||
|
||||
function getTickInterval(duration: number, canvasWidth: number): { major: number; minor: number } {
|
||||
const targetPx = 120
|
||||
const secondsPerPixel = duration / canvasWidth
|
||||
const targetInterval = secondsPerPixel * targetPx
|
||||
|
||||
let major = NICE_INTERVALS[NICE_INTERVALS.length - 1]
|
||||
for (const interval of NICE_INTERVALS) {
|
||||
if (interval >= targetInterval) {
|
||||
major = interval
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Minor ticks: subdivide major interval
|
||||
let minor = major / 4
|
||||
if (major >= 60) minor = 15
|
||||
else if (major >= 30) minor = 10
|
||||
else if (major >= 10) minor = 5
|
||||
else if (major >= 5) minor = 1
|
||||
else if (major >= 2) minor = 0.5
|
||||
else minor = 0.25
|
||||
|
||||
return { major, minor }
|
||||
}
|
||||
|
||||
export function WaveformViewer({
|
||||
@@ -61,7 +25,6 @@ export function WaveformViewer({
|
||||
onSeek,
|
||||
onRegionCreate,
|
||||
isShiftHeld,
|
||||
highlightedTimeRange,
|
||||
}: WaveformViewerProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
@@ -79,8 +42,7 @@ export function WaveformViewer({
|
||||
|
||||
const width = canvas.width
|
||||
const height = canvas.height
|
||||
const waveformHeight = height - RULER_HEIGHT
|
||||
const centerY = waveformHeight / 2
|
||||
const centerY = height / 2
|
||||
|
||||
// Clear with dark background
|
||||
ctx.fillStyle = "#0d1117"
|
||||
@@ -100,7 +62,7 @@ export function WaveformViewer({
|
||||
|
||||
amplitudes.forEach((amp, i) => {
|
||||
const x = i * barWidth
|
||||
const barHeight = Math.max(2, amp * waveformHeight * 0.9)
|
||||
const barHeight = Math.max(2, amp * height * 0.9)
|
||||
const y = centerY - barHeight / 2
|
||||
const time = (i / amplitudes.length) * duration
|
||||
|
||||
@@ -127,79 +89,7 @@ export function WaveformViewer({
|
||||
|
||||
ctx.fillRect(x, y, Math.max(1, barWidth - 0.5), barHeight)
|
||||
})
|
||||
|
||||
// Draw highlight overlay
|
||||
if (highlightedTimeRange && duration > 0) {
|
||||
const startX = (highlightedTimeRange.start / duration) * width
|
||||
const endX = (highlightedTimeRange.end / duration) * width
|
||||
|
||||
// Semi-transparent white overlay on waveform area
|
||||
ctx.fillStyle = "rgba(255, 255, 255, 0.12)"
|
||||
ctx.fillRect(startX, 0, endX - startX, waveformHeight)
|
||||
|
||||
// Vertical edge lines
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.5)"
|
||||
ctx.lineWidth = 1
|
||||
ctx.setLineDash([])
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(startX, 0)
|
||||
ctx.lineTo(startX, waveformHeight)
|
||||
ctx.moveTo(endX, 0)
|
||||
ctx.lineTo(endX, waveformHeight)
|
||||
ctx.stroke()
|
||||
|
||||
// Pink tint in ruler area for highlighted range
|
||||
ctx.fillStyle = "rgba(236, 72, 153, 0.3)"
|
||||
ctx.fillRect(startX, waveformHeight, endX - startX, RULER_HEIGHT)
|
||||
}
|
||||
|
||||
// Draw time ruler
|
||||
const rulerY = waveformHeight
|
||||
ctx.fillStyle = "rgba(0, 0, 0, 0.5)"
|
||||
ctx.fillRect(0, rulerY, width, RULER_HEIGHT)
|
||||
|
||||
// Ruler top border
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.15)"
|
||||
ctx.lineWidth = 1
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(0, rulerY)
|
||||
ctx.lineTo(width, rulerY)
|
||||
ctx.stroke()
|
||||
|
||||
if (duration > 0) {
|
||||
const { major, minor } = getTickInterval(duration, width)
|
||||
|
||||
// Draw minor ticks
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.15)"
|
||||
ctx.lineWidth = 1
|
||||
for (let t = 0; t <= duration; t += minor) {
|
||||
const x = (t / duration) * width
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(x, rulerY)
|
||||
ctx.lineTo(x, rulerY + 4)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Draw major ticks with labels
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.4)"
|
||||
ctx.fillStyle = "rgba(255, 255, 255, 0.6)"
|
||||
ctx.font = "10px monospace"
|
||||
ctx.textBaseline = "bottom"
|
||||
for (let t = 0; t <= duration; t += major) {
|
||||
const x = (t / duration) * width
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(x, rulerY)
|
||||
ctx.lineTo(x, rulerY + 8)
|
||||
ctx.stroke()
|
||||
|
||||
const label = formatTime(t)
|
||||
const textWidth = ctx.measureText(label).width
|
||||
// Avoid drawing label past right edge
|
||||
const labelX = Math.min(x + 3, width - textWidth - 2)
|
||||
ctx.fillText(label, Math.max(2, labelX), rulerY + RULER_HEIGHT - 2)
|
||||
}
|
||||
}
|
||||
}, [amplitudes, duration, muteRegions, audibleSegments, highlightedTimeRange])
|
||||
}, [amplitudes, duration, muteRegions, audibleSegments])
|
||||
|
||||
// Resize canvas
|
||||
const resizeCanvas = useCallback(() => {
|
||||
@@ -228,23 +118,6 @@ export function WaveformViewer({
|
||||
return () => window.removeEventListener("resize", handleResize)
|
||||
}, [resizeCanvas, drawWaveform])
|
||||
|
||||
// Auto-scroll to show highlighted range when zoomed
|
||||
useEffect(() => {
|
||||
const container = containerRef.current
|
||||
const canvas = canvasRef.current
|
||||
if (!container || !canvas || !highlightedTimeRange || !duration || zoomLevel <= 1) return
|
||||
|
||||
const startFraction = highlightedTimeRange.start / duration
|
||||
const endFraction = highlightedTimeRange.end / duration
|
||||
const centerFraction = (startFraction + endFraction) / 2
|
||||
const targetScrollLeft = centerFraction * canvas.width - container.clientWidth / 2
|
||||
|
||||
container.scrollTo({
|
||||
left: Math.max(0, targetScrollLeft),
|
||||
behavior: "smooth",
|
||||
})
|
||||
}, [highlightedTimeRange, duration, zoomLevel])
|
||||
|
||||
// Calculate playhead position
|
||||
const playheadPosition =
|
||||
duration > 0 && canvasRef.current
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import userEvent from "@testing-library/user-event"
|
||||
import { InstrumentalGuidancePanel } from "../InstrumentalGuidancePanel"
|
||||
import type { BackingVocalAnalysis, AudibleSegment } from "@/lib/api"
|
||||
|
||||
// Mock localStorage
|
||||
const localStorageMock = (() => {
|
||||
let store: Record<string, string> = {}
|
||||
return {
|
||||
getItem: jest.fn((key: string) => store[key] || null),
|
||||
setItem: jest.fn((key: string, value: string) => {
|
||||
store[key] = value
|
||||
}),
|
||||
removeItem: jest.fn((key: string) => {
|
||||
delete store[key]
|
||||
}),
|
||||
clear: jest.fn(() => {
|
||||
store = {}
|
||||
}),
|
||||
}
|
||||
})()
|
||||
Object.defineProperty(window, "localStorage", { value: localStorageMock })
|
||||
|
||||
const makeAnalysis = (
|
||||
overrides: Partial<BackingVocalAnalysis> = {}
|
||||
): BackingVocalAnalysis => ({
|
||||
audible_segments: [],
|
||||
audible_percentage: 4,
|
||||
recommended_selection: "clean",
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const makeSegments = (count: number): AudibleSegment[] =>
|
||||
Array.from({ length: count }, (_, i) => ({
|
||||
start_seconds: i * 10,
|
||||
end_seconds: i * 10 + 2,
|
||||
}))
|
||||
|
||||
describe("InstrumentalGuidancePanel", () => {
|
||||
beforeEach(() => {
|
||||
localStorageMock.clear()
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
describe("simple case - clean recommended with low backing vocals", () => {
|
||||
it("shows simplified guidance when clean recommended and < 10% backing vocals", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({ audible_percentage: 4, recommended_selection: "clean" })}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/Choose your karaoke backing track/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/very little backing vocal content/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Clean Instrumental/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows the backing vocal percentage", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({ audible_percentage: 4 })}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/4%/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe("complex case - backing vocals need review", () => {
|
||||
it("shows full workflow steps when backing vocals are significant", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({
|
||||
audible_percentage: 25,
|
||||
recommended_selection: "with_backing",
|
||||
})}
|
||||
audibleSegments={makeSegments(5)}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/Step 1:/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Step 2:/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Step 3/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows segment count in step 1", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({
|
||||
audible_percentage: 25,
|
||||
recommended_selection: "with_backing",
|
||||
})}
|
||||
audibleSegments={makeSegments(3)}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/3 detected/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("explains what backing vocals are", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({
|
||||
audible_percentage: 25,
|
||||
recommended_selection: "with_backing",
|
||||
})}
|
||||
audibleSegments={makeSegments(2)}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/harmony\/chorus voices/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows full steps when clean recommended but >= 10% backing vocals", () => {
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis({
|
||||
audible_percentage: 15,
|
||||
recommended_selection: "clean",
|
||||
})}
|
||||
audibleSegments={makeSegments(3)}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/Step 1:/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Step 2:/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe("dismissal and persistence", () => {
|
||||
it("dismisses tip and stores in localStorage", async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis()}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(screen.getByLabelText("Dismiss tip"))
|
||||
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith(
|
||||
"instrumentalReviewGuidanceDismissed",
|
||||
"true"
|
||||
)
|
||||
expect(screen.queryByText(/Choose your karaoke backing track/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows "Show tips" link after dismissal', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis()}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(screen.getByLabelText("Dismiss tip"))
|
||||
expect(screen.getByText("Show tips")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('restores tip when "Show tips" is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis()}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(screen.getByLabelText("Dismiss tip"))
|
||||
await user.click(screen.getByText("Show tips"))
|
||||
|
||||
expect(screen.getByText(/Choose your karaoke backing track/)).toBeInTheDocument()
|
||||
expect(localStorageMock.removeItem).toHaveBeenCalledWith(
|
||||
"instrumentalReviewGuidanceDismissed"
|
||||
)
|
||||
})
|
||||
|
||||
it("starts dismissed if localStorage has been set", () => {
|
||||
localStorageMock.getItem.mockReturnValueOnce("true")
|
||||
|
||||
render(
|
||||
<InstrumentalGuidancePanel
|
||||
analysis={makeAnalysis()}
|
||||
audibleSegments={[]}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByText(/Choose your karaoke backing track/)).not.toBeInTheDocument()
|
||||
expect(screen.getByText("Show tips")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,118 +0,0 @@
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import userEvent from "@testing-library/user-event"
|
||||
import { MuteRegionEditor } from "../MuteRegionEditor"
|
||||
import type { AudibleSegment } from "@/lib/api"
|
||||
|
||||
const defaultProps = {
|
||||
regions: [],
|
||||
audibleSegments: [] as AudibleSegment[],
|
||||
hasCustom: false,
|
||||
isCreatingCustom: false,
|
||||
onRemoveRegion: jest.fn(),
|
||||
onClearAll: jest.fn(),
|
||||
onCreateCustom: jest.fn(),
|
||||
onSeekTo: jest.fn(),
|
||||
onAddSegment: jest.fn(),
|
||||
onHoverRegion: jest.fn(),
|
||||
onHoverSegment: jest.fn(),
|
||||
}
|
||||
|
||||
describe("MuteRegionEditor", () => {
|
||||
it("shows contextual help when segments exist but no regions", () => {
|
||||
const segments: AudibleSegment[] = [
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
{ start_seconds: 30, end_seconds: 35 },
|
||||
]
|
||||
|
||||
render(
|
||||
<MuteRegionEditor {...defaultProps} audibleSegments={segments} />
|
||||
)
|
||||
|
||||
expect(screen.getByText(/lead vocal bleed/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/custom mix/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows clean recommendation when no segments detected", () => {
|
||||
render(<MuteRegionEditor {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText(/No backing vocals detected/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/clean instrumental recommended/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows shift+drag instruction", () => {
|
||||
const segments: AudibleSegment[] = [
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
]
|
||||
|
||||
render(
|
||||
<MuteRegionEditor {...defaultProps} audibleSegments={segments} />
|
||||
)
|
||||
|
||||
expect(screen.getByText(/drag on the waveform/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows header as "Custom Mix" instead of "Mute Regions"', () => {
|
||||
render(<MuteRegionEditor {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText("Custom Mix")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows region count in header when regions exist", () => {
|
||||
render(
|
||||
<MuteRegionEditor
|
||||
{...defaultProps}
|
||||
regions={[
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
{ start_seconds: 30, end_seconds: 35 },
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText("Custom Mix (2 muted)")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("calls onHoverRegion on mouse enter/leave of region tags", async () => {
|
||||
const onHoverRegion = jest.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<MuteRegionEditor
|
||||
{...defaultProps}
|
||||
onHoverRegion={onHoverRegion}
|
||||
regions={[
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
const regionTag = screen.getByText("0:10 - 0:12").closest("div")!
|
||||
await user.hover(regionTag)
|
||||
expect(onHoverRegion).toHaveBeenCalledWith(0)
|
||||
|
||||
await user.unhover(regionTag)
|
||||
expect(onHoverRegion).toHaveBeenCalledWith(null)
|
||||
})
|
||||
|
||||
it("calls onHoverSegment on mouse enter/leave of segment buttons", async () => {
|
||||
const onHoverSegment = jest.fn()
|
||||
const user = userEvent.setup()
|
||||
const segments: AudibleSegment[] = [
|
||||
{ start_seconds: 10, end_seconds: 12 },
|
||||
]
|
||||
|
||||
render(
|
||||
<MuteRegionEditor
|
||||
{...defaultProps}
|
||||
onHoverSegment={onHoverSegment}
|
||||
audibleSegments={segments}
|
||||
/>
|
||||
)
|
||||
|
||||
const segmentBtn = screen.getByText("0:10 - 0:12")
|
||||
await user.hover(segmentBtn)
|
||||
expect(onHoverSegment).toHaveBeenCalledWith(0)
|
||||
|
||||
await user.unhover(segmentBtn)
|
||||
expect(onHoverSegment).toHaveBeenCalledWith(null)
|
||||
})
|
||||
})
|
||||
@@ -1,85 +0,0 @@
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import { SelectionOptions } from "../SelectionOptions"
|
||||
import type { BackingVocalAnalysis } from "@/lib/api"
|
||||
|
||||
const defaultProps = {
|
||||
value: "clean" as const,
|
||||
onChange: jest.fn(),
|
||||
hasWithBacking: true,
|
||||
hasOriginal: false,
|
||||
hasCustom: false,
|
||||
hasUploaded: false,
|
||||
muteRegionsCount: 0,
|
||||
}
|
||||
|
||||
describe("SelectionOptions", () => {
|
||||
it("shows recommendation reasoning for clean instrumental", () => {
|
||||
const analysis: BackingVocalAnalysis = {
|
||||
audible_segments: [],
|
||||
audible_percentage: 4,
|
||||
recommended_selection: "clean",
|
||||
}
|
||||
|
||||
render(
|
||||
<SelectionOptions
|
||||
{...defaultProps}
|
||||
backingVocalAnalysis={analysis}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText("Recommended")).toBeInTheDocument()
|
||||
expect(screen.getByText(/Very few backing vocals detected \(4%\)/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows recommendation reasoning for with_backing", () => {
|
||||
const analysis: BackingVocalAnalysis = {
|
||||
audible_segments: [],
|
||||
audible_percentage: 25,
|
||||
recommended_selection: "with_backing",
|
||||
}
|
||||
|
||||
render(
|
||||
<SelectionOptions
|
||||
{...defaultProps}
|
||||
value="with_backing"
|
||||
backingVocalAnalysis={analysis}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText("Recommended")).toBeInTheDocument()
|
||||
expect(screen.getByText(/Significant backing vocals \(25%\)/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("does not show reasoning for non-recommended options", () => {
|
||||
const analysis: BackingVocalAnalysis = {
|
||||
audible_segments: [],
|
||||
audible_percentage: 4,
|
||||
recommended_selection: "clean",
|
||||
}
|
||||
|
||||
render(
|
||||
<SelectionOptions
|
||||
{...defaultProps}
|
||||
backingVocalAnalysis={analysis}
|
||||
/>
|
||||
)
|
||||
|
||||
// Only one recommendation reasoning text
|
||||
const reasoningTexts = screen.getAllByText(/backing vocals/)
|
||||
// "No backing vocals" (description) + "Very few backing vocals detected" (reasoning) + "All backing vocals included" (description)
|
||||
expect(reasoningTexts.length).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it("shows custom option with region count when available", () => {
|
||||
render(
|
||||
<SelectionOptions
|
||||
{...defaultProps}
|
||||
hasCustom={true}
|
||||
muteRegionsCount={3}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText("Custom")).toBeInTheDocument()
|
||||
expect(screen.getByText("3 regions muted")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,167 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Job, adminApi } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import {
|
||||
Loader2,
|
||||
RotateCcw,
|
||||
RefreshCw,
|
||||
Trash2,
|
||||
CloudOff,
|
||||
Music,
|
||||
Mic,
|
||||
} from "lucide-react"
|
||||
|
||||
interface AdminJobActionsProps {
|
||||
job: Job
|
||||
onRefresh: () => void
|
||||
}
|
||||
|
||||
export function AdminJobActions({ job, onRefresh }: AdminJobActionsProps) {
|
||||
const [loading, setLoading] = useState<string | null>(null)
|
||||
const { toast } = useToast()
|
||||
|
||||
async function handleAction(
|
||||
actionKey: string,
|
||||
action: () => Promise<void>,
|
||||
confirmMessage: string
|
||||
) {
|
||||
if (!confirm(confirmMessage)) return
|
||||
setLoading(actionKey)
|
||||
try {
|
||||
await action()
|
||||
onRefresh()
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: error?.message || `Failed to ${actionKey}`,
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = (targetState: string, label: string) =>
|
||||
handleAction(`reset-${targetState}`, async () => {
|
||||
await adminApi.resetJob(job.job_id, targetState)
|
||||
toast({ title: "Job Reset", description: `Reset to ${label}` })
|
||||
}, `Reset this job to "${label}"?`)
|
||||
|
||||
const handleDeleteOutputs = () =>
|
||||
handleAction("del-outputs", async () => {
|
||||
await adminApi.deleteJobOutputs(job.job_id)
|
||||
toast({ title: "Outputs Deleted", description: "Distribution files removed" })
|
||||
}, "Delete all output files (YouTube, Dropbox, GDrive)?")
|
||||
|
||||
const handleRegenScreens = () =>
|
||||
handleAction("regen-screens", async () => {
|
||||
const result = await adminApi.regenerateScreens(job.job_id)
|
||||
if (result.worker_triggered) {
|
||||
toast({ title: "Regen Started", description: "Screens are being regenerated" })
|
||||
} else {
|
||||
toast({ title: "Regen Failed", description: result.error || result.message, variant: "destructive" })
|
||||
}
|
||||
}, "Regenerate title/end screens with current metadata?")
|
||||
|
||||
const handleFullRestart = () =>
|
||||
handleAction("full-restart", async () => {
|
||||
const result = await adminApi.restartJob(job.job_id, {
|
||||
preserve_audio_stems: true,
|
||||
delete_outputs: true,
|
||||
})
|
||||
toast({ title: "Job Restarted", description: result.message })
|
||||
}, "Fully restart this job? (preserves audio stems)")
|
||||
|
||||
const handleAudioSearch = () =>
|
||||
handleAction("audio-search", async () => {
|
||||
const result = await adminApi.overrideAudioSource(job.job_id, {
|
||||
source_type: "audio_search",
|
||||
})
|
||||
toast({ title: "Audio Source Changed", description: result.message })
|
||||
}, "Switch this job to audio search mode?")
|
||||
|
||||
const handleDeleteJob = () =>
|
||||
handleAction("delete", async () => {
|
||||
await adminApi.deleteJob(job.job_id)
|
||||
toast({ title: "Job Deleted", description: "Job permanently deleted" })
|
||||
}, "Permanently delete this job and all files? This cannot be undone.")
|
||||
|
||||
const isLoading = (key: string) => loading === key
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-1 flex-wrap mt-2 pt-2 border-t"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<span className="text-[10px] font-medium uppercase tracking-wide mr-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
Reset:
|
||||
</span>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-blue-400 hover:text-blue-300"
|
||||
onClick={() => handleReset("awaiting_audio_selection", "Audio")}
|
||||
disabled={loading !== null}
|
||||
>
|
||||
{isLoading("reset-awaiting_audio_selection") ? <Loader2 className="w-3 h-3 animate-spin" /> : <Music className="w-3 h-3 mr-0.5" />}
|
||||
Audio
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-blue-400 hover:text-blue-300"
|
||||
onClick={() => handleReset("awaiting_review", "Review")}
|
||||
disabled={loading !== null}
|
||||
>
|
||||
{isLoading("reset-awaiting_review") ? <Loader2 className="w-3 h-3 animate-spin" /> : <Mic className="w-3 h-3 mr-0.5" />}
|
||||
Review
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-blue-400 hover:text-blue-300"
|
||||
onClick={() => handleReset("instrumental_selected", "Reprocess")}
|
||||
disabled={loading !== null}
|
||||
>
|
||||
{isLoading("reset-instrumental_selected") ? <Loader2 className="w-3 h-3 animate-spin" /> : <RefreshCw className="w-3 h-3 mr-0.5" />}
|
||||
Reprocess
|
||||
</Button>
|
||||
|
||||
<span className="text-muted-foreground mx-0.5">|</span>
|
||||
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-orange-400 hover:text-orange-300"
|
||||
onClick={handleDeleteOutputs}
|
||||
disabled={loading !== null}
|
||||
>
|
||||
{isLoading("del-outputs") ? <Loader2 className="w-3 h-3 animate-spin" /> : <CloudOff className="w-3 h-3 mr-0.5" />}
|
||||
Del Outputs
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-blue-400 hover:text-blue-300"
|
||||
onClick={handleRegenScreens}
|
||||
disabled={loading !== null}
|
||||
>
|
||||
{isLoading("regen-screens") ? <Loader2 className="w-3 h-3 animate-spin" /> : <RefreshCw className="w-3 h-3 mr-0.5" />}
|
||||
Regen Screens
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-purple-400 hover:text-purple-300"
|
||||
onClick={handleFullRestart}
|
||||
disabled={loading !== null}
|
||||
>
|
||||
{isLoading("full-restart") ? <Loader2 className="w-3 h-3 animate-spin" /> : <RotateCcw className="w-3 h-3 mr-0.5" />}
|
||||
Full Restart
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-amber-400 hover:text-amber-300"
|
||||
onClick={handleAudioSearch}
|
||||
disabled={loading !== null}
|
||||
>
|
||||
{isLoading("audio-search") ? <Loader2 className="w-3 h-3 animate-spin" /> : <Music className="w-3 h-3 mr-0.5" />}
|
||||
Audio Search
|
||||
</Button>
|
||||
|
||||
<span className="text-muted-foreground mx-0.5">|</span>
|
||||
|
||||
<Button variant="ghost" size="sm" className="h-6 px-1.5 text-[11px] text-red-400 hover:text-red-300"
|
||||
onClick={handleDeleteJob}
|
||||
disabled={loading !== null}
|
||||
>
|
||||
{isLoading("delete") ? <Loader2 className="w-3 h-3 animate-spin" /> : <Trash2 className="w-3 h-3 mr-0.5" />}
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,370 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import { AlertTriangle, CheckCircle2, Music } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import Link from "next/link"
|
||||
import { SongInfoStep } from "./steps/SongInfoStep"
|
||||
import { AudioSourceStep } from "./steps/AudioSourceStep"
|
||||
import { CustomizeStep } from "./steps/CustomizeStep"
|
||||
|
||||
interface GuidedJobFlowProps {
|
||||
onJobCreated: () => void
|
||||
}
|
||||
|
||||
type Step = 1 | 2 | 3
|
||||
|
||||
const STEP_LABELS = ["Song Info", "Choose Audio", "Customize & Create"]
|
||||
|
||||
export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
const { user } = useAuth()
|
||||
const { features } = useTenant()
|
||||
const isAdmin = user?.role === "admin"
|
||||
const noCredits = !isAdmin && user?.credits === 0
|
||||
|
||||
const [step, setStep] = useState<Step>(1)
|
||||
const [showSuccess, setShowSuccess] = useState(false)
|
||||
|
||||
// Form state (persists across steps)
|
||||
const [artist, setArtist] = useState("")
|
||||
const [title, setTitle] = useState("")
|
||||
const [displayArtist, setDisplayArtist] = useState("")
|
||||
const [displayTitle, setDisplayTitle] = useState("")
|
||||
const [isPrivate, setIsPrivate] = useState(false)
|
||||
|
||||
// Job tracking
|
||||
const [jobId, setJobId] = useState<string | null>(null)
|
||||
const [audioSource, setAudioSource] = useState<"search" | "upload" | "url">("search")
|
||||
const [selectedResultIndex, setSelectedResultIndex] = useState<number | null>(null)
|
||||
const [searchSessionId, setSearchSessionId] = useState<string | null>(null)
|
||||
|
||||
// Submission state
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [submitError, setSubmitError] = useState("")
|
||||
|
||||
function handleSearchCompleted(sessionId: string) {
|
||||
setSearchSessionId(sessionId)
|
||||
setAudioSource("search")
|
||||
}
|
||||
|
||||
function handleJobCreated(id: string, source: "upload" | "url") {
|
||||
setJobId(id)
|
||||
setAudioSource(source)
|
||||
}
|
||||
|
||||
function handleSearchResultChosen(resultIndex: number) {
|
||||
// Just store the choice — job is created at Step 3 confirm
|
||||
setSelectedResultIndex(resultIndex)
|
||||
setStep(3)
|
||||
}
|
||||
|
||||
function handleFallbackComplete() {
|
||||
// Upload/URL jobs are already processing — show success directly
|
||||
onJobCreated()
|
||||
setShowSuccess(true)
|
||||
}
|
||||
|
||||
async function handleConfirm() {
|
||||
if (!searchSessionId || selectedResultIndex === null) return
|
||||
|
||||
setIsSubmitting(true)
|
||||
setSubmitError("")
|
||||
try {
|
||||
// Create the job now with all final values from Steps 1+3
|
||||
const response = await api.createJobFromSearch({
|
||||
search_session_id: searchSessionId,
|
||||
selection_index: selectedResultIndex,
|
||||
artist: artist,
|
||||
title: title,
|
||||
display_artist: displayArtist.trim() || undefined,
|
||||
display_title: displayTitle.trim() || undefined,
|
||||
is_private: isPrivate,
|
||||
})
|
||||
setJobId(response.job_id)
|
||||
onJobCreated()
|
||||
setShowSuccess(true)
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
setSubmitError(err.message)
|
||||
} else {
|
||||
setSubmitError("Failed to start processing. Please try again.")
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
function handleBackFromAudio() {
|
||||
// Sessions expire naturally — no cleanup needed
|
||||
setSearchSessionId(null)
|
||||
setAudioSource("search")
|
||||
setSelectedResultIndex(null)
|
||||
setStep(1)
|
||||
}
|
||||
|
||||
function resetFlow() {
|
||||
setStep(1)
|
||||
setShowSuccess(false)
|
||||
setArtist("")
|
||||
setTitle("")
|
||||
setDisplayArtist("")
|
||||
setDisplayTitle("")
|
||||
setIsPrivate(false)
|
||||
setJobId(null)
|
||||
setAudioSource("search")
|
||||
setSelectedResultIndex(null)
|
||||
setSearchSessionId(null)
|
||||
setSubmitError("")
|
||||
}
|
||||
|
||||
// Success state
|
||||
if (showSuccess) {
|
||||
const effectiveArtist = displayArtist.trim() || artist
|
||||
const effectiveTitle = displayTitle.trim() || title
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex flex-col items-center text-center py-5 space-y-3">
|
||||
<div
|
||||
className="w-12 h-12 rounded-full flex items-center justify-center"
|
||||
style={{ backgroundColor: 'rgba(34, 197, 94, 0.15)' }}
|
||||
>
|
||||
<CheckCircle2 className="w-7 h-7 text-green-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Job Created
|
||||
</h2>
|
||||
<p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="font-medium" style={{ color: 'var(--text)' }}>{effectiveArtist} - {effectiveTitle}</span>
|
||||
</p>
|
||||
{jobId && (
|
||||
<p className="text-xs mt-0.5 font-mono" style={{ color: 'var(--text-muted)' }} data-testid="created-job-id">
|
||||
ID: {jobId.slice(0, 8)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Timeline */}
|
||||
<p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'var(--text-muted)' }}>What happens next</p>
|
||||
<div className="space-y-0 mt-3">
|
||||
{/* Step 1: Automated processing */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-blue-500/15">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-blue-400">
|
||||
<path d="M8 1.5a1.25 1.25 0 0 1 1.177.825l.573 1.608 1.608.573a1.25 1.25 0 0 1 0 2.354l-1.608.573-.573 1.608a1.25 1.25 0 0 1-2.354 0l-.573-1.608-1.608-.573a1.25 1.25 0 0 1 0-2.354l1.608-.573.573-1.608A1.25 1.25 0 0 1 8 1.5Z" fill="currentColor" opacity="0.85"/>
|
||||
<path d="M12 9a1 1 0 0 1 .94.66l.36 1.02 1.02.36a1 1 0 0 1 0 1.884l-1.02.36-.36 1.02a1 1 0 0 1-1.88 0l-.36-1.02-1.02-.36a1 1 0 0 1 0-1.884l1.02-.36.36-1.02A1 1 0 0 1 12 9Z" fill="currentColor" opacity="0.55"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: 'var(--card-border)' }} />
|
||||
</div>
|
||||
<div className="pb-4 pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Audio processing</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
We download the audio, separate vocals from the instrumental, and transcribe the lyrics. <span className="font-medium" style={{ color: 'var(--text)' }}>~10 minutes</span>
|
||||
</p>
|
||||
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-blue-500/15 text-blue-400">
|
||||
Automatic
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step 2: User review */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: 'rgba(255, 122, 204, 0.15)' }}>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ color: 'var(--brand-pink)' }}>
|
||||
<path d="M8 2a3 3 0 1 0 0 6 3 3 0 0 0 0-6ZM3.5 13.5c0-2.485 2.015-4.5 4.5-4.5s4.5 2.015 4.5 4.5a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5Z" fill="currentColor" opacity="0.85"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: 'var(--card-border)' }} />
|
||||
</div>
|
||||
<div className="pb-4 pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>You review the lyrics & instrumental</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
Check the lyrics and listen to the instrumental. Fix any errors and approve.
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
|
||||
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: 'rgba(255, 122, 204, 0.15)', color: 'var(--brand-pink)' }}>
|
||||
You
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
|
||||
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
|
||||
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
|
||||
</svg>
|
||||
Email + chime when ready
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step 3: Final render */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-green-500/15">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-green-400">
|
||||
<path d="M3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v11a.5.5 0 0 1-.765.424L8 11.28l-4.235 2.644A.5.5 0 0 1 3 13.5v-11Z" fill="currentColor" opacity="0.5"/>
|
||||
<path d="M6.354 7.854 7.5 9l2.146-2.146a.5.5 0 0 0-.708-.708L7.5 7.586l-.646-.647a.5.5 0 1 0-.708.708l.208.207Z" fill="currentColor"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Video delivered</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
After you approve, your karaoke video is rendered and uploaded. <span className="font-medium" style={{ color: 'var(--text)' }}>~10 minutes</span>
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
|
||||
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-green-500/15 text-green-400">
|
||||
Automatic
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
|
||||
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
|
||||
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
|
||||
</svg>
|
||||
Email with link to view
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-[10px] text-center" style={{ color: 'var(--text-muted)' }}>
|
||||
Track progress in the <span className="font-medium" style={{ color: 'var(--text)' }}>Recent Jobs</span> list. Keep this tab open to hear the chime.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={resetFlow}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
>
|
||||
<Music className="w-4 h-4 mr-2" />
|
||||
Create Another
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Zero-credit warning banner */}
|
||||
{noCredits && (
|
||||
<div className="flex items-start gap-2 rounded-lg p-3 border border-amber-500/30 bg-amber-500/10">
|
||||
<AlertTriangle className="w-5 h-5 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-sm" style={{ color: 'var(--text)' }}>
|
||||
<p>You have no credits remaining. Buy credits to create new karaoke videos.</p>
|
||||
<Link
|
||||
href="/#pricing"
|
||||
className="inline-block mt-1 text-sm font-medium underline"
|
||||
style={{ color: 'var(--brand-pink)' }}
|
||||
>
|
||||
Buy Credits
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Step indicator */}
|
||||
<div className="flex items-center gap-1" role="navigation" aria-label="Progress">
|
||||
{STEP_LABELS.map((label, i) => {
|
||||
const stepNum = (i + 1) as Step
|
||||
const isActive = step === stepNum
|
||||
const isCompleted = step > stepNum
|
||||
|
||||
return (
|
||||
<div key={label} className="flex items-center gap-1 flex-1">
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
<div
|
||||
className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-semibold shrink-0 transition-colors ${
|
||||
isActive
|
||||
? 'bg-[var(--brand-pink)] text-white'
|
||||
: isCompleted
|
||||
? 'bg-[var(--brand-pink)]/20 text-[var(--brand-pink)]'
|
||||
: 'bg-[var(--secondary)] text-[var(--text-muted)]'
|
||||
}`}
|
||||
>
|
||||
{isCompleted ? "\u2713" : stepNum}
|
||||
</div>
|
||||
<span
|
||||
className={`text-[10px] whitespace-nowrap transition-colors ${
|
||||
isActive ? 'font-medium' : ''
|
||||
}`}
|
||||
style={{ color: isActive ? 'var(--text)' : 'var(--text-muted)' }}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
{i < STEP_LABELS.length - 1 && (
|
||||
<div
|
||||
className="h-px flex-1 mx-1 hidden sm:block"
|
||||
style={{
|
||||
backgroundColor: isCompleted ? 'var(--brand-pink)' : 'var(--card-border)',
|
||||
opacity: isCompleted ? 0.4 : 1,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Submit error */}
|
||||
{submitError && (
|
||||
<div className="text-sm text-red-400 bg-red-500/10 rounded p-3">
|
||||
<p>{submitError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Step content */}
|
||||
{step === 1 && (
|
||||
<SongInfoStep
|
||||
artist={artist}
|
||||
title={title}
|
||||
onArtistChange={setArtist}
|
||||
onTitleChange={setTitle}
|
||||
onNext={() => setStep(2)}
|
||||
disabled={noCredits}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<AudioSourceStep
|
||||
artist={artist}
|
||||
title={title}
|
||||
displayArtist={displayArtist}
|
||||
displayTitle={displayTitle}
|
||||
isPrivate={isPrivate}
|
||||
onSearchCompleted={handleSearchCompleted}
|
||||
onJobCreated={handleJobCreated}
|
||||
onSearchResultChosen={handleSearchResultChosen}
|
||||
onFallbackComplete={handleFallbackComplete}
|
||||
onBack={handleBackFromAudio}
|
||||
noCredits={noCredits}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<CustomizeStep
|
||||
artist={artist}
|
||||
title={title}
|
||||
displayArtist={displayArtist}
|
||||
displayTitle={displayTitle}
|
||||
onDisplayArtistChange={setDisplayArtist}
|
||||
onDisplayTitleChange={setDisplayTitle}
|
||||
isPrivate={isPrivate}
|
||||
onPrivateChange={setIsPrivate}
|
||||
onConfirm={handleConfirm}
|
||||
onBack={() => setStep(2)}
|
||||
isSubmitting={isSubmitting}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { Job, api } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import {
|
||||
Loader2, RotateCcw, Trash2
|
||||
Loader2, RotateCcw, XCircle
|
||||
} from "lucide-react"
|
||||
|
||||
interface JobActionsProps {
|
||||
@@ -15,11 +15,11 @@ interface JobActionsProps {
|
||||
|
||||
export function JobActions({ job, onRefresh }: JobActionsProps) {
|
||||
const [isRetrying, setIsRetrying] = useState(false)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const [isCancelling, setIsCancelling] = useState(false)
|
||||
const { toast } = useToast()
|
||||
|
||||
const canRetry = job.status === "failed"
|
||||
const canDelete = !["complete", "failed", "prep_complete"].includes(job.status)
|
||||
const canRetry = job.status === "failed" || job.status === "cancelled"
|
||||
const canCancel = !["complete", "failed", "cancelled"].includes(job.status)
|
||||
|
||||
async function handleRetry() {
|
||||
setIsRetrying(true)
|
||||
@@ -49,60 +49,46 @@ export function JobActions({ job, onRefresh }: JobActionsProps) {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
if (!confirm("Are you sure you want to permanently cancel and delete this job? This cannot be undone.")) return
|
||||
async function handleCancel() {
|
||||
if (!confirm("Are you sure you want to cancel this job?")) return
|
||||
|
||||
setIsDeleting(true)
|
||||
setIsCancelling(true)
|
||||
try {
|
||||
await api.deleteJob(job.job_id)
|
||||
toast({
|
||||
title: "Job deleted",
|
||||
description: "The job has been permanently deleted.",
|
||||
})
|
||||
await api.cancelJob(job.job_id)
|
||||
onRefresh()
|
||||
} catch (error: any) {
|
||||
console.error("Failed to delete job:", error)
|
||||
|
||||
const errorMessage = error?.response?.data?.detail ||
|
||||
error?.message ||
|
||||
"Failed to delete job. Please try again."
|
||||
|
||||
toast({
|
||||
title: "Delete failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to cancel job:", error)
|
||||
} finally {
|
||||
setIsDeleting(false)
|
||||
setIsCancelling(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Don't render anything if no actions are available
|
||||
if (!canDelete && !canRetry) {
|
||||
if (!canCancel && !canRetry) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2" onClick={(e) => e.stopPropagation()}>
|
||||
{/* Delete button (red) */}
|
||||
{canDelete && (
|
||||
{/* Cancel button (red) */}
|
||||
{canCancel && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleDelete}
|
||||
disabled={isDeleting}
|
||||
onClick={handleCancel}
|
||||
disabled={isCancelling}
|
||||
className="text-xs text-red-400 hover:text-red-300"
|
||||
>
|
||||
{isDeleting ? (
|
||||
{isCancelling ? (
|
||||
<Loader2 className="w-3 h-3 mr-1 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="w-3 h-3 mr-1" />
|
||||
<XCircle className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Delete
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Retry button (failed jobs only) */}
|
||||
{/* Retry button */}
|
||||
{canRetry && (
|
||||
<Button
|
||||
size="sm"
|
||||
|
||||
@@ -5,7 +5,6 @@ import { Job } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Zap } from "lucide-react"
|
||||
import { JobActions } from "./JobActions"
|
||||
import { AdminJobActions } from "./AdminJobActions"
|
||||
import { OutputLinks } from "./OutputLinks"
|
||||
import { AudioSearchDialog } from "../audio-search/AudioSearchDialog"
|
||||
import { getJobStep, formatStepIndicator, getJobProgressPercent } from "@/lib/job-status"
|
||||
@@ -72,10 +71,9 @@ function ProgressBar({ job }: { job: Job }) {
|
||||
interface JobCardProps {
|
||||
job: Job
|
||||
onRefresh: () => void
|
||||
showAdminControls?: boolean
|
||||
}
|
||||
|
||||
export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
export function JobCard({ job, onRefresh }: JobCardProps) {
|
||||
const [showAudioSearch, setShowAudioSearch] = useState(false)
|
||||
const { user } = useAuth()
|
||||
const isAdmin = user?.role === 'admin'
|
||||
@@ -191,23 +189,17 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions row: Delete/secondary on left, primary action on right */}
|
||||
{/* Actions row: Cancel/secondary on left, primary action on right */}
|
||||
<div className="mt-2 flex items-center justify-between">
|
||||
<JobActions job={job} onRefresh={onRefresh} />
|
||||
{renderPrimaryAction()}
|
||||
</div>
|
||||
|
||||
{/* Admin controls (toggled via header button) */}
|
||||
{showAdminControls && (
|
||||
<AdminJobActions job={job} onRefresh={onRefresh} />
|
||||
)}
|
||||
|
||||
<AudioSearchDialog
|
||||
jobId={job.job_id}
|
||||
open={showAudioSearch}
|
||||
onClose={() => setShowAudioSearch(false)}
|
||||
onSelect={onRefresh}
|
||||
searchTitle={job.title}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -63,7 +63,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
const [displayTitle, setDisplayTitle] = useState("")
|
||||
const [showDisplayAs, setShowDisplayAs] = useState(false)
|
||||
|
||||
// Private (no YouTube upload) mode - Dropbox only, no YouTube/GDrive
|
||||
// Non-interactive mode (shared across all tabs)
|
||||
const [nonInteractive, setNonInteractive] = useState(false)
|
||||
|
||||
// Private (non-published) mode - Dropbox only, no YouTube/GDrive
|
||||
const [isPrivate, setIsPrivate] = useState(false)
|
||||
|
||||
// Credit enforcement
|
||||
@@ -86,6 +89,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await api.uploadJob(uploadFile, uploadArtist.trim(), uploadTitle.trim(), {
|
||||
non_interactive: nonInteractive,
|
||||
is_private: isPrivate,
|
||||
})
|
||||
setUploadFile(null)
|
||||
@@ -127,6 +131,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
youtubeArtist.trim(),
|
||||
youtubeTitle.trim(),
|
||||
{
|
||||
non_interactive: nonInteractive,
|
||||
is_private: isPrivate,
|
||||
}
|
||||
)
|
||||
@@ -161,6 +166,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await api.searchAudio(searchArtist.trim(), searchTitle.trim(), false, {
|
||||
non_interactive: nonInteractive,
|
||||
is_private: isPrivate,
|
||||
// Display overrides (empty string means use search values)
|
||||
display_artist: displayArtist.trim() || undefined,
|
||||
@@ -316,7 +322,32 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
<span className="text-amber-500 font-medium">Note:</span> Format these exactly as you want them on the title card and video filename.
|
||||
</p>
|
||||
|
||||
{/* Private (no YouTube upload) mode */}
|
||||
{/* Non-interactive mode (admin only) */}
|
||||
{isAdmin && (
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="non-interactive-upload"
|
||||
checked={nonInteractive}
|
||||
onChange={(e) => setNonInteractive(e.target.checked)}
|
||||
disabled={isSubmitting}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="non-interactive-upload" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Skip lyrics review (non-interactive)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="text-amber-500 font-medium">Warning:</span> auto lyrics correction isn't perfect.
|
||||
Skipping review will likely result in incorrect words in your karaoke video.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Private (non-published) mode */}
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
@@ -329,7 +360,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="private-upload" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (no YouTube upload)
|
||||
Private (non-published)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
@@ -413,7 +444,32 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
<span className="text-amber-500 font-medium">Note:</span> Format these exactly as you want them on the title card and video filename.
|
||||
</p>
|
||||
|
||||
{/* Private (no YouTube upload) mode */}
|
||||
{/* Non-interactive mode (admin only) */}
|
||||
{isAdmin && (
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="non-interactive-url"
|
||||
checked={nonInteractive}
|
||||
onChange={(e) => setNonInteractive(e.target.checked)}
|
||||
disabled={isSubmitting}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="non-interactive-url" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Skip lyrics review (non-interactive)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="text-amber-500 font-medium">Warning:</span> auto lyrics correction isn't perfect.
|
||||
Skipping review will likely result in incorrect words in your karaoke video.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Private (non-published) mode */}
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
@@ -426,7 +482,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="private-url" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (no YouTube upload)
|
||||
Private (non-published)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
@@ -548,7 +604,32 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Private (no YouTube upload) mode */}
|
||||
{/* Non-interactive mode (admin only) */}
|
||||
{isAdmin && (
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="non-interactive-search"
|
||||
checked={nonInteractive}
|
||||
onChange={(e) => setNonInteractive(e.target.checked)}
|
||||
disabled={isSubmitting}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="non-interactive-search" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Skip lyrics review (non-interactive)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="text-amber-500 font-medium">Warning:</span> auto lyrics correction isn't perfect.
|
||||
Skipping review will likely result in incorrect words in your karaoke video.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Private (non-published) mode */}
|
||||
<div className="space-y-2 pt-4 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
@@ -561,7 +642,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="private-search" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (no YouTube upload)
|
||||
Private (non-published)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useEffect, useCallback } from "react"
|
||||
|
||||
interface TitleCardPreviewProps {
|
||||
artist: string
|
||||
title: string
|
||||
}
|
||||
|
||||
// Matches the Nomad theme title card (style_params.json from GCS):
|
||||
// - 3840x2160 canvas (16:9)
|
||||
// - Background: karaoke-title-screen-background-nomad-4k.png
|
||||
// - Font: AvenirNext-Bold.ttf
|
||||
// - Title: white (#ffffff), uppercase, region 370,980,3100,350
|
||||
// - Artist: golden yellow (#ffdf6b), uppercase, region 370,1400,3100,450
|
||||
|
||||
const CANVAS_W = 3840
|
||||
const CANVAS_H = 2160
|
||||
|
||||
// Title region: x=370, y=980, w=3100, h=350
|
||||
const TITLE_X = 370
|
||||
const TITLE_Y = 980
|
||||
const TITLE_W = 3100
|
||||
const TITLE_H = 350
|
||||
|
||||
// Artist region: x=370, y=1400, w=3100, h=450
|
||||
const ARTIST_X = 370
|
||||
const ARTIST_Y = 1400
|
||||
const ARTIST_W = 3100
|
||||
const ARTIST_H = 450
|
||||
|
||||
const TITLE_COLOR = "#ffffff"
|
||||
const ARTIST_COLOR = "#ffdf6b"
|
||||
|
||||
let bgImageCache: HTMLImageElement | null = null
|
||||
|
||||
function loadBgImage(): Promise<HTMLImageElement> {
|
||||
if (bgImageCache?.complete) return Promise.resolve(bgImageCache)
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
bgImageCache = img
|
||||
resolve(img)
|
||||
}
|
||||
img.onerror = reject
|
||||
img.src = "/title-card-bg.png"
|
||||
})
|
||||
}
|
||||
|
||||
function fitText(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
text: string,
|
||||
maxWidth: number,
|
||||
maxHeight: number,
|
||||
fontFamily: string,
|
||||
): { fontSize: number; lines: string[] } {
|
||||
for (let size = 500; size >= 40; size -= 10) {
|
||||
ctx.font = `700 ${size}px ${fontFamily}`
|
||||
const metrics = ctx.measureText(text)
|
||||
|
||||
if (metrics.width <= maxWidth) {
|
||||
return { fontSize: size, lines: [text] }
|
||||
}
|
||||
|
||||
// Try 2-line split
|
||||
const words = text.split(" ")
|
||||
if (words.length >= 2) {
|
||||
let bestSplit = 1
|
||||
let bestDiff = Infinity
|
||||
for (let i = 1; i < words.length; i++) {
|
||||
const line1 = words.slice(0, i).join(" ")
|
||||
const line2 = words.slice(i).join(" ")
|
||||
const diff = Math.abs(ctx.measureText(line1).width - ctx.measureText(line2).width)
|
||||
if (diff < bestDiff) {
|
||||
bestDiff = diff
|
||||
bestSplit = i
|
||||
}
|
||||
}
|
||||
const line1 = words.slice(0, bestSplit).join(" ")
|
||||
const line2 = words.slice(bestSplit).join(" ")
|
||||
const w1 = ctx.measureText(line1).width
|
||||
const w2 = ctx.measureText(line2).width
|
||||
const lineHeight = size * 1.1
|
||||
|
||||
if (Math.max(w1, w2) <= maxWidth && lineHeight * 2 <= maxHeight) {
|
||||
return { fontSize: size, lines: [line1, line2] }
|
||||
}
|
||||
}
|
||||
}
|
||||
return { fontSize: 40, lines: [text] }
|
||||
}
|
||||
|
||||
function drawTextBlock(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
text: string,
|
||||
regionX: number,
|
||||
regionY: number,
|
||||
regionW: number,
|
||||
regionH: number,
|
||||
color: string,
|
||||
fontFamily: string,
|
||||
) {
|
||||
if (!text) return
|
||||
|
||||
ctx.fillStyle = color
|
||||
ctx.textAlign = "center"
|
||||
ctx.textBaseline = "middle"
|
||||
|
||||
const { fontSize, lines } = fitText(ctx, text, regionW, regionH, fontFamily)
|
||||
ctx.font = `700 ${fontSize}px ${fontFamily}`
|
||||
|
||||
const lineHeight = fontSize * 1.1
|
||||
const totalHeight = lineHeight * lines.length
|
||||
const startY = regionY + (regionH - totalHeight) / 2 + lineHeight / 2
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
ctx.fillText(lines[i], regionX + regionW / 2, startY + i * lineHeight)
|
||||
}
|
||||
}
|
||||
|
||||
export function TitleCardPreview({ artist, title }: TitleCardPreviewProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
|
||||
const draw = useCallback(async () => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
|
||||
// Draw background image (or black fallback)
|
||||
try {
|
||||
const bgImg = await loadBgImage()
|
||||
ctx.drawImage(bgImg, 0, 0, CANVAS_W, CANVAS_H)
|
||||
} catch {
|
||||
ctx.fillStyle = "#000000"
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
|
||||
// Get computed font family from CSS variable
|
||||
const computedFont = getComputedStyle(canvas).getPropertyValue("--font-title-card").trim()
|
||||
const fontFamily = computedFont || "'AvenirNext-Bold', 'Avenir Next', sans-serif"
|
||||
|
||||
// Ensure font is loaded before rendering — canvas doesn't participate in CSS
|
||||
// font swap, so we must explicitly wait for the font to be available.
|
||||
const fontSpec = `700 100px ${fontFamily}`
|
||||
if (!document.fonts.check(fontSpec)) {
|
||||
try {
|
||||
await document.fonts.load(fontSpec)
|
||||
} catch {
|
||||
// Font failed to load; will render with fallback
|
||||
}
|
||||
}
|
||||
|
||||
// Apply uppercase transform (matching style_params.json title_text_transform/artist_text_transform)
|
||||
const titleText = (title || "Song Title").toUpperCase()
|
||||
const artistText = (artist || "Artist").toUpperCase()
|
||||
|
||||
// Draw title (white)
|
||||
drawTextBlock(
|
||||
ctx,
|
||||
titleText,
|
||||
TITLE_X, TITLE_Y, TITLE_W, TITLE_H,
|
||||
title ? TITLE_COLOR : "rgba(255,255,255,0.25)",
|
||||
fontFamily,
|
||||
)
|
||||
|
||||
// Draw artist (golden yellow)
|
||||
drawTextBlock(
|
||||
ctx,
|
||||
artistText,
|
||||
ARTIST_X, ARTIST_Y, ARTIST_W, ARTIST_H,
|
||||
artist ? ARTIST_COLOR : "rgba(255,223,107,0.25)",
|
||||
fontFamily,
|
||||
)
|
||||
}, [artist, title])
|
||||
|
||||
useEffect(() => {
|
||||
draw()
|
||||
}, [draw])
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={CANVAS_W}
|
||||
height={CANVAS_H}
|
||||
className="w-full rounded-lg"
|
||||
style={{
|
||||
aspectRatio: "16/9",
|
||||
border: "1px solid var(--card-border)",
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
import { render, act } from "@testing-library/react"
|
||||
import { TitleCardPreview } from "../TitleCardPreview"
|
||||
|
||||
// Module-level state shared with mock closures via reference
|
||||
const state = {
|
||||
fillTextCalls: [] as Array<{ text: string; font: string }>,
|
||||
currentFont: "",
|
||||
fontCheckReturn: true,
|
||||
fontLoadResolve: null as (() => void) | null,
|
||||
}
|
||||
|
||||
// Mock Image globally before any module code runs
|
||||
global.Image = class MockImage {
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
_src = ""
|
||||
complete = true
|
||||
get src() {
|
||||
return this._src
|
||||
}
|
||||
set src(v: string) {
|
||||
this._src = v
|
||||
// Fire synchronously to avoid timing issues in tests
|
||||
Promise.resolve().then(() => this.onload?.())
|
||||
}
|
||||
} as unknown as typeof Image
|
||||
|
||||
function setupMocks() {
|
||||
state.fillTextCalls = []
|
||||
state.currentFont = ""
|
||||
state.fontCheckReturn = true
|
||||
state.fontLoadResolve = null
|
||||
|
||||
HTMLCanvasElement.prototype.getContext = jest.fn(() => ({
|
||||
drawImage: jest.fn(),
|
||||
fillRect: jest.fn(),
|
||||
fillText: jest.fn((text: string) => {
|
||||
state.fillTextCalls.push({ text, font: state.currentFont })
|
||||
}),
|
||||
measureText: jest.fn(() => ({ width: 100 })),
|
||||
get font() {
|
||||
return state.currentFont
|
||||
},
|
||||
set font(v: string) {
|
||||
state.currentFont = v
|
||||
},
|
||||
fillStyle: "",
|
||||
textAlign: "",
|
||||
textBaseline: "",
|
||||
})) as unknown as typeof HTMLCanvasElement.prototype.getContext
|
||||
|
||||
window.getComputedStyle = jest.fn(() => ({
|
||||
getPropertyValue: (prop: string) => {
|
||||
if (prop === "--font-title-card") return "'__AvenirNext_abc123'"
|
||||
return ""
|
||||
},
|
||||
})) as unknown as typeof window.getComputedStyle
|
||||
|
||||
Object.defineProperty(document, "fonts", {
|
||||
value: {
|
||||
check: jest.fn(() => state.fontCheckReturn),
|
||||
load: jest.fn(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
state.fontLoadResolve = resolve
|
||||
}),
|
||||
),
|
||||
ready: Promise.resolve(),
|
||||
},
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setupMocks()
|
||||
})
|
||||
|
||||
describe("TitleCardPreview", () => {
|
||||
it("renders title and artist text in uppercase", async () => {
|
||||
await act(async () => {
|
||||
render(<TitleCardPreview title="My Song" artist="Cool Band" />)
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
})
|
||||
|
||||
const texts = state.fillTextCalls.map((c) => c.text)
|
||||
expect(texts).toContain("MY SONG")
|
||||
expect(texts).toContain("COOL BAND")
|
||||
})
|
||||
|
||||
it("uses font from CSS variable for canvas text", async () => {
|
||||
await act(async () => {
|
||||
render(<TitleCardPreview title="Test" artist="Artist" />)
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
})
|
||||
|
||||
const fonts = state.fillTextCalls.map((c) => c.font)
|
||||
expect(fonts.length).toBeGreaterThan(0)
|
||||
expect(fonts.every((f) => f.includes("'__AvenirNext_abc123'"))).toBe(true)
|
||||
})
|
||||
|
||||
it("skips document.fonts.load when font is already available", async () => {
|
||||
state.fontCheckReturn = true
|
||||
|
||||
await act(async () => {
|
||||
render(<TitleCardPreview title="Song" artist="Artist" />)
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
})
|
||||
|
||||
expect(document.fonts.check).toHaveBeenCalledWith(
|
||||
expect.stringContaining("'__AvenirNext_abc123'"),
|
||||
)
|
||||
expect(document.fonts.load).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("calls document.fonts.load when font is not yet available", async () => {
|
||||
state.fontCheckReturn = false
|
||||
|
||||
await act(async () => {
|
||||
render(<TitleCardPreview title="Song" artist="Artist" />)
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
// Resolve the pending font load promise
|
||||
state.fontLoadResolve?.()
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
})
|
||||
|
||||
expect(document.fonts.check).toHaveBeenCalledWith(
|
||||
expect.stringContaining("'__AvenirNext_abc123'"),
|
||||
)
|
||||
expect(document.fonts.load).toHaveBeenCalledWith(
|
||||
expect.stringContaining("'__AvenirNext_abc123'"),
|
||||
)
|
||||
})
|
||||
|
||||
it("still renders text if font load fails", async () => {
|
||||
state.fontCheckReturn = false
|
||||
;(document.fonts as { load: jest.Mock }).load = jest.fn().mockRejectedValue(new Error("fail"))
|
||||
|
||||
await act(async () => {
|
||||
render(<TitleCardPreview title="Fallback" artist="Test" />)
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
})
|
||||
|
||||
const texts = state.fillTextCalls.map((c) => c.text)
|
||||
expect(texts).toContain("FALLBACK")
|
||||
})
|
||||
})
|
||||