mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 17:47:11 +09:00
Compare commits
No files matched your search
+68
-14
@@ -902,6 +902,22 @@ jobs:
|
||||
# - / (main app)
|
||||
# - /app/jobs/{id}/lyrics (lyrics review)
|
||||
# - /app/jobs/{id}/instrumental (instrumental review)
|
||||
- name: Capture build metadata
|
||||
id: frontend-meta
|
||||
run: |
|
||||
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
|
||||
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
|
||||
if [ -n "$PR_NUM" ]; then
|
||||
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
|
||||
else
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
@@ -911,6 +927,10 @@ jobs:
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
|
||||
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
|
||||
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
|
||||
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
|
||||
run: npm run build
|
||||
|
||||
- name: Deploy consumer to Cloudflare Pages
|
||||
@@ -929,6 +949,10 @@ jobs:
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
NEXT_PUBLIC_TENANT_PORTAL: "true"
|
||||
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
|
||||
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
|
||||
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
|
||||
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
|
||||
run: npm run build
|
||||
|
||||
- name: Deploy tenant portal to Cloudflare Pages
|
||||
@@ -1008,6 +1032,23 @@ jobs:
|
||||
echo "📋 Current version: $VERSION"
|
||||
echo "🚀 Deploying on every push to main"
|
||||
|
||||
- name: Capture build metadata
|
||||
id: build-meta
|
||||
run: |
|
||||
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
|
||||
# For squash-merge commits, PR number is in the commit message as (#NNN)
|
||||
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
|
||||
if [ -n "$PR_NUM" ]; then
|
||||
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
|
||||
else
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Authenticate to Google Cloud (Workload Identity)
|
||||
id: auth
|
||||
uses: google-github-actions/auth@v2
|
||||
@@ -1186,24 +1227,37 @@ jobs:
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
DEPLOY_TEST_PATH="gs://karaoke-gen-storage-nomadkaraoke/deploy-test"
|
||||
|
||||
echo "Uploading test assets to GCS..."
|
||||
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
|
||||
gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass
|
||||
"${DEPLOY_TEST_PATH}/test-preview.ass"
|
||||
gsutil cp infrastructure/encoding-worker/test-assets/test-audio.flac \
|
||||
"${DEPLOY_TEST_PATH}/test-audio.flac"
|
||||
|
||||
echo "Submitting test encode to $SECONDARY_IP..."
|
||||
RESPONSE=$(curl -sf -X POST "http://${SECONDARY_IP}:8080/encode-preview" \
|
||||
HTTP_CODE=$(curl -s -o /tmp/encode-response.json -w '%{http_code}' \
|
||||
-X POST "http://${SECONDARY_IP}:8080/encode-preview" \
|
||||
-H "X-API-Key: $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"job_id": "deploy-health-check",
|
||||
"ass_gcs_path": "gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass",
|
||||
"duration_seconds": 10
|
||||
}')
|
||||
-d "{
|
||||
\"job_id\": \"deploy-health-check\",
|
||||
\"ass_gcs_path\": \"${DEPLOY_TEST_PATH}/test-preview.ass\",
|
||||
\"audio_gcs_path\": \"${DEPLOY_TEST_PATH}/test-audio.flac\",
|
||||
\"output_gcs_path\": \"${DEPLOY_TEST_PATH}/output-preview.mp4\"
|
||||
}") || HTTP_CODE="000"
|
||||
RESPONSE=$(cat /tmp/encode-response.json 2>/dev/null || echo "{}")
|
||||
|
||||
echo "Encode response (HTTP $HTTP_CODE): $RESPONSE"
|
||||
if [ "$HTTP_CODE" != "200" ] && [ "$HTTP_CODE" != "202" ]; then
|
||||
echo "::error::Encode request failed with HTTP $HTTP_CODE"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Encode response: $RESPONSE"
|
||||
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
|
||||
|
||||
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "completed" ]; then
|
||||
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "cached" ] && [ "$STATUS" != "in_progress" ]; then
|
||||
echo "::error::Encode test failed with status: $STATUS"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
@@ -1211,11 +1265,11 @@ jobs:
|
||||
|
||||
for i in $(seq 1 12); do
|
||||
sleep 5
|
||||
JOB_STATUS=$(curl -sf \
|
||||
JOB_STATUS=$(curl -s \
|
||||
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
|
||||
-H "X-API-Key: $API_KEY" | jq -r '.status // "unknown"')
|
||||
-H "X-API-Key: $API_KEY" 2>/dev/null | jq -r '.status // "unknown"' 2>/dev/null) || JOB_STATUS="unknown"
|
||||
echo "Encode status: $JOB_STATUS (attempt $i/12)"
|
||||
if [ "$JOB_STATUS" = "completed" ]; then
|
||||
if [ "$JOB_STATUS" = "complete" ]; then
|
||||
echo "Encode test passed!"
|
||||
echo "passed=true" >> $GITHUB_OUTPUT
|
||||
gsutil rm -f gs://karaoke-gen-storage-nomadkaraoke/deploy-test/** || true
|
||||
@@ -1232,7 +1286,7 @@ jobs:
|
||||
exit 1
|
||||
|
||||
- name: Rollback on failure
|
||||
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed == 'false'
|
||||
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed != 'true'
|
||||
run: |
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
if [ -n "$SECONDARY_VM" ]; then
|
||||
@@ -1556,7 +1610,7 @@ jobs:
|
||||
--min-instances 1 \
|
||||
--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,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,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true" \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,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,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--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"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
[{"name":"generate-buildid","duration":272,"timestamp":244518298649,"id":4,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"load-custom-routes","duration":314,"timestamp":244518299029,"id":5,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"create-dist-dir","duration":333,"timestamp":244518299363,"id":6,"parentId":1,"tags":{},"startTime":1775262331362,"traceId":"b3ef0d179e8acedf"},{"name":"clean","duration":358,"timestamp":244518300558,"id":7,"parentId":1,"tags":{},"startTime":1775262331363,"traceId":"b3ef0d179e8acedf"},{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
|
||||
@@ -0,0 +1 @@
|
||||
[{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
|
||||
@@ -29,6 +29,8 @@ tmp/
|
||||
# Google Cloud
|
||||
.gcloud/
|
||||
*.json
|
||||
# Allow i18n translation files
|
||||
!translations/*.json
|
||||
|
||||
# Testing
|
||||
.pytest_cache/
|
||||
|
||||
@@ -11,10 +11,11 @@ import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Tuple, List, Optional, Any, Dict
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
@@ -53,6 +53,7 @@ from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from pathlib import Path
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -309,17 +310,17 @@ def _validate_and_prepare_selection(
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
|
||||
|
||||
# Get search results from state_data
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="No search results available")
|
||||
raise HTTPException(status_code=400, detail=t("en", "audioSearch.noSearchResults"))
|
||||
|
||||
if selection_index < 0 or selection_index >= len(search_results):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid selection index {selection_index}. Valid range: 0-{len(search_results)-1}"
|
||||
detail=t("en", "audioSearch.invalidSelectionIndex", selection_index=selection_index, max=len(search_results)-1)
|
||||
)
|
||||
|
||||
selected = search_results[selection_index]
|
||||
@@ -594,12 +595,14 @@ async def search_audio(
|
||||
- Interactive mode (default): Returns results, user calls /select endpoint
|
||||
- Auto mode (auto_download=True): Automatically selects and downloads best
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# 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"
|
||||
detail=t(locale, "audioSearch.notEnabled")
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -966,12 +969,14 @@ async def search_audio_standalone(
|
||||
Credits are checked here (early feedback) but NOT deducted — deduction
|
||||
happens when the job is created via create-from-search.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# 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"
|
||||
detail=t(locale, "audioSearch.notEnabled")
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -1098,14 +1103,14 @@ async def get_audio_search_results(
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
|
||||
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
|
||||
|
||||
if not search_results:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="No search results available for this job"
|
||||
detail=t("en", "audioSearch.noSearchResults")
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -1136,7 +1141,7 @@ async def select_audio_source(
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
|
||||
|
||||
# Verify job is awaiting selection
|
||||
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
|
||||
|
||||
+41
-35
@@ -9,7 +9,7 @@ Provides endpoints for:
|
||||
import logging
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.services.credential_manager import (
|
||||
@@ -18,6 +18,7 @@ from backend.services.credential_manager import (
|
||||
CredentialCheckResult,
|
||||
)
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
@@ -125,15 +126,16 @@ async def get_credentials_status():
|
||||
|
||||
|
||||
@router.get("/status/{service}", response_model=CredentialStatusResponse)
|
||||
async def get_service_credential_status(service: str):
|
||||
async def get_service_credential_status(service: str, request: Request):
|
||||
"""
|
||||
Get the status of a specific service's OAuth credentials.
|
||||
|
||||
|
||||
Args:
|
||||
service: One of "youtube", "gdrive", "dropbox"
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
manager = get_credential_manager()
|
||||
|
||||
|
||||
if service == "youtube":
|
||||
result = manager.check_youtube_credentials()
|
||||
elif service == "gdrive":
|
||||
@@ -141,7 +143,7 @@ async def get_service_credential_status(service: str):
|
||||
elif service == "dropbox":
|
||||
result = manager.check_dropbox_credentials()
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail=f"Unknown service: {service}")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "auth.unknownService", service=service))
|
||||
|
||||
return CredentialStatusResponse(
|
||||
service=result.service,
|
||||
@@ -153,42 +155,43 @@ async def get_service_credential_status(service: str):
|
||||
|
||||
|
||||
@router.post("/validate", response_model=CredentialValidationResponse)
|
||||
async def validate_credentials(request: CredentialValidationRequest):
|
||||
async def validate_credentials(request: CredentialValidationRequest, http_request: Request):
|
||||
"""
|
||||
Validate that credentials are available for requested services.
|
||||
|
||||
|
||||
Use this before submitting a job to ensure all required
|
||||
credentials are valid.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
manager = get_credential_manager()
|
||||
invalid_services = []
|
||||
|
||||
|
||||
if request.youtube:
|
||||
result = manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append("youtube")
|
||||
|
||||
|
||||
if request.gdrive:
|
||||
result = manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append("gdrive")
|
||||
|
||||
|
||||
if request.dropbox:
|
||||
result = manager.check_dropbox_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append("dropbox")
|
||||
|
||||
|
||||
if invalid_services:
|
||||
return CredentialValidationResponse(
|
||||
valid=False,
|
||||
invalid_services=invalid_services,
|
||||
message=f"The following services need re-authorization: {', '.join(invalid_services)}"
|
||||
message=t(locale, "auth.invalidCredentials", services=", ".join(invalid_services))
|
||||
)
|
||||
|
||||
|
||||
return CredentialValidationResponse(
|
||||
valid=True,
|
||||
invalid_services=[],
|
||||
message="All requested credentials are valid"
|
||||
message=t(locale, "auth.validCredentials")
|
||||
)
|
||||
|
||||
|
||||
@@ -197,40 +200,41 @@ async def validate_credentials(request: CredentialValidationRequest):
|
||||
# ===========================================================================
|
||||
|
||||
@router.post("/youtube/device", response_model=DeviceAuthStartResponse)
|
||||
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None):
|
||||
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
"""
|
||||
Start YouTube device authorization flow.
|
||||
|
||||
|
||||
This initiates a device auth flow that allows authorization
|
||||
from any device. The user must visit the verification URL
|
||||
and enter the user code.
|
||||
|
||||
|
||||
Client credentials are loaded from Secret Manager ('youtube-client-credentials')
|
||||
unless explicitly provided in the request body.
|
||||
|
||||
|
||||
After starting, poll /auth/youtube/device/{device_code} to
|
||||
check for completion.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request) if http_request else "en"
|
||||
manager = get_credential_manager()
|
||||
|
||||
|
||||
try:
|
||||
device_info = manager.start_youtube_device_auth(
|
||||
client_id=request.client_id if request else None,
|
||||
client_secret=request.client_secret if request else None
|
||||
)
|
||||
|
||||
|
||||
return DeviceAuthStartResponse(
|
||||
device_code=device_info.device_code,
|
||||
user_code=device_info.user_code,
|
||||
verification_url=device_info.verification_url,
|
||||
expires_in=device_info.expires_in,
|
||||
interval=device_info.interval,
|
||||
instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}"
|
||||
instructions=t(locale, "auth.youtubeAuthInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code)
|
||||
)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start YouTube device auth: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "auth.youtubeAuthStartFailed", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/youtube/device/{device_code}", response_model=DeviceAuthPollResponse)
|
||||
@@ -259,35 +263,36 @@ async def poll_youtube_device_auth(device_code: str):
|
||||
|
||||
|
||||
@router.post("/gdrive/device", response_model=DeviceAuthStartResponse)
|
||||
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None):
|
||||
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
"""
|
||||
Start Google Drive device authorization flow.
|
||||
|
||||
|
||||
Client credentials are loaded from Secret Manager ('gdrive-client-credentials')
|
||||
unless explicitly provided in the request body.
|
||||
|
||||
|
||||
After starting, poll /auth/gdrive/device/{device_code} to check for completion.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request) if http_request else "en"
|
||||
manager = get_credential_manager()
|
||||
|
||||
|
||||
try:
|
||||
device_info = manager.start_gdrive_device_auth(
|
||||
client_id=request.client_id if request else None,
|
||||
client_secret=request.client_secret if request else None
|
||||
)
|
||||
|
||||
|
||||
return DeviceAuthStartResponse(
|
||||
device_code=device_info.device_code,
|
||||
user_code=device_info.user_code,
|
||||
verification_url=device_info.verification_url,
|
||||
expires_in=device_info.expires_in,
|
||||
interval=device_info.interval,
|
||||
instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}"
|
||||
instructions=t(locale, "auth.gdriveLinkInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code)
|
||||
)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start Google Drive device auth: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "auth.gdriveAuthStartFailed", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/gdrive/device/{device_code}", response_model=DeviceAuthPollResponse)
|
||||
@@ -311,19 +316,20 @@ async def poll_gdrive_device_auth(device_code: str):
|
||||
# ===========================================================================
|
||||
|
||||
@router.post("/test-alert")
|
||||
async def test_credential_alert(background_tasks: BackgroundTasks):
|
||||
async def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
|
||||
"""
|
||||
Test the credential alert mechanism.
|
||||
|
||||
|
||||
Sends a test alert to Discord if configured.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
settings = get_settings()
|
||||
discord_url = settings.get_secret("discord-alert-webhook")
|
||||
|
||||
|
||||
if not discord_url:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Discord alert webhook not configured"
|
||||
detail=t(locale, "auth.discordAlertNotConfigured")
|
||||
)
|
||||
|
||||
manager = get_credential_manager()
|
||||
|
||||
@@ -14,6 +14,7 @@ from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -26,7 +27,7 @@ RATE_LIMIT_MAX_REQUESTS = 20
|
||||
RATE_LIMIT_WINDOW_SECONDS = 60
|
||||
|
||||
|
||||
def _check_rate_limit(user_email: str) -> None:
|
||||
def _check_rate_limit(user_email: str, locale: str = "en") -> None:
|
||||
"""Check per-user rate limit. Raises 429 if exceeded."""
|
||||
now = time.monotonic()
|
||||
window_start = now - RATE_LIMIT_WINDOW_SECONDS
|
||||
@@ -37,12 +38,12 @@ def _check_rate_limit(user_email: str) -> None:
|
||||
|
||||
# Remove expired entries
|
||||
timestamps = _rate_limit_windows[user_email]
|
||||
_rate_limit_windows[user_email] = [t for t in timestamps if t > window_start]
|
||||
_rate_limit_windows[user_email] = [ts for ts in timestamps if ts > window_start]
|
||||
|
||||
if len(_rate_limit_windows[user_email]) >= RATE_LIMIT_MAX_REQUESTS:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=f"Rate limit exceeded. Maximum {RATE_LIMIT_MAX_REQUESTS} catalog requests per minute.",
|
||||
detail=t(locale, "catalog.rateLimitExceeded", max_requests=RATE_LIMIT_MAX_REQUESTS),
|
||||
)
|
||||
|
||||
_rate_limit_windows[user_email].append(now)
|
||||
@@ -107,6 +108,7 @@ class CommunityCheckResponse(BaseModel):
|
||||
|
||||
@router.get("/artists", response_model=list[ArtistResult])
|
||||
async def search_artists(
|
||||
request: Request,
|
||||
q: str = Query(..., min_length=2, description="Artist name search query"),
|
||||
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
@@ -115,7 +117,8 @@ async def search_artists(
|
||||
Search for artists by name. Returns canonical MusicBrainz/Spotify artist data
|
||||
for autocomplete in job creation forms.
|
||||
"""
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.catalog_proxy_service import search_artists
|
||||
results = await search_artists(q, limit)
|
||||
@@ -124,6 +127,7 @@ async def search_artists(
|
||||
|
||||
@router.get("/tracks", response_model=list[TrackResult])
|
||||
async def search_tracks(
|
||||
request: Request,
|
||||
q: str = Query(..., min_length=2, description="Track name search query"),
|
||||
artist: Optional[str] = Query(None, description="Filter by artist name"),
|
||||
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
|
||||
@@ -133,7 +137,8 @@ async def search_tracks(
|
||||
Search for tracks by name, optionally filtered by artist.
|
||||
Returns canonical Spotify track data for autocomplete in job creation forms.
|
||||
"""
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.catalog_proxy_service import search_tracks
|
||||
results = await search_tracks(q, artist, limit)
|
||||
@@ -142,6 +147,7 @@ async def search_tracks(
|
||||
|
||||
@router.post("/community-check", response_model=CommunityCheckResponse)
|
||||
async def check_community_versions(
|
||||
request: Request,
|
||||
body: CommunityCheckRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
@@ -149,7 +155,8 @@ async def check_community_versions(
|
||||
Check if a song already has community-approved karaoke versions on YouTube
|
||||
via karaokenerds.com. Non-blocking — just informs the user.
|
||||
"""
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.karaokenerds_service import check_community_versions
|
||||
result = await check_community_versions(body.artist, body.title)
|
||||
|
||||
@@ -45,6 +45,7 @@ from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -350,7 +351,8 @@ async def _trigger_audio_worker_only(job_id: str) -> None:
|
||||
def _prepare_theme_for_job(
|
||||
job_id: str,
|
||||
theme_id: str,
|
||||
color_overrides: Optional[Dict[str, str]] = None
|
||||
color_overrides: Optional[Dict[str, str]] = None,
|
||||
locale: str = "en"
|
||||
) -> Tuple[str, Dict[str, str], Optional[str]]:
|
||||
"""
|
||||
Prepare theme style files for a job.
|
||||
@@ -359,6 +361,7 @@ def _prepare_theme_for_job(
|
||||
job_id: The job ID
|
||||
theme_id: Theme identifier
|
||||
color_overrides: Optional color override dict
|
||||
locale: Locale for error messages
|
||||
|
||||
Returns:
|
||||
Tuple of (style_params_gcs_path, style_assets, youtube_description)
|
||||
@@ -372,7 +375,7 @@ def _prepare_theme_for_job(
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Theme not found: {theme_id}. Use GET /api/themes to list available themes."
|
||||
detail=t(locale, "fileUpload.invalidTheme", theme_id=theme_id)
|
||||
)
|
||||
|
||||
# Convert dict to ColorOverrides model if provided
|
||||
@@ -465,6 +468,8 @@ async def upload_and_create_job(
|
||||
The style_params JSON can reference the uploaded images/fonts by their original
|
||||
filenames, and the backend will update the paths to GCS locations.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.file_upload:
|
||||
@@ -699,7 +704,7 @@ async def upload_and_create_job(
|
||||
if effective_theme_id and not has_custom_style_files:
|
||||
try:
|
||||
theme_style_params_path, theme_style_assets, theme_youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, parsed_color_overrides or None
|
||||
job_id, effective_theme_id, parsed_color_overrides or None, locale=locale
|
||||
)
|
||||
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
|
||||
except HTTPException:
|
||||
@@ -896,7 +901,7 @@ async def upload_and_create_job(
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"message": "Files uploaded successfully. Processing started.",
|
||||
"message": t(locale, "fileUpload.uploadSuccess"),
|
||||
"filename": file.filename,
|
||||
"style_assets_uploaded": list(style_assets.keys()) if style_assets else [],
|
||||
"server_version": VERSION,
|
||||
@@ -909,7 +914,7 @@ async def upload_and_create_job(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error uploading files: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadError", error=str(e))) from e
|
||||
|
||||
|
||||
# ============================================================================
|
||||
@@ -1110,6 +1115,8 @@ async def create_job_with_upload_urls(
|
||||
- Works with any HTTP client (no HTTP/2 required)
|
||||
- Resumable uploads possible with GCS
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.file_upload:
|
||||
@@ -1121,14 +1128,14 @@ async def create_job_with_upload_urls(
|
||||
try:
|
||||
# Validate files list
|
||||
if not body.files:
|
||||
raise HTTPException(status_code=400, detail="At least one file is required")
|
||||
|
||||
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
|
||||
|
||||
# Check that audio file is included
|
||||
audio_files = [f for f in body.files if f.file_type == 'audio']
|
||||
if not audio_files:
|
||||
raise HTTPException(status_code=400, detail="An audio file is required")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
|
||||
if len(audio_files) > 1:
|
||||
raise HTTPException(status_code=400, detail="Only one audio file is allowed")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.multipleAudioFilesNotAllowed"))
|
||||
|
||||
# Validate file types and extensions
|
||||
for file_info in body.files:
|
||||
@@ -1271,7 +1278,7 @@ async def create_job_with_upload_urls(
|
||||
# If theme is set and no style_params uploaded, prepare theme style now
|
||||
if effective_theme_id and not has_style_params_upload:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, body.color_overrides
|
||||
job_id, effective_theme_id, body.color_overrides, locale=locale
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
@@ -1307,7 +1314,7 @@ async def create_job_with_upload_urls(
|
||||
return CreateJobWithUploadUrlsResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Job created. Upload files to the provided URLs, then call /api/jobs/{job_id}/uploads-complete",
|
||||
message=t(locale, "fileUpload.urlCreationSuccess"),
|
||||
upload_urls=upload_urls,
|
||||
server_version=VERSION
|
||||
)
|
||||
@@ -1318,12 +1325,13 @@ async def create_job_with_upload_urls(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job with upload URLs: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.urlCreationError", error=str(e))) from e
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/uploads-complete")
|
||||
async def mark_uploads_complete(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: UploadsCompleteRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
@@ -1342,22 +1350,23 @@ async def mark_uploads_complete(
|
||||
- Update job with GCS paths
|
||||
- Trigger audio and lyrics workers
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
# Get job and verify it exists
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Verify job is in pending state
|
||||
if job.status != JobStatus.PENDING:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job {job_id} is not in pending state (current: {job.status}). Cannot complete uploads."
|
||||
detail=t(locale, "jobs.notCompleted", status=job.status)
|
||||
)
|
||||
|
||||
|
||||
# Validate required files
|
||||
if 'audio' not in body.uploaded_files:
|
||||
raise HTTPException(status_code=400, detail="Audio file upload is required")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
|
||||
|
||||
# Build GCS paths for uploaded files and validate they exist
|
||||
update_data = {}
|
||||
@@ -1495,7 +1504,7 @@ async def mark_uploads_complete(
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"message": "Uploads validated. Processing started.",
|
||||
"message": t(locale, "fileUpload.uploadsCompleteSuccess"),
|
||||
"files_validated": body.uploaded_files,
|
||||
"style_assets": list(style_assets.keys()) if style_assets else [],
|
||||
"server_version": VERSION,
|
||||
@@ -1506,7 +1515,7 @@ async def mark_uploads_complete(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error completing uploads for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadsCompleteError", error=str(e))) from e
|
||||
|
||||
|
||||
# ============================================================================
|
||||
@@ -1589,6 +1598,8 @@ async def create_job_from_url(
|
||||
Note: YouTube rate limiting may cause occasional download failures.
|
||||
The backend will retry automatically.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.youtube_url:
|
||||
@@ -1744,7 +1755,7 @@ async def create_job_from_url(
|
||||
# If theme is set, prepare theme style now
|
||||
if effective_theme_id:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, body.color_overrides
|
||||
job_id, effective_theme_id, body.color_overrides, locale=locale
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
@@ -1803,7 +1814,7 @@ async def create_job_from_url(
|
||||
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"YouTube download failed: {e}"
|
||||
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
|
||||
)
|
||||
else:
|
||||
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
|
||||
@@ -1897,6 +1908,8 @@ async def create_finalise_only_job(
|
||||
|
||||
The endpoint returns signed URLs for uploading all the prep files.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag - finalise-only requires file upload capability
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.file_upload:
|
||||
@@ -2057,7 +2070,7 @@ async def create_finalise_only_job(
|
||||
# If theme is set and no style_params uploaded, prepare theme style now
|
||||
if effective_theme_id and not has_style_params_upload:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, body.color_overrides
|
||||
job_id, effective_theme_id, body.color_overrides, locale=locale
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
|
||||
@@ -5,10 +5,12 @@ import os
|
||||
import logging
|
||||
import subprocess
|
||||
import platform
|
||||
from fastapi import APIRouter
|
||||
from typing import Dict, Any, Optional
|
||||
from fastapi import APIRouter, Depends
|
||||
from typing import Dict, Any, Optional, Tuple
|
||||
|
||||
from backend.version import VERSION
|
||||
from backend.version import VERSION, COMMIT_SHA, PR_NUMBER, PR_TITLE, STARTUP_TIME
|
||||
from backend.api.dependencies import optional_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.services.flacfetch_client import get_flacfetch_client
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.stripe_service import get_stripe_service
|
||||
@@ -308,6 +310,30 @@ async def flacfetch_health() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def check_audio_separator_status() -> Dict[str, Any]:
|
||||
"""Check audio separator availability without calling the remote GPU service."""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
except Exception:
|
||||
pkg_version = None
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": pkg_version,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -341,6 +367,118 @@ async def audio_separator_health() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _get_encoding_worker_manager():
|
||||
"""Get the EncodingWorkerManager instance. Separated for testability."""
|
||||
try:
|
||||
encoding_service = get_encoding_service()
|
||||
if hasattr(encoding_service, '_worker_manager') and encoding_service._worker_manager:
|
||||
return encoding_service._worker_manager
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/health/system-status")
|
||||
async def system_status(
|
||||
auth: Optional[Tuple] = Depends(optional_auth),
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Aggregated system status for all services.
|
||||
|
||||
Returns basic info for everyone. Admin users get additional
|
||||
blue-green deployment details for the encoder.
|
||||
"""
|
||||
is_admin = auth is not None and len(auth) >= 2 and auth[1] == UserType.ADMIN
|
||||
|
||||
# Fetch all health statuses concurrently
|
||||
import asyncio
|
||||
encoding_task = check_encoding_worker_status()
|
||||
flacfetch_task = check_flacfetch_service_status()
|
||||
encoding_status, flacfetch_status = await asyncio.gather(
|
||||
encoding_task, flacfetch_task
|
||||
)
|
||||
separator_status = check_audio_separator_status()
|
||||
|
||||
# Build frontend service info (from env vars baked at build time — returned as-is)
|
||||
frontend_svc = {
|
||||
"status": "ok",
|
||||
"version": VERSION, # Frontend and backend share the same version from pyproject.toml
|
||||
}
|
||||
|
||||
# Build backend service info
|
||||
backend_svc = {
|
||||
"status": "ok",
|
||||
"version": VERSION,
|
||||
"deployed_at": STARTUP_TIME,
|
||||
}
|
||||
if COMMIT_SHA:
|
||||
backend_svc["commit_sha"] = COMMIT_SHA
|
||||
if PR_NUMBER:
|
||||
backend_svc["pr_number"] = PR_NUMBER
|
||||
if PR_TITLE:
|
||||
backend_svc["pr_title"] = PR_TITLE
|
||||
|
||||
# Build encoder service info
|
||||
encoder_svc = {
|
||||
"status": "ok" if encoding_status.get("available") else "offline",
|
||||
"version": encoding_status.get("wheel_version"),
|
||||
"active_jobs": encoding_status.get("active_jobs", 0),
|
||||
}
|
||||
|
||||
# Build flacfetch service info
|
||||
flacfetch_svc = {
|
||||
"status": "ok" if flacfetch_status.get("available") else "offline",
|
||||
"version": flacfetch_status.get("version"),
|
||||
}
|
||||
|
||||
# Build separator service info
|
||||
separator_svc = {
|
||||
"status": "ok" if separator_status.get("available") else "offline",
|
||||
"version": separator_status.get("version"),
|
||||
}
|
||||
|
||||
# Admin-only: blue-green encoder details from Firestore
|
||||
if is_admin:
|
||||
manager = _get_encoding_worker_manager()
|
||||
if manager:
|
||||
try:
|
||||
config = manager.get_config()
|
||||
encoder_svc["admin_details"] = {
|
||||
"primary_vm": config.primary_vm,
|
||||
"primary_ip": config.primary_ip,
|
||||
"primary_version": config.primary_version,
|
||||
"primary_deployed_at": config.primary_deployed_at,
|
||||
"secondary_vm": config.secondary_vm,
|
||||
"secondary_ip": config.secondary_ip,
|
||||
"secondary_version": config.secondary_version,
|
||||
"secondary_deployed_at": config.secondary_deployed_at,
|
||||
"last_swap_at": config.last_swap_at,
|
||||
"deploy_in_progress": config.deploy_in_progress,
|
||||
"active_jobs": encoding_status.get("active_jobs", 0),
|
||||
"queue_length": encoding_status.get("queue_length", 0),
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to get blue-green config: {e}")
|
||||
|
||||
# Add error details for offline services
|
||||
if not flacfetch_status.get("available"):
|
||||
flacfetch_svc["admin_details"] = {"error": flacfetch_status.get("error")}
|
||||
if not separator_status.get("available"):
|
||||
separator_svc["admin_details"] = {"error": separator_status.get("error")}
|
||||
if not encoding_status.get("available") and "admin_details" not in encoder_svc:
|
||||
encoder_svc["admin_details"] = {"error": encoding_status.get("error")}
|
||||
|
||||
return {
|
||||
"services": {
|
||||
"frontend": frontend_svc,
|
||||
"backend": backend_svc,
|
||||
"encoder": encoder_svc,
|
||||
"flacfetch": flacfetch_svc,
|
||||
"separator": separator_svc,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/detailed")
|
||||
async def detailed_health_check() -> Dict[str, Any]:
|
||||
"""
|
||||
|
||||
+121
-84
@@ -38,6 +38,7 @@ from backend.services.tracing import add_span_attribute
|
||||
from backend.api.dependencies import require_admin, require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.metrics import metrics
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.middleware.tenant import get_tenant_from_request
|
||||
from backend.utils.test_data import is_test_email
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
@@ -84,6 +85,7 @@ async def create_job(
|
||||
3. Both workers update job state as they progress
|
||||
4. When both complete, job transitions to AWAITING_REVIEW
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
try:
|
||||
# Determine job owner email:
|
||||
# All authentication methods must provide a user_email for job ownership
|
||||
@@ -95,7 +97,7 @@ async def create_job(
|
||||
logger.error("Authentication succeeded but no user_email provided")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Authentication error: no user identity available"
|
||||
detail=t(locale, "jobs.authError")
|
||||
)
|
||||
|
||||
# Admins can optionally create jobs on behalf of other users
|
||||
@@ -114,7 +116,7 @@ async def create_job(
|
||||
if not effective_theme_id:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="No default theme configured. Please contact support or specify a theme_id."
|
||||
detail=t(locale, "jobs.noDefaultTheme")
|
||||
)
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
@@ -156,7 +158,7 @@ async def create_job(
|
||||
return JobResponse(
|
||||
status="success",
|
||||
job_id=job.job_id,
|
||||
message="Job created successfully. Processing started."
|
||||
message=t(locale, "jobs.created")
|
||||
)
|
||||
except InsufficientCreditsError:
|
||||
raise
|
||||
@@ -172,16 +174,18 @@ async def create_job(
|
||||
@router.get("/{job_id}", response_model=Job)
|
||||
async def get_job(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> Job:
|
||||
"""Get job status and details."""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership - users can only see their own jobs, admins can see all
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
# If job is complete, include download URLs
|
||||
if job.status == JobStatus.COMPLETE:
|
||||
@@ -236,6 +240,7 @@ class EditTrackResponse(BaseModel):
|
||||
async def edit_completed_track(
|
||||
job_id: str,
|
||||
request: EditTrackRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
@@ -249,30 +254,31 @@ async def edit_completed_track(
|
||||
|
||||
No additional credits are consumed — the original credit covers re-edits.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
import re
|
||||
from datetime import timezone
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to edit this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionEdit"))
|
||||
|
||||
# Only completed jobs can be edited
|
||||
if job.status != JobStatus.COMPLETE.value and job.status != "complete":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Only completed jobs can be edited. Current status: {job.status}"
|
||||
detail=t(locale, "jobs.notCompleted", status=job.status)
|
||||
)
|
||||
|
||||
# Prevent editing if outputs already deleted (edit already in progress)
|
||||
if job.outputs_deleted_at:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="This job is already being edited (outputs were already deleted)"
|
||||
detail=t(locale, "jobs.alreadyBeingEdited")
|
||||
)
|
||||
|
||||
user_email = auth_result.user_email or "unknown"
|
||||
@@ -397,8 +403,7 @@ async def edit_completed_track(
|
||||
if critical_failures:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Cleanup failed for {', '.join(critical_failures)}. "
|
||||
f"Job not modified. Please try again or contact support."
|
||||
detail=t(locale, "jobs.cleanupFailed", services=", ".join(critical_failures))
|
||||
)
|
||||
|
||||
# --- Phase 2: Update job record ---
|
||||
@@ -504,7 +509,7 @@ async def edit_completed_track(
|
||||
return EditTrackResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Track reopened for editing. Previous outputs have been removed.",
|
||||
message=t(locale, "jobs.reopened"),
|
||||
review_url=f"/app/jobs#/{job_id}/review",
|
||||
review_token=review_token,
|
||||
metadata_updated=metadata_updated,
|
||||
@@ -598,17 +603,19 @@ async def list_jobs(
|
||||
created_after_dt = None
|
||||
created_before_dt = None
|
||||
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
if created_after:
|
||||
try:
|
||||
created_after_dt = datetime.fromisoformat(created_after.replace('Z', '+00:00'))
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid created_after format: {created_after}") from e
|
||||
raise HTTPException(status_code=400, detail=t(locale, "jobs.invalidDatetimeFormat", field="created_after", value=created_after)) from e
|
||||
|
||||
if created_before:
|
||||
try:
|
||||
created_before_dt = datetime.fromisoformat(created_before.replace('Z', '+00:00'))
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid created_before format: {created_before}") from e
|
||||
raise HTTPException(status_code=400, detail=t(locale, "jobs.invalidDatetimeFormat", field="created_before", value=created_before)) from e
|
||||
|
||||
# Determine user_email filter based on admin status
|
||||
# Admins see all jobs, regular users only see their own
|
||||
@@ -683,24 +690,26 @@ async def list_jobs(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing jobs: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "jobs.listError", error=str(e)))
|
||||
|
||||
|
||||
@router.delete("/{job_id}")
|
||||
async def delete_job(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
delete_files: bool = True,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""Delete a job and optionally its output files."""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership - users can only delete their own jobs
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to delete this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionDelete"))
|
||||
|
||||
# Recycle any unreturned brand code before deleting the job record
|
||||
state_data = job.state_data or {}
|
||||
@@ -727,11 +736,12 @@ async def delete_job(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "jobs.deleteError", job_id=job_id, error=str(e)))
|
||||
|
||||
|
||||
@router.delete("")
|
||||
async def bulk_delete_jobs(
|
||||
request: Request,
|
||||
environment: Optional[str] = None,
|
||||
client_id: Optional[str] = None,
|
||||
status: Optional[JobStatus] = None,
|
||||
@@ -763,13 +773,15 @@ async def bulk_delete_jobs(
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Require at least one filter to prevent accidental deletion of all jobs
|
||||
if not any([environment, client_id, status, created_before]):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="At least one filter (environment, client_id, status, created_before) is required"
|
||||
detail=t(locale, "jobs.deletionRequiresFilters")
|
||||
)
|
||||
|
||||
|
||||
# Require explicit confirmation
|
||||
if not confirm:
|
||||
# Return preview of what would be deleted
|
||||
@@ -790,7 +802,7 @@ async def bulk_delete_jobs(
|
||||
|
||||
return {
|
||||
"status": "preview",
|
||||
"message": "Add &confirm=true to execute deletion",
|
||||
"message": t(locale, "jobs.deletionPreview"),
|
||||
"jobs_to_delete": len(jobs),
|
||||
"sample_jobs": [
|
||||
{
|
||||
@@ -832,7 +844,7 @@ async def bulk_delete_jobs(
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error bulk deleting jobs: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "jobs.bulkDeleteError", error=str(e)))
|
||||
|
||||
|
||||
# ============================================================================
|
||||
@@ -842,6 +854,7 @@ async def bulk_delete_jobs(
|
||||
@router.get("/{job_id}/review-data")
|
||||
async def get_review_data(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -850,18 +863,19 @@ async def get_review_data(
|
||||
Returns corrections JSON URL and audio URL.
|
||||
Frontend loads these to render the review UI.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not ready for review (current status: {job.status})"
|
||||
detail=t(locale, "jobs.reviewNotReady", status=job.status)
|
||||
)
|
||||
|
||||
# Get URLs from file_urls
|
||||
@@ -880,13 +894,13 @@ async def get_review_data(
|
||||
if not corrections_url:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Corrections data not available"
|
||||
detail=t(locale, "jobs.correctionsUnavailable")
|
||||
)
|
||||
|
||||
if not audio_url:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Audio not available for review"
|
||||
detail=t(locale, "jobs.audioUnavailable")
|
||||
)
|
||||
|
||||
# Generate signed URLs for direct access
|
||||
@@ -906,6 +920,7 @@ async def get_review_data(
|
||||
async def start_review(
|
||||
job_id: str,
|
||||
request: StartReviewRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
@@ -913,22 +928,23 @@ async def start_review(
|
||||
|
||||
This helps track that the user is actively working on the review.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
success = job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.IN_REVIEW,
|
||||
message="User started reviewing lyrics"
|
||||
)
|
||||
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail="Cannot start review")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "jobs.reviewCannotStart"))
|
||||
|
||||
return {"status": "success", "job_status": "in_review"}
|
||||
|
||||
@@ -937,6 +953,7 @@ async def start_review(
|
||||
async def submit_corrections(
|
||||
job_id: str,
|
||||
submission: CorrectionsSubmission,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
@@ -948,18 +965,19 @@ async def submit_corrections(
|
||||
|
||||
Can be called multiple times to save progress.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
detail=t(locale, "jobs.jobNotInReviewState", status=job.status)
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -995,7 +1013,7 @@ async def submit_corrections(
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "in_review",
|
||||
"message": "Corrections saved. Call /complete-review when done."
|
||||
"message": t(locale, "jobs.correctionsProcessing")
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -1007,6 +1025,7 @@ async def submit_corrections(
|
||||
async def submit_edit_log(
|
||||
job_id: str,
|
||||
edit_log: Dict[str, Any],
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
@@ -1017,12 +1036,13 @@ async def submit_edit_log(
|
||||
|
||||
Stored to GCS as jobs/{job_id}/lyrics/edit_log_{session_id}.json.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
session_id = edit_log.get("session_id", "unknown")
|
||||
entries = edit_log.get("entries", [])
|
||||
@@ -1049,13 +1069,14 @@ async def submit_edit_log(
|
||||
|
||||
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))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "jobs.editLogSaveFailed", job_id=job_id, error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/create-custom-instrumental")
|
||||
async def create_custom_instrumental(
|
||||
job_id: str,
|
||||
request: CreateCustomInstrumentalRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
@@ -1064,17 +1085,18 @@ async def create_custom_instrumental(
|
||||
Downloads the clean instrumental and backing vocals stems, applies mute
|
||||
regions, combines them, uploads to GCS, and returns a signed URL for playback.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
detail=t(locale, "jobs.jobNotInReviewState", status=job.status)
|
||||
)
|
||||
|
||||
# Get stem paths from job
|
||||
@@ -1085,7 +1107,7 @@ async def create_custom_instrumental(
|
||||
if not clean_path or not backing_path:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Job missing required stems (instrumental_clean and/or backing_vocals)"
|
||||
detail=t(locale, "jobs.stemsMissing")
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -1133,12 +1155,13 @@ async def create_custom_instrumental(
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating custom instrumental for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "jobs.customInstrumentalFailed", job_id=job_id, error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/upload-instrumental")
|
||||
async def upload_custom_instrumental(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
file: UploadFile = File(...),
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
@@ -1149,17 +1172,18 @@ async def upload_custom_instrumental(
|
||||
The file is stored to GCS and its path recorded in the job's stems metadata.
|
||||
The user can then select 'custom' as their instrumental_selection when completing review.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
detail=t(locale, "jobs.reviewNotInState", status=job.status)
|
||||
)
|
||||
|
||||
# Determine extension from filename or content type
|
||||
@@ -1202,11 +1226,9 @@ async def upload_custom_instrumental(
|
||||
if diff > 0.5:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
f"Duration mismatch: uploaded file is {upload_duration:.1f}s "
|
||||
f"but original audio is {original_duration:.1f}s. "
|
||||
f"The instrumental must be exactly {original_duration:.1f}s (±0.5s)."
|
||||
),
|
||||
detail=t(locale, "jobs.durationMismatch",
|
||||
upload_duration=f"{upload_duration:.1f}",
|
||||
original_duration=f"{original_duration:.1f}"),
|
||||
)
|
||||
|
||||
# Convert to FLAC for consistency with the rest of the pipeline
|
||||
@@ -1225,7 +1247,7 @@ async def upload_custom_instrumental(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error processing uploaded instrumental: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Failed to process audio file: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=t(locale, "jobs.audioProcessingFailed", error=str(e)))
|
||||
finally:
|
||||
if tmp_path and os.path.exists(tmp_path):
|
||||
os.unlink(tmp_path)
|
||||
@@ -1278,6 +1300,7 @@ async def _get_audio_duration_ffprobe_signed(job_id: str, job, storage: StorageS
|
||||
@router.post("/{job_id}/complete-review")
|
||||
async def complete_review(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
body: Optional[CompleteReviewRequest] = None
|
||||
@@ -1294,18 +1317,19 @@ async def complete_review(
|
||||
3. Worker uses OutputGenerator to create with_vocals.mkv
|
||||
4. Job transitions to INSTRUMENTAL_SELECTED then GENERATING_VIDEO
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
detail=t(locale, "jobs.reviewNotInState", status=job.status)
|
||||
)
|
||||
|
||||
# Check for 0-segment lyrics — fail early with user-friendly message
|
||||
@@ -1320,12 +1344,7 @@ async def complete_review(
|
||||
if segment_count == 0 and len(corrected_segments) == 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Cannot complete review: no lyrics were detected in the audio. "
|
||||
"This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). "
|
||||
"You can go back and paste lyrics manually using 'Replace All', "
|
||||
"or cancel this job and try again with an audio file that contains vocals."
|
||||
)
|
||||
detail=t(locale, "jobs.noLyricsDetected")
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -1352,18 +1371,19 @@ async def complete_review(
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "review_complete",
|
||||
"message": "Review complete. Video rendering started."
|
||||
"message": t(locale, "jobs.reviewCompleteStartRendering")
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error completing review for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "jobs.reviewCompleteError", job_id=job_id, error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/select-instrumental")
|
||||
async def select_instrumental(
|
||||
job_id: str,
|
||||
selection: InstrumentalSelection,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
@@ -1383,18 +1403,19 @@ async def select_instrumental(
|
||||
Returns:
|
||||
Status and confirmation of selection
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
if job.status != JobStatus.AWAITING_INSTRUMENTAL_SELECTION:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not awaiting instrumental selection (current status: {job.status})"
|
||||
detail=t(locale, "jobs.reviewNotInState", status=job.status)
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -1420,17 +1441,18 @@ async def select_instrumental(
|
||||
"status": "success",
|
||||
"job_status": "instrumental_selected",
|
||||
"selection": selection.selection,
|
||||
"message": "Instrumental selected. Video generation started."
|
||||
"message": t(locale, "jobs.instrumentalSelected")
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error selecting instrumental for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "jobs.instrumentalSelectionError", job_id=job_id, error=str(e)))
|
||||
|
||||
|
||||
@router.get("/{job_id}/download-urls")
|
||||
async def get_download_urls(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
@@ -1439,13 +1461,14 @@ async def get_download_urls(
|
||||
Returns a dictionary mapping file types to download URLs.
|
||||
Uses the streaming download endpoint which proxies through the backend.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
file_urls = job.file_urls or {}
|
||||
download_urls = {}
|
||||
@@ -1489,6 +1512,7 @@ async def download_file(
|
||||
job_id: str,
|
||||
category: str,
|
||||
file_key: str,
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
@@ -1497,16 +1521,17 @@ async def download_file(
|
||||
This endpoint proxies the file from GCS through the backend,
|
||||
so no client-side authentication is required.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
from fastapi.responses import StreamingResponse
|
||||
import tempfile
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
file_urls = job.file_urls or {}
|
||||
category_files = file_urls.get(category)
|
||||
@@ -1599,6 +1624,7 @@ async def download_file(
|
||||
async def cancel_job(
|
||||
job_id: str,
|
||||
request: CancelJobRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
@@ -1606,13 +1632,14 @@ async def cancel_job(
|
||||
|
||||
Jobs can be cancelled at any stage before completion.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to cancel this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
success = job_manager.cancel_job(job_id, reason=request.reason)
|
||||
|
||||
@@ -1629,6 +1656,7 @@ async def cancel_job(
|
||||
@router.post("/{job_id}/retry")
|
||||
async def retry_job(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
@@ -1644,20 +1672,21 @@ async def retry_job(
|
||||
The retry logic determines the appropriate stage to resume from
|
||||
based on what files/state already exist.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to retry this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
if job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Only failed or cancelled jobs can be retried (current status: {job.status})"
|
||||
detail=t(locale, "jobs.notCompleted", status=job.status)
|
||||
)
|
||||
|
||||
|
||||
try:
|
||||
# Determine retry point based on what's already complete
|
||||
error_details = job.error_details or {}
|
||||
@@ -1906,6 +1935,7 @@ async def retry_job(
|
||||
@router.get("/{job_id}/logs")
|
||||
async def get_worker_logs(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
since_index: int = 0,
|
||||
worker: Optional[str] = None,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
@@ -1932,13 +1962,14 @@ async def get_worker_logs(
|
||||
"total_logs": 42
|
||||
}
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Check ownership - users can only see logs for their own jobs
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to access logs for this job")
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
logs = job_manager.get_worker_logs(job_id, since_index=since_index, worker=worker)
|
||||
total = job_manager.get_worker_logs_count(job_id)
|
||||
@@ -1953,6 +1984,7 @@ async def get_worker_logs(
|
||||
@router.post("/{job_id}/cleanup-distribution")
|
||||
async def cleanup_distribution(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
delete_job: bool = True,
|
||||
auth_result: AuthResult = Depends(require_admin)
|
||||
) -> dict:
|
||||
@@ -1972,9 +2004,10 @@ async def cleanup_distribution(
|
||||
Returns:
|
||||
Cleanup results for each service
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
state_data = job.state_data or {}
|
||||
results = {
|
||||
@@ -2191,6 +2224,8 @@ async def create_job_from_search(
|
||||
|
||||
Credit deduction happens here (inside job_manager.create_job).
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Lazy imports from audio_search to avoid circular imports at module level
|
||||
from backend.api.routes.audio_search import (
|
||||
_validate_and_prepare_selection,
|
||||
@@ -2201,7 +2236,7 @@ async def create_job_from_search(
|
||||
try:
|
||||
user_email = auth_result.user_email
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "jobs.authError"))
|
||||
|
||||
# Read the session non-destructively for validation.
|
||||
# consume_search_session (atomic read+delete) is called later, just before job creation,
|
||||
@@ -2328,7 +2363,7 @@ async def create_job_from_search(
|
||||
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, {}
|
||||
job_id, effective_theme_id, {}, locale=locale
|
||||
)
|
||||
theme_update = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
@@ -2389,6 +2424,7 @@ async def create_job_from_search(
|
||||
async def change_visibility(
|
||||
job_id: str,
|
||||
request: ChangeVisibilityRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
@@ -2402,10 +2438,11 @@ async def change_visibility(
|
||||
- Resets custom styling to default Nomad theme
|
||||
- Regenerates screens, re-renders video, publishes publicly
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
user_email = auth_result.user_email or "unknown"
|
||||
is_admin = auth_result.is_admin
|
||||
|
||||
+24
-12
@@ -18,6 +18,7 @@ from backend.config import get_settings
|
||||
from backend.api.dependencies import require_auth, require_admin
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.push_notification_service import get_push_notification_service
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -127,18 +128,20 @@ async def subscribe_push(
|
||||
1. Request body tenant_id field (explicit from frontend)
|
||||
2. Tenant middleware (X-Tenant-ID header or subdomain detection)
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.enable_push_notifications:
|
||||
raise HTTPException(status_code=503, detail="Push notifications are not enabled")
|
||||
raise HTTPException(status_code=503, detail=t(locale, "push.disabled"))
|
||||
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
|
||||
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
# Validate keys
|
||||
if "p256dh" not in subscribe_request.keys or "auth" not in subscribe_request.keys:
|
||||
raise HTTPException(status_code=400, detail="Missing required keys (p256dh, auth)")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "push.missingEncryptionKeys"))
|
||||
|
||||
# Resolve tenant_id: prefer explicit from body, fall back to middleware
|
||||
tenant_id = subscribe_request.tenant_id
|
||||
@@ -154,17 +157,18 @@ async def subscribe_push(
|
||||
)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=500, detail="Failed to save subscription")
|
||||
raise HTTPException(status_code=500, detail=t(locale, "push.subscriptionSaveFailed"))
|
||||
|
||||
return SubscribeResponse(
|
||||
status="success",
|
||||
message="Push subscription registered successfully"
|
||||
message=t(locale, "push.subscriptionRegistered")
|
||||
)
|
||||
|
||||
|
||||
@router.post("/unsubscribe", response_model=UnsubscribeResponse)
|
||||
async def unsubscribe_push(
|
||||
request: UnsubscribeRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
@@ -172,8 +176,10 @@ async def unsubscribe_push(
|
||||
|
||||
Requires authentication. Users can only remove their own subscriptions.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
|
||||
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
@@ -186,17 +192,18 @@ async def unsubscribe_push(
|
||||
# Don't error if subscription wasn't found - might already be removed
|
||||
return UnsubscribeResponse(
|
||||
status="success",
|
||||
message="Subscription removed (or was not found)"
|
||||
message=t(locale, "push.subscriptionNotFound")
|
||||
)
|
||||
|
||||
return UnsubscribeResponse(
|
||||
status="success",
|
||||
message="Push subscription removed successfully"
|
||||
message=t(locale, "push.subscriptionRemoved")
|
||||
)
|
||||
|
||||
|
||||
@router.get("/subscriptions", response_model=SubscriptionsListResponse)
|
||||
async def list_subscriptions(
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
@@ -204,8 +211,10 @@ async def list_subscriptions(
|
||||
|
||||
Requires authentication.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
|
||||
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
@@ -220,6 +229,7 @@ async def list_subscriptions(
|
||||
@router.post("/test", response_model=TestNotificationResponse)
|
||||
async def send_test_notification(
|
||||
request: TestNotificationRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
@@ -227,12 +237,14 @@ async def send_test_notification(
|
||||
|
||||
Admin only. Useful for testing push notification setup.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.enable_push_notifications:
|
||||
raise HTTPException(status_code=503, detail="Push notifications are not enabled")
|
||||
raise HTTPException(status_code=503, detail=t(locale, "push.disabled"))
|
||||
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
|
||||
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
@@ -247,5 +259,5 @@ async def send_test_notification(
|
||||
return TestNotificationResponse(
|
||||
status="success",
|
||||
sent_count=sent_count,
|
||||
message=f"Test notification sent to {sent_count} device(s)"
|
||||
message=t(locale, "push.testNotificationSent", sent_count=sent_count)
|
||||
)
|
||||
@@ -10,12 +10,13 @@ import logging
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.email_validation_service import get_email_validation_service, EmailValidationService
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/admin/rate-limits", tags=["admin", "rate-limits"])
|
||||
@@ -106,13 +107,13 @@ async def add_disposable_domain(
|
||||
|
||||
domain = request.domain.lower().strip()
|
||||
if not domain or "." not in domain:
|
||||
raise HTTPException(status_code=400, detail="Invalid domain format")
|
||||
raise HTTPException(status_code=400, detail=t("en", "admin.invalidDomainFormat"))
|
||||
|
||||
email_validation.add_disposable_domain(domain, auth_result.user_email)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Domain '{domain}' added to disposable domains blocklist"
|
||||
message=t("en", "admin.domainAddedToBl", domain=domain)
|
||||
)
|
||||
|
||||
|
||||
@@ -126,11 +127,11 @@ async def remove_disposable_domain(
|
||||
|
||||
domain = domain.lower().strip()
|
||||
if not email_validation.remove_disposable_domain(domain, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="Domain not found in blocklist")
|
||||
raise HTTPException(status_code=404, detail=t("en", "admin.domainNotFoundInBl"))
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Domain '{domain}' removed from disposable domains blocklist"
|
||||
message=t("en", "admin.domainRemovedFromBl", domain=domain)
|
||||
)
|
||||
|
||||
|
||||
@@ -143,9 +144,9 @@ async def add_allowlisted_domain(
|
||||
email_validation = get_email_validation_service()
|
||||
domain = request.domain.lower().strip()
|
||||
if not domain or "." not in domain:
|
||||
raise HTTPException(status_code=400, detail="Invalid domain format")
|
||||
raise HTTPException(status_code=400, detail=t("en", "admin.invalidDomainFormat"))
|
||||
email_validation.add_allowlisted_domain(domain, auth_result.user_email)
|
||||
return SuccessResponse(success=True, message=f"Domain '{domain}' added to allowlist")
|
||||
return SuccessResponse(success=True, message=t("en", "admin.domainAddedToAllowlist", domain=domain))
|
||||
|
||||
|
||||
@router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse)
|
||||
@@ -157,8 +158,8 @@ async def remove_allowlisted_domain(
|
||||
email_validation = get_email_validation_service()
|
||||
domain = domain.lower().strip()
|
||||
if not email_validation.remove_allowlisted_domain(domain, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="Domain not found in allowlist")
|
||||
return SuccessResponse(success=True, message=f"Domain '{domain}' removed from allowlist")
|
||||
raise HTTPException(status_code=404, detail=t("en", "admin.domainNotFoundInAllowlist"))
|
||||
return SuccessResponse(success=True, message=t("en", "admin.domainRemovedFromAllowlist", domain=domain))
|
||||
|
||||
|
||||
@router.post("/blocklists/sync", response_model=SuccessResponse)
|
||||
@@ -181,7 +182,7 @@ async def trigger_sync(
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Synced {result['external_count']} external domains ({result['added']} added, {result['removed']} removed)"
|
||||
message=t("en", "admin.syncComplete", external_count=result['external_count'], added=result['added'], removed=result['removed'])
|
||||
)
|
||||
|
||||
|
||||
@@ -195,13 +196,13 @@ async def add_blocked_email(
|
||||
|
||||
email = request.email.lower().strip()
|
||||
if not email or "@" not in email:
|
||||
raise HTTPException(status_code=400, detail="Invalid email format")
|
||||
raise HTTPException(status_code=400, detail=t("en", "admin.invalidEmailFormat"))
|
||||
|
||||
email_validation.add_blocked_email(email, auth_result.user_email)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Email '{email}' added to blocked emails list"
|
||||
message=t("en", "admin.emailAddedToBl", email=email)
|
||||
)
|
||||
|
||||
|
||||
@@ -215,11 +216,11 @@ async def remove_blocked_email(
|
||||
|
||||
email = email.lower().strip()
|
||||
if not email_validation.remove_blocked_email(email, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="Email not found in blocklist")
|
||||
raise HTTPException(status_code=404, detail=t("en", "admin.emailNotFoundInBl"))
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Email '{email}' removed from blocked emails list"
|
||||
message=t("en", "admin.emailRemovedFromBl", email=email)
|
||||
)
|
||||
|
||||
|
||||
@@ -233,13 +234,13 @@ async def add_blocked_ip(
|
||||
|
||||
ip_address = request.ip_address.strip()
|
||||
if not ip_address:
|
||||
raise HTTPException(status_code=400, detail="Invalid IP address")
|
||||
raise HTTPException(status_code=400, detail=t("en", "admin.invalidIPAddress"))
|
||||
|
||||
email_validation.add_blocked_ip(ip_address, auth_result.user_email)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"IP '{ip_address}' added to blocked IPs list"
|
||||
message=t("en", "admin.ipAddedToBl", ip_address=ip_address)
|
||||
)
|
||||
|
||||
|
||||
@@ -253,11 +254,11 @@ async def remove_blocked_ip(
|
||||
|
||||
ip_address = ip_address.strip()
|
||||
if not email_validation.remove_blocked_ip(ip_address, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="IP not found in blocklist")
|
||||
raise HTTPException(status_code=404, detail=t("en", "admin.ipNotFoundInBl"))
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"IP '{ip_address}' removed from blocked IPs list"
|
||||
message=t("en", "admin.ipRemovedFromBl", ip_address=ip_address)
|
||||
)
|
||||
|
||||
|
||||
@@ -303,12 +304,12 @@ async def retry_youtube_upload(
|
||||
if not queue_service.retry_upload(job_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Upload not found or not in retryable state for job {job_id}"
|
||||
detail=t("en", "admin.youtubeUploadNotFound", job_id=job_id)
|
||||
)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"YouTube upload for job {job_id} queued for retry"
|
||||
message=t("en", "admin.youtubeUploadQueuedForRetry", job_id=job_id)
|
||||
)
|
||||
|
||||
|
||||
@@ -341,5 +342,5 @@ async def trigger_youtube_queue_processing(
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message="YouTube queue processing started in background"
|
||||
message=t("en", "admin.youtubeQueueProcessingStarted")
|
||||
)
|
||||
@@ -36,6 +36,7 @@ from backend.services.encoding_service import get_encoding_service
|
||||
from backend.api.dependencies import require_auth, require_review_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
# LyricsTranscriber imports for preview generation
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
@@ -113,12 +114,12 @@ async def get_correction_data(
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not ready for review (current status: {job.status})"
|
||||
detail=t("en", "review.reviewNotReady", status=job.status)
|
||||
)
|
||||
|
||||
# Check for updated corrections first (from previous review sessions where user edited lyrics)
|
||||
@@ -139,7 +140,7 @@ async def get_correction_data(
|
||||
if not storage.file_exists(corrections_gcs):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Corrections data not found. Lyrics processing may not be complete."
|
||||
detail=t("en", "review.correctionsNotFound")
|
||||
)
|
||||
|
||||
# Download and return corrections data
|
||||
@@ -224,7 +225,7 @@ async def get_correction_data(
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error loading corrections: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error loading corrections: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/{audio_hash}")
|
||||
@@ -260,11 +261,11 @@ async def _stream_audio(job_id: str):
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
if not audio_gcs_path:
|
||||
raise HTTPException(status_code=404, detail="Audio file not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
|
||||
try:
|
||||
transcoding = AudioTranscodingService()
|
||||
@@ -274,7 +275,7 @@ async def _stream_audio(job_id: str):
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error generating audio signed URL: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error serving audio: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.audioServeError", error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/complete")
|
||||
@@ -298,12 +299,12 @@ async def complete_review(
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
detail=t("en", "review.reviewNotReady", status=job.status)
|
||||
)
|
||||
|
||||
# === Require instrumental selection ===
|
||||
@@ -311,7 +312,7 @@ async def complete_review(
|
||||
if not instrumental_selection:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="instrumental_selection is required. Must be 'clean' or 'with_backing'."
|
||||
detail=t("en", "review.instrumentalSelectionRequired")
|
||||
)
|
||||
|
||||
valid_selections = ["clean", "with_backing"]
|
||||
@@ -323,7 +324,7 @@ async def complete_review(
|
||||
if instrumental_selection not in valid_selections:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid instrumental_selection. Must be one of: {valid_selections}"
|
||||
detail=t("en", "review.invalidInstrumentalSelection", valid_selections=valid_selections)
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -331,12 +332,16 @@ async def complete_review(
|
||||
# (it's stored separately in state_data)
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# Save updated corrections to GCS
|
||||
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
storage.upload_json(corrections_gcs_path, corrections_to_save)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
|
||||
|
||||
logger.info(f"Job {job_id}: Saved updated corrections")
|
||||
# Only write corrections_updated.json if there's actual correction data.
|
||||
# Writing an empty dict causes KeyError downstream when render workers
|
||||
# try to access updated_data["corrections"].
|
||||
if corrections_to_save and "corrections" in corrections_to_save:
|
||||
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
storage.upload_json(corrections_gcs_path, corrections_to_save)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
|
||||
logger.info(f"Job {job_id}: Saved updated corrections")
|
||||
else:
|
||||
logger.info(f"Job {job_id}: No corrections data in request, skipping corrections_updated.json")
|
||||
|
||||
# === Store instrumental selection in state_data ===
|
||||
# This will be used by render_video_worker to skip AWAITING_INSTRUMENTAL_SELECTION
|
||||
@@ -380,7 +385,7 @@ async def complete_review(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error completing review: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error completing review: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.reviewCompletedError", error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/handlers")
|
||||
@@ -396,7 +401,7 @@ async def update_handlers(
|
||||
would require re-running correction.
|
||||
"""
|
||||
logger.info(f"Job {job_id}: Handler update requested (not implemented)")
|
||||
return {"status": "success", "message": "Handler updates not yet implemented"}
|
||||
return {"status": "success", "message": t("en", "review.handlersUpdateNotImplemented")}
|
||||
|
||||
|
||||
@router.post("/{job_id}/add-lyrics")
|
||||
@@ -416,13 +421,13 @@ async def add_lyrics(
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
# Job must be in review state to add lyrics
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
detail=t("en", "review.reviewNotReady", status=job.status)
|
||||
)
|
||||
|
||||
source = data.get("source", "").strip()
|
||||
@@ -497,11 +502,11 @@ async def add_lyrics(
|
||||
# ValueError from CorrectionOperations (e.g., duplicate source name)
|
||||
logger.warning(f"Job {job_id}: Invalid add lyrics request: {e}")
|
||||
span.set_attribute("error", str(e))
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
raise HTTPException(status_code=400, detail=t("en", "review.lyricsAddInvalidRequest", error=str(e)))
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to add lyrics: {e}", exc_info=True)
|
||||
span.set_attribute("error", str(e))
|
||||
raise HTTPException(status_code=500, detail=f"Failed to add lyrics: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.lyricsAddError", error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/search-lyrics")
|
||||
@@ -537,12 +542,12 @@ async def search_lyrics(
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
detail=t("en", "review.reviewNotReady", status=job.status)
|
||||
)
|
||||
|
||||
artist = (data.get("artist") or "").strip()
|
||||
@@ -602,7 +607,7 @@ async def search_lyrics(
|
||||
span.set_attribute("success", False)
|
||||
return {
|
||||
"status": "no_results",
|
||||
"message": "No matching lyrics found from any provider",
|
||||
"message": t("en", "review.lyricsSearchNoResults"),
|
||||
"sources_added": [],
|
||||
"sources_rejected": sources_rejected,
|
||||
"sources_not_found": sources_not_found,
|
||||
@@ -642,11 +647,11 @@ async def search_lyrics(
|
||||
except ValueError as e:
|
||||
logger.warning(f"Job {job_id}: Invalid search lyrics request: {e}")
|
||||
span.set_attribute("error", str(e))
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
raise HTTPException(status_code=400, detail=t("en", "review.lyricsSearchInvalidRequest", error=str(e)))
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to search lyrics: {e}", exc_info=True)
|
||||
span.set_attribute("error", str(e))
|
||||
raise HTTPException(status_code=500, detail=f"Failed to search lyrics: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.lyricsSearchError", error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/preview-video")
|
||||
@@ -671,13 +676,13 @@ async def generate_preview_video(
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
# Job must be in review state to generate preview
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
detail=t("en", "review.reviewNotReady", status=job.status)
|
||||
)
|
||||
|
||||
# Check if GCE preview encoding is enabled
|
||||
@@ -851,7 +856,7 @@ async def generate_preview_video(
|
||||
span.set_attribute("error", str(e))
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Failed to generate preview video: {e}"
|
||||
detail=t("en", "review.previewVideoGenerationError", error=str(e))
|
||||
) from e
|
||||
|
||||
|
||||
@@ -872,7 +877,7 @@ async def get_preview_video(
|
||||
# Try standard path
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
if not storage.file_exists(preview_gcs_path):
|
||||
raise HTTPException(status_code=404, detail="Preview video not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.previewVideoNotFound"))
|
||||
|
||||
try:
|
||||
# Download to temp file and stream
|
||||
@@ -897,7 +902,7 @@ async def get_preview_video(
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error streaming preview video: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error streaming preview video: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
@@ -937,7 +942,7 @@ async def submit_annotation(
|
||||
|
||||
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))
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.annotationSaveError", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/{job_id}/v1/annotations/stats")
|
||||
@@ -978,7 +983,7 @@ async def get_instrumental_analysis(
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
# Get backing vocals analysis from state_data
|
||||
backing_analysis = job.state_data.get('backing_vocals_analysis', {})
|
||||
@@ -1046,7 +1051,7 @@ async def get_waveform_data(
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
# Get backing vocals path
|
||||
stems = job.file_urls.get('stems', {})
|
||||
@@ -1057,7 +1062,7 @@ async def get_waveform_data(
|
||||
backing_vocals_path = job.input_media_gcs_path
|
||||
|
||||
if not backing_vocals_path:
|
||||
raise HTTPException(status_code=404, detail="No audio available for waveform")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.waveformNoAudio"))
|
||||
|
||||
try:
|
||||
analysis_service = AudioAnalysisService()
|
||||
@@ -1075,7 +1080,7 @@ async def get_waveform_data(
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error generating waveform data: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error generating waveform: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.waveformGenerationError", error=str(e)))
|
||||
|
||||
|
||||
# ============================================
|
||||
@@ -1107,11 +1112,11 @@ async def save_review_session(
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
correction_data = data.get("correction_data")
|
||||
if not correction_data:
|
||||
raise HTTPException(status_code=400, detail="correction_data is required")
|
||||
raise HTTPException(status_code=400, detail=t("en", "review.sessionSaveError"))
|
||||
|
||||
# Compute hash for deduplication
|
||||
data_json = json.dumps(correction_data, sort_keys=True, default=str)
|
||||
@@ -1280,7 +1285,7 @@ async def save_audio_edit_session(
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
user_email = auth_info[0] if isinstance(auth_info, tuple) else ""
|
||||
edit_data = data.get("edit_data", {})
|
||||
@@ -1473,7 +1478,7 @@ async def get_input_audio_info(
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if not job.input_media_gcs_path:
|
||||
raise HTTPException(status_code=404, detail="No input audio available")
|
||||
@@ -1580,7 +1585,7 @@ async def apply_audio_edit(
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
@@ -1677,7 +1682,7 @@ async def undo_audio_edit(
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
@@ -1724,7 +1729,7 @@ async def redo_audio_edit(
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
@@ -1780,7 +1785,7 @@ async def upload_audio_for_join(
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
@@ -1873,7 +1878,7 @@ async def submit_audio_edit(
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
|
||||
@@ -12,6 +12,7 @@ from fastapi import APIRouter, Query, Request
|
||||
|
||||
from backend.models.tenant import TenantConfigResponse, TenantPublicConfig
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -115,6 +116,6 @@ async def get_tenant_asset(tenant_id: str, asset_name: str):
|
||||
if not url:
|
||||
from fastapi import HTTPException
|
||||
|
||||
raise HTTPException(status_code=404, detail="Asset not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "tenant.assetNotFound"))
|
||||
|
||||
return RedirectResponse(url=url)
|
||||
@@ -9,10 +9,11 @@ before job creation.
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from backend.models.theme import ThemeDetailResponse, ThemesListResponse
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -20,7 +21,7 @@ router = APIRouter(prefix="/themes", tags=["themes"])
|
||||
|
||||
|
||||
@router.get("", response_model=ThemesListResponse)
|
||||
async def list_themes() -> ThemesListResponse:
|
||||
async def list_themes(request: Request) -> ThemesListResponse:
|
||||
"""
|
||||
List all available themes.
|
||||
|
||||
@@ -29,6 +30,7 @@ async def list_themes() -> ThemesListResponse:
|
||||
|
||||
This endpoint is public and does not require authentication.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
themes = theme_service.list_themes()
|
||||
@@ -37,12 +39,12 @@ async def list_themes() -> ThemesListResponse:
|
||||
logger.error(f"Error listing themes: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load themes"
|
||||
detail=t(locale, "themes.themesLoadError")
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
|
||||
async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
|
||||
"""
|
||||
Get detailed information about a specific theme.
|
||||
|
||||
@@ -58,6 +60,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
Raises:
|
||||
404: Theme not found
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
theme = theme_service.get_theme(theme_id)
|
||||
@@ -65,7 +68,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
if theme is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
detail=t(locale, "themes.themeNotFound", theme_id=theme_id)
|
||||
)
|
||||
|
||||
return ThemeDetailResponse(theme=theme)
|
||||
@@ -75,12 +78,12 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
logger.error(f"Error getting theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load theme"
|
||||
detail=t(locale, "themes.themeLoadError")
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}/preview")
|
||||
async def get_theme_preview(theme_id: str) -> dict:
|
||||
async def get_theme_preview(theme_id: str, request: Request) -> dict:
|
||||
"""
|
||||
Get a signed URL for the theme's preview image.
|
||||
|
||||
@@ -96,20 +99,21 @@ async def get_theme_preview(theme_id: str) -> dict:
|
||||
Raises:
|
||||
404: Theme not found or no preview available
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
detail=t(locale, "themes.themeNotFound", theme_id=theme_id)
|
||||
)
|
||||
|
||||
theme = theme_service.get_theme(theme_id)
|
||||
if theme is None or theme.preview_url is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"No preview available for theme: {theme_id}"
|
||||
detail=t(locale, "themes.previewNotAvailable", theme_id=theme_id)
|
||||
)
|
||||
|
||||
return {"preview_url": theme.preview_url}
|
||||
@@ -119,12 +123,12 @@ async def get_theme_preview(theme_id: str) -> dict:
|
||||
logger.error(f"Error getting preview for theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load theme preview"
|
||||
detail=t(locale, "themes.previewLoadError")
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}/youtube-description")
|
||||
async def get_theme_youtube_description(theme_id: str) -> dict:
|
||||
async def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
|
||||
"""
|
||||
Get the YouTube description template for a theme.
|
||||
|
||||
@@ -141,13 +145,14 @@ async def get_theme_youtube_description(theme_id: str) -> dict:
|
||||
Raises:
|
||||
404: Theme not found
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
detail=t(locale, "themes.youtubeDescriptionNotFound", theme_id=theme_id)
|
||||
)
|
||||
|
||||
description = theme_service.get_youtube_description(theme_id)
|
||||
@@ -158,5 +163,5 @@ async def get_theme_youtube_description(theme_id: str) -> dict:
|
||||
logger.error(f"Error getting YouTube description for theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load YouTube description"
|
||||
detail=t(locale, "themes.youtubeDescriptionLoadError")
|
||||
)
|
||||
+57
-26
@@ -35,6 +35,7 @@ def _mask_email(email: str) -> str:
|
||||
from fastapi import APIRouter, HTTPException, Depends, Request, Header
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.services.email_validation_service import get_email_validation_service
|
||||
from backend.models.user import (
|
||||
UserRole,
|
||||
@@ -182,18 +183,20 @@ async def send_magic_link(
|
||||
# (done before email service check so we can reject without needing email config)
|
||||
email_validation = get_email_validation_service()
|
||||
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
if email_validation.is_disposable_domain(email):
|
||||
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="disposable_email_not_allowed"
|
||||
detail=t(locale, "users.disposableEmailBlocked")
|
||||
)
|
||||
|
||||
if email_validation.is_email_blocked(email):
|
||||
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
ip_address = get_client_ip(http_request)
|
||||
@@ -201,7 +204,7 @@ async def send_magic_link(
|
||||
logger.warning(f"Blocked IP signup attempt: {ip_address}")
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
# Per-IP and per-fingerprint signup rate limit (only for new users)
|
||||
@@ -217,7 +220,7 @@ async def send_magic_link(
|
||||
# Silent reject (anti-enumeration)
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
# Check if email service is configured
|
||||
@@ -225,7 +228,7 @@ async def send_magic_link(
|
||||
logger.error("Email service not configured - cannot send magic links")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Email service is not available. Please contact support."
|
||||
detail=t(locale, "users.emailServiceNotConfigured")
|
||||
)
|
||||
|
||||
# Get tenant context from middleware
|
||||
@@ -239,7 +242,7 @@ async def send_magic_link(
|
||||
# Return success anyway to prevent email enumeration
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
# Get client info for security logging (ip_address already extracted above for blocklist check)
|
||||
@@ -270,6 +273,7 @@ async def send_magic_link(
|
||||
sender_email=sender_email,
|
||||
tenant_frontend_url=tenant_frontend_url,
|
||||
tenant_name=tenant_name,
|
||||
locale=locale,
|
||||
)
|
||||
|
||||
if not sent:
|
||||
@@ -291,7 +295,7 @@ async def send_magic_link(
|
||||
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
|
||||
@@ -308,9 +312,11 @@ async def verify_magic_link(
|
||||
Returns a session token that should be stored and used for subsequent requests.
|
||||
The session will be associated with the tenant from the magic link.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
# Reject empty tokens early to avoid invalid Firestore document paths
|
||||
if not token or not token.strip():
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.invalidToken"))
|
||||
|
||||
# Get client info
|
||||
ip_address = get_client_ip(http_request)
|
||||
@@ -334,7 +340,7 @@ async def verify_magic_link(
|
||||
success, user, message = user_service.verify_magic_link(token)
|
||||
|
||||
if not success or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.verifyError", message=message))
|
||||
|
||||
# Grant welcome credits on first verification (with AI abuse evaluation)
|
||||
# Use pre-computed evaluation from magic link if available (computed at send time)
|
||||
@@ -359,6 +365,13 @@ async def verify_magic_link(
|
||||
elif credit_status == "denied":
|
||||
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
|
||||
|
||||
# Persist user's locale preference (from Accept-Language header)
|
||||
if locale and locale != (user.locale or "en"):
|
||||
try:
|
||||
user_service.update_user(user.email, locale=locale)
|
||||
except Exception:
|
||||
pass # Non-critical — don't block login
|
||||
|
||||
# Create session with tenant context and device fingerprint from the magic link
|
||||
magic_link_fingerprint = magic_link_data.get('device_fingerprint') if magic_link_doc.exists else None
|
||||
session = user_service.create_session(
|
||||
@@ -371,7 +384,7 @@ async def verify_magic_link(
|
||||
|
||||
# Send welcome email to first-time users
|
||||
if is_first_login:
|
||||
email_service.send_welcome_email(user.email, user.credits)
|
||||
email_service.send_welcome_email(user.email, user.credits, locale=locale)
|
||||
|
||||
# Return user info with tenant_id
|
||||
user_public = UserPublic(
|
||||
@@ -397,7 +410,7 @@ async def verify_magic_link(
|
||||
status="success",
|
||||
session_token=session.token,
|
||||
user=user_public,
|
||||
message="Successfully signed in",
|
||||
message=t(locale, "users.magicLinkSuccess"),
|
||||
tenant_subdomain=tenant_subdomain,
|
||||
credits_granted=credits_granted,
|
||||
credit_status=credit_status,
|
||||
@@ -406,21 +419,23 @@ async def verify_magic_link(
|
||||
|
||||
@router.post("/auth/logout", response_model=LogoutResponse)
|
||||
async def logout(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Logout and invalidate the current session.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
if not authorization:
|
||||
return LogoutResponse(status="success", message="Already logged out")
|
||||
return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess"))
|
||||
|
||||
# Extract token from "Bearer <token>"
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
user_service.revoke_session(token)
|
||||
|
||||
return LogoutResponse(status="success", message="Successfully logged out")
|
||||
return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess"))
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -429,6 +444,7 @@ async def logout(
|
||||
|
||||
@router.get("/me", response_model=UserProfileResponse)
|
||||
async def get_current_user(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -437,10 +453,11 @@ async def get_current_user(
|
||||
|
||||
Requires a valid session token or admin token.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
from backend.services.auth_service import get_auth_service
|
||||
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
# Extract token
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
@@ -471,7 +488,7 @@ async def get_current_user(
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
feedback_eligible = (
|
||||
user.total_jobs_completed >= 2
|
||||
@@ -1144,6 +1161,7 @@ async def stripe_webhook(
|
||||
|
||||
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
|
||||
async def check_feedback_eligibility(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -1152,8 +1170,9 @@ async def check_feedback_eligibility(
|
||||
|
||||
Eligible if: total_jobs_completed >= 2 AND has not already submitted feedback.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
@@ -1168,7 +1187,7 @@ async def check_feedback_eligibility(
|
||||
else:
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
eligible = user.total_jobs_completed >= 2 and not user.has_submitted_feedback
|
||||
|
||||
@@ -1182,6 +1201,7 @@ async def check_feedback_eligibility(
|
||||
|
||||
@router.post("/feedback", response_model=UserFeedbackResponse)
|
||||
async def submit_user_feedback(
|
||||
http_request: Request,
|
||||
request: UserFeedbackRequest,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -1193,8 +1213,9 @@ async def submit_user_feedback(
|
||||
not have already submitted feedback. At least one text field
|
||||
must have >50 characters.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
@@ -1209,20 +1230,20 @@ async def submit_user_feedback(
|
||||
else:
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
# 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."
|
||||
detail=t(locale, "users.feedbackNotEligible")
|
||||
)
|
||||
|
||||
# Check if already submitted
|
||||
if user.has_submitted_feedback:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="You have already submitted feedback. Thank you!"
|
||||
detail=t(locale, "users.feedbackNotEligible")
|
||||
)
|
||||
|
||||
# Validate: at least one text field has >50 characters
|
||||
@@ -1495,12 +1516,14 @@ async def list_users(
|
||||
@router.get("/admin/users/{email}/detail", response_model=UserDetailResponse)
|
||||
async def get_user_detail(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Get detailed user information including credit history and recent jobs (admin only).
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from urllib.parse import unquote
|
||||
@@ -1510,7 +1533,7 @@ async def get_user_detail(
|
||||
|
||||
user = user_service.get_user(email)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
db = user_service.db
|
||||
|
||||
@@ -1627,18 +1650,20 @@ async def add_credits_to_user(
|
||||
@router.post("/admin/users/{email}/disable")
|
||||
async def disable_user(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Disable a user account (admin only).
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success = user_service.disable_user(email, admin_email=admin_id)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
return {"status": "success", "message": f"User {email} has been disabled"}
|
||||
|
||||
@@ -1646,18 +1671,20 @@ async def disable_user(
|
||||
@router.post("/admin/users/{email}/enable")
|
||||
async def enable_user(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Enable a user account (admin only).
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success = user_service.enable_user(email, admin_email=admin_id)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
return {"status": "success", "message": f"User {email} has been enabled"}
|
||||
|
||||
@@ -1665,6 +1692,7 @@ async def enable_user(
|
||||
@router.delete("/admin/users/{email}")
|
||||
async def delete_user(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -1673,6 +1701,7 @@ async def delete_user(
|
||||
|
||||
Jobs are NOT deleted - they remain as historical records.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
try:
|
||||
@@ -1681,7 +1710,7 @@ async def delete_user(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
return {"status": "success", "message": f"User {email} has been deleted"}
|
||||
|
||||
@@ -1690,18 +1719,20 @@ async def delete_user(
|
||||
async def set_user_role(
|
||||
email: str,
|
||||
role: UserRole,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Set a user's role (admin only).
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success = user_service.set_user_role(email, role, admin_email=admin_id)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
return {"status": "success", "message": f"User {email} role set to {role.value}"}
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
Lightweight i18n utility for backend translations.
|
||||
|
||||
Usage:
|
||||
from backend.i18n import t, get_locale_from_request, SUPPORTED_LOCALES
|
||||
|
||||
# In a route handler:
|
||||
locale = get_locale_from_request(request)
|
||||
message = t(locale, "auth.userNotFound")
|
||||
message = t(locale, "jobs.notFound", job_id="abc123")
|
||||
"""
|
||||
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from starlette.requests import Request
|
||||
|
||||
SUPPORTED_LOCALES = ("en", "es", "de")
|
||||
DEFAULT_LOCALE = "en"
|
||||
TRANSLATIONS_DIR = Path(__file__).parent / "translations"
|
||||
|
||||
|
||||
@lru_cache(maxsize=len(SUPPORTED_LOCALES))
|
||||
def _load_translations(locale: str) -> dict[str, Any]:
|
||||
"""Load and cache translation file for a locale."""
|
||||
path = TRANSLATIONS_DIR / f"{locale}.json"
|
||||
if not path.exists():
|
||||
if locale != DEFAULT_LOCALE:
|
||||
return _load_translations(DEFAULT_LOCALE)
|
||||
return {}
|
||||
with open(path, encoding="utf-8") as f:
|
||||
result: dict[str, Any] = json.load(f)
|
||||
return result
|
||||
|
||||
|
||||
def t(locale: str, key: str, **kwargs: Any) -> str:
|
||||
"""Get a translated string by dotted key path.
|
||||
|
||||
Args:
|
||||
locale: Language code (en, es, de)
|
||||
key: Dotted path like "auth.userNotFound" or "emails.magicLink.subject"
|
||||
**kwargs: Interpolation variables (e.g., job_id="abc123")
|
||||
|
||||
Returns:
|
||||
Translated string with variables interpolated, or the key itself if not found.
|
||||
"""
|
||||
if locale not in SUPPORTED_LOCALES:
|
||||
locale = DEFAULT_LOCALE
|
||||
|
||||
translations = _load_translations(locale)
|
||||
|
||||
# Walk the dotted path
|
||||
value: Any = translations
|
||||
for part in key.split("."):
|
||||
if isinstance(value, dict) and part in value:
|
||||
value = value[part]
|
||||
else:
|
||||
# Key not found — fall back to English
|
||||
if locale != DEFAULT_LOCALE:
|
||||
return t(DEFAULT_LOCALE, key, **kwargs)
|
||||
return key # Return the key itself as last resort
|
||||
|
||||
if not isinstance(value, str):
|
||||
return key
|
||||
|
||||
result: str = value
|
||||
# Interpolate variables
|
||||
if kwargs:
|
||||
try:
|
||||
result = result.format(**kwargs)
|
||||
except KeyError:
|
||||
pass # Missing variable — return template as-is
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_locale_from_request(request: Request) -> str:
|
||||
"""Extract locale from Accept-Language header.
|
||||
|
||||
Returns the first supported locale found, or DEFAULT_LOCALE.
|
||||
"""
|
||||
accept_lang = request.headers.get("accept-language", "")
|
||||
|
||||
# Simple parsing — Accept-Language can be "de", "de-DE", "en-US,en;q=0.9,de;q=0.8"
|
||||
for part in accept_lang.split(","):
|
||||
lang = part.split(";")[0].strip().split("-")[0].lower()
|
||||
if lang in SUPPORTED_LOCALES:
|
||||
return lang
|
||||
|
||||
return DEFAULT_LOCALE
|
||||
|
||||
|
||||
def get_locale_prefix(locale: str) -> str:
|
||||
"""Get URL locale prefix for frontend URLs (e.g., '/en', '/es')."""
|
||||
if locale not in SUPPORTED_LOCALES:
|
||||
locale = DEFAULT_LOCALE
|
||||
return f"/{locale}"
|
||||
+4
-2
@@ -170,18 +170,20 @@ app.include_router(tenant.router) # Tenant/white-label configuration (no /api p
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
|
||||
@app.exception_handler(InsufficientCreditsError)
|
||||
async def insufficient_credits_exception_handler(request: Request, exc: InsufficientCreditsError):
|
||||
"""Handle insufficient credits errors with 402 Payment Required status."""
|
||||
locale = get_locale_from_request(request)
|
||||
return JSONResponse(
|
||||
status_code=402,
|
||||
content={
|
||||
"detail": exc.message,
|
||||
"detail": t(locale, "errors.insufficientCredits"),
|
||||
"credits_available": exc.credits_available,
|
||||
"credits_required": exc.credits_required,
|
||||
"buy_url": "/#pricing",
|
||||
"buy_url": t(locale, "errors.insufficientCreditsBuyUrl"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -91,6 +91,9 @@ class User(BaseModel):
|
||||
# Optional profile fields for future use
|
||||
display_name: Optional[str] = None
|
||||
|
||||
# i18n locale preference (set from Accept-Language on login, used for emails/push)
|
||||
locale: Optional[str] = None
|
||||
|
||||
# Push notification subscriptions (Web Push API)
|
||||
# Users can subscribe from multiple devices/browsers
|
||||
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
|
||||
|
||||
+172
-153
@@ -19,6 +19,7 @@ from typing import Optional, List
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_prefix
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
|
||||
@@ -249,6 +250,7 @@ class EmailService:
|
||||
sender_email: Optional[str] = None,
|
||||
tenant_frontend_url: Optional[str] = None,
|
||||
tenant_name: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send a magic link email for authentication.
|
||||
@@ -264,10 +266,10 @@ class EmailService:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
base_url = tenant_frontend_url or self.frontend_url
|
||||
magic_link_url = f"{base_url}/auth/verify?token={token}"
|
||||
magic_link_url = f"{base_url}{get_locale_prefix(locale)}/auth/verify?token={token}"
|
||||
|
||||
brand_name = tenant_name or "Nomad Karaoke"
|
||||
subject = f"Sign in to {brand_name}"
|
||||
subject = t(locale, "emails.magicLink.subject", brand_name=brand_name)
|
||||
|
||||
extra_styles = """
|
||||
.warning {
|
||||
@@ -281,38 +283,38 @@ class EmailService:
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>Hi there,</p>
|
||||
<p>{t(locale, "emails.magicLink.greeting")}</p>
|
||||
|
||||
<p>Click the button below to sign in to {html.escape(brand_name)}:</p>
|
||||
<p>{t(locale, "emails.magicLink.signInPrompt", brand_name=html.escape(brand_name))}</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{magic_link_url}" class="button">Sign In</a>
|
||||
<a href="{magic_link_url}" class="button">{t(locale, "emails.magicLink.signInButton")}</a>
|
||||
</p>
|
||||
|
||||
<div class="warning">
|
||||
⏰ This link expires in 15 minutes and can only be used once.
|
||||
⏰ {t(locale, "emails.magicLink.expiryWarning")}
|
||||
</div>
|
||||
|
||||
<p>If the button doesn't work, copy and paste this link into your browser:</p>
|
||||
<p>{t(locale, "emails.magicLink.fallbackLink")}</p>
|
||||
<p style="word-break: break-all; font-size: 14px; color: #666;">
|
||||
{magic_link_url}
|
||||
</p>
|
||||
|
||||
<p>If you didn't request this email, you can safely ignore it.</p>
|
||||
<p>{t(locale, "emails.magicLink.ignoreNote")}</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
text_content = f"""
|
||||
Sign in to {brand_name}
|
||||
{t(locale, "emails.magicLink.signInButton")}
|
||||
========================
|
||||
|
||||
Click this link to sign in:
|
||||
{t(locale, "emails.magicLink.signInPrompt", brand_name=brand_name)}
|
||||
{magic_link_url}
|
||||
|
||||
This link expires in 15 minutes and can only be used once.
|
||||
{t(locale, "emails.magicLink.expiryWarning")}
|
||||
|
||||
If you didn't request this email, you can safely ignore it.
|
||||
{t(locale, "emails.magicLink.ignoreNote")}
|
||||
|
||||
---
|
||||
© {self._get_year()} {brand_name}
|
||||
@@ -322,7 +324,7 @@ If you didn't request this email, you can safely ignore it.
|
||||
email, subject, html_content, text_content, from_email_override=sender_email
|
||||
)
|
||||
|
||||
def send_credits_added(self, email: str, credits: int, total_credits: int) -> bool:
|
||||
def send_credits_added(self, email: str, credits: int, total_credits: int, locale: str = "en") -> bool:
|
||||
"""
|
||||
Send notification when credits are added to account.
|
||||
|
||||
@@ -334,7 +336,7 @@ If you didn't request this email, you can safely ignore it.
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
subject = f"🎉 {credits} credits added to your Nomad Karaoke account"
|
||||
subject = t(locale, "emails.creditsAdded.subject", credits=credits)
|
||||
|
||||
extra_styles = f"""
|
||||
.credits-box {{
|
||||
@@ -353,39 +355,39 @@ If you didn't request this email, you can safely ignore it.
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>Great news!</p>
|
||||
<p>{t(locale, "emails.creditsAdded.greatNews")}</p>
|
||||
|
||||
<p><strong>{credits} credits</strong> have been added to your account.</p>
|
||||
<p><strong>{t(locale, "emails.creditsAdded.creditsAddedMessage", credits=credits)}</strong></p>
|
||||
|
||||
<div class="credits-box">
|
||||
<div>Your balance:</div>
|
||||
<div>{t(locale, "emails.creditsAdded.yourBalance")}</div>
|
||||
<div class="credits-number">{total_credits}</div>
|
||||
<div>credits</div>
|
||||
<div>{t(locale, "emails.creditsAdded.credits")}</div>
|
||||
</div>
|
||||
|
||||
<p>Each credit lets you create one professional karaoke video with:</p>
|
||||
<p>{t(locale, "emails.creditsAdded.eachCreditLets")}</p>
|
||||
<ul>
|
||||
<li>AI-powered vocal/instrumental separation</li>
|
||||
<li>Synchronized lyrics with word-level timing</li>
|
||||
<li>4K video output</li>
|
||||
<li>YouTube upload</li>
|
||||
<li>{t(locale, "emails.creditsAdded.featureVocalSeparation")}</li>
|
||||
<li>{t(locale, "emails.creditsAdded.featureLyrics")}</li>
|
||||
<li>{t(locale, "emails.creditsAdded.feature4k")}</li>
|
||||
<li>{t(locale, "emails.creditsAdded.featureYoutube")}</li>
|
||||
</ul>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{self.frontend_url}" class="button">Create Karaoke Now</a>
|
||||
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">{t(locale, "emails.creditsAdded.createButton")}</a>
|
||||
</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
text_content = f"""
|
||||
{credits} credits added to your Nomad Karaoke account!
|
||||
{t(locale, "emails.creditsAdded.creditsAddedMessage", credits=credits)}
|
||||
|
||||
Your new balance: {total_credits} credits
|
||||
{t(locale, "emails.creditsAdded.yourBalance")} {total_credits} {t(locale, "emails.creditsAdded.credits")}
|
||||
|
||||
Each credit lets you create one professional karaoke video.
|
||||
{t(locale, "emails.creditsAdded.eachCreditLets")}
|
||||
|
||||
Start creating: {self.frontend_url}
|
||||
{self.frontend_url}{get_locale_prefix(locale)}
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
@@ -393,7 +395,7 @@ Start creating: {self.frontend_url}
|
||||
|
||||
return self.provider.send_email(email, subject, html_content, text_content)
|
||||
|
||||
def send_welcome_email(self, email: str, credits: int = 0) -> bool:
|
||||
def send_welcome_email(self, email: str, credits: int = 0, locale: str = "en") -> bool:
|
||||
"""
|
||||
Send welcome email to new users.
|
||||
|
||||
@@ -404,7 +406,7 @@ Start creating: {self.frontend_url}
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
subject = "Welcome to Nomad Karaoke! 🎤"
|
||||
subject = t(locale, "emails.welcome.subject")
|
||||
|
||||
extra_styles = """
|
||||
.credits-box {
|
||||
@@ -447,87 +449,87 @@ Start creating: {self.frontend_url}
|
||||
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 class="credits-label">{t(locale, "emails.welcome.freeCreditsLabel")}</div>
|
||||
<div class="credits-note">{t(locale, "emails.welcome.freeCreditsNote")}</div>
|
||||
</div>
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>Welcome to Nomad Karaoke!</p>
|
||||
<p>{t(locale, "emails.welcome.welcomeGreeting")}</p>
|
||||
|
||||
<p>Turn any song into a professional karaoke video in minutes.</p>
|
||||
<p>{t(locale, "emails.welcome.turnAnySong")}</p>
|
||||
|
||||
{credits_box}
|
||||
|
||||
<p><strong>Here's how it works:</strong></p>
|
||||
<p><strong>{t(locale, "emails.welcome.howItWorks")}</strong></p>
|
||||
|
||||
<div class="feature">
|
||||
<span class="feature-icon">🎵</span>
|
||||
<div>
|
||||
<strong>1. Search for a song</strong><br>
|
||||
Enter the artist and title, and we'll find high-quality audio.
|
||||
<strong>{t(locale, "emails.welcome.step1Title")}</strong><br>
|
||||
{t(locale, "emails.welcome.step1Desc")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<span class="feature-icon">✨</span>
|
||||
<div>
|
||||
<strong>2. Our system works its magic</strong><br>
|
||||
We separate vocals, transcribe lyrics, and sync everything perfectly.
|
||||
<strong>{t(locale, "emails.welcome.step2Title")}</strong><br>
|
||||
{t(locale, "emails.welcome.step2Desc")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<span class="feature-icon">✏️</span>
|
||||
<div>
|
||||
<strong>3. Review & customize</strong><br>
|
||||
Fine-tune the lyrics if needed, choose your instrumental.
|
||||
<strong>{t(locale, "emails.welcome.step3Title")}</strong><br>
|
||||
{t(locale, "emails.welcome.step3Desc")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="feature">
|
||||
<span class="feature-icon">🎬</span>
|
||||
<div>
|
||||
<strong>4. Get your video</strong><br>
|
||||
Download your 4K karaoke video or upload directly to YouTube.
|
||||
<strong>{t(locale, "emails.welcome.step4Title")}</strong><br>
|
||||
{t(locale, "emails.welcome.step4Desc")}
|
||||
</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!
|
||||
{t(locale, "emails.welcome.feedbackBonus")}
|
||||
</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{self.frontend_url}" class="button">Get Started</a>
|
||||
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">{t(locale, "emails.welcome.getStartedButton")}</a>
|
||||
</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
credits_text = f"\nYou have {credits} free credits to get started!\nEach credit creates one professional karaoke video.\n" if credits > 0 else ""
|
||||
credits_text = f"\n{t(locale, 'emails.welcome.freeCreditsNote')}: {credits}\n" if credits > 0 else ""
|
||||
|
||||
text_content = f"""
|
||||
Welcome to Nomad Karaoke!
|
||||
{t(locale, "emails.welcome.welcomeGreeting")}
|
||||
|
||||
Turn any song into a professional karaoke video in minutes.
|
||||
{t(locale, "emails.welcome.turnAnySong")}
|
||||
{credits_text}
|
||||
Here's how it works:
|
||||
{t(locale, "emails.welcome.howItWorks")}
|
||||
|
||||
1. Search for a song
|
||||
Enter the artist and title, and we'll find high-quality audio.
|
||||
{t(locale, "emails.welcome.step1Title")}
|
||||
{t(locale, "emails.welcome.step1Desc")}
|
||||
|
||||
2. Our system works its magic
|
||||
We separate vocals, transcribe lyrics, and sync everything perfectly.
|
||||
{t(locale, "emails.welcome.step2Title")}
|
||||
{t(locale, "emails.welcome.step2Desc")}
|
||||
|
||||
3. Review & customize
|
||||
Fine-tune the lyrics if needed, choose your instrumental.
|
||||
{t(locale, "emails.welcome.step3Title")}
|
||||
{t(locale, "emails.welcome.step3Desc")}
|
||||
|
||||
4. Get your video
|
||||
Download your 4K karaoke video or upload directly to YouTube.
|
||||
{t(locale, "emails.welcome.step4Title")}
|
||||
{t(locale, "emails.welcome.step4Desc")}
|
||||
|
||||
Complete 2 videos and earn 2 more free credits by sharing your feedback!
|
||||
{t(locale, "emails.welcome.feedbackBonus")}
|
||||
|
||||
Get started: {self.frontend_url}
|
||||
{self.frontend_url}{get_locale_prefix(locale)}
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
@@ -553,10 +555,10 @@ Get started: {self.frontend_url}
|
||||
</div>
|
||||
"""
|
||||
|
||||
def _get_email_footer(self) -> str:
|
||||
def _get_email_footer(self, locale: str = "en") -> str:
|
||||
"""Get the standard email footer with support message and signature."""
|
||||
return f"""
|
||||
<p style="margin-top: 30px; font-style: italic; color: #666;">If anything isn't perfect, just reply to this email and I'll fix it!</p>
|
||||
<p style="margin-top: 30px; font-style: italic; color: #666;">{t(locale, "emails.shared.footerHelp")}</p>
|
||||
|
||||
<div class="signature">
|
||||
{self._get_email_signature()}
|
||||
@@ -599,13 +601,14 @@ Get started: {self.frontend_url}
|
||||
}}
|
||||
"""
|
||||
|
||||
def _build_email_html(self, content: str, extra_styles: str = "", extra_header_content: str = "") -> str:
|
||||
def _build_email_html(self, content: str, extra_styles: str = "", extra_header_content: str = "", locale: str = "en") -> str:
|
||||
"""Build a complete HTML email with standard header, footer, and styles.
|
||||
|
||||
Args:
|
||||
content: The main body content of the email
|
||||
extra_styles: Additional CSS styles specific to this email type
|
||||
extra_header_content: Optional extra content to add in header (e.g., beta badge)
|
||||
locale: Locale for footer localization
|
||||
|
||||
Returns:
|
||||
Complete HTML email string
|
||||
@@ -624,7 +627,7 @@ Get started: {self.frontend_url}
|
||||
|
||||
{content}
|
||||
|
||||
{self._get_email_footer()}
|
||||
{self._get_email_footer(locale)}
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
@@ -870,6 +873,7 @@ Get started: {self.frontend_url}
|
||||
title: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
cc_admin: bool = True,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send job completion email with the rendered template content.
|
||||
@@ -891,11 +895,11 @@ Get started: {self.frontend_url}
|
||||
safe_artist = sanitize_filename(artist) if artist else None
|
||||
safe_title = sanitize_filename(title) if title else None
|
||||
if brand_code and safe_artist and safe_title:
|
||||
subject = f"{brand_code}: {safe_artist} - {safe_title} (Your karaoke video is ready!)"
|
||||
subject = t(locale, "emails.jobCompletion.subjectWithBrand", brand_code=brand_code, artist=safe_artist, title=safe_title)
|
||||
elif safe_artist and safe_title:
|
||||
subject = f"{safe_artist} - {safe_title} (Your karaoke video is ready!)"
|
||||
subject = t(locale, "emails.jobCompletion.subject", artist=safe_artist, title=safe_title)
|
||||
else:
|
||||
subject = "Your karaoke video is ready!"
|
||||
subject = t(locale, "emails.jobCompletion.subjectFallback")
|
||||
|
||||
extra_styles = """
|
||||
.content {
|
||||
@@ -907,7 +911,7 @@ Get started: {self.frontend_url}
|
||||
<div class="content">{html.escape(message_content)}</div>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
cc_emails = ["gen@nomadkaraoke.com"] if cc_admin else None
|
||||
|
||||
@@ -927,6 +931,7 @@ Get started: {self.frontend_url}
|
||||
action_type: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send action-needed reminder email.
|
||||
@@ -942,13 +947,26 @@ Get started: {self.frontend_url}
|
||||
True if email was sent successfully
|
||||
"""
|
||||
# Build subject based on action type
|
||||
song_info = f" for {artist} - {title}" if artist and title else ""
|
||||
if action_type == "lyrics":
|
||||
subject = f"Action needed: Review lyrics{song_info}"
|
||||
if artist and title:
|
||||
subject = t(locale, "emails.actionReminder.lyricsSubject", artist=artist, title=title)
|
||||
else:
|
||||
subject = t(locale, "emails.actionReminder.lyricsSubjectFallback")
|
||||
elif action_type == "instrumental":
|
||||
subject = f"Action needed: Select instrumental{song_info}"
|
||||
if artist and title:
|
||||
subject = t(locale, "emails.actionReminder.instrumentalSubject", artist=artist, title=title)
|
||||
else:
|
||||
subject = t(locale, "emails.actionReminder.instrumentalSubjectFallback")
|
||||
elif action_type == "audio_edit":
|
||||
if artist and title:
|
||||
subject = t(locale, "emails.actionReminder.audioEditSubject", artist=artist, title=title)
|
||||
else:
|
||||
subject = t(locale, "emails.actionReminder.audioEditSubjectFallback")
|
||||
else:
|
||||
subject = f"Action needed{song_info}"
|
||||
if artist and title:
|
||||
subject = t(locale, "emails.actionReminder.audioEditSubject", artist=artist, title=title)
|
||||
else:
|
||||
subject = t(locale, "emails.actionReminder.audioEditSubjectFallback")
|
||||
|
||||
extra_styles = """
|
||||
.alert {
|
||||
@@ -966,13 +984,13 @@ Get started: {self.frontend_url}
|
||||
|
||||
content = f"""
|
||||
<div class="alert">
|
||||
⏰ Your karaoke video needs input from you!
|
||||
⏰ {t(locale, "emails.actionReminder.alertHeading")}
|
||||
</div>
|
||||
|
||||
<div class="content">{html.escape(message_content)}</div>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
@@ -987,6 +1005,7 @@ Get started: {self.frontend_url}
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
job_id: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send 24h review reminder email with expiry warning.
|
||||
@@ -1003,10 +1022,13 @@ Get started: {self.frontend_url}
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
song_info = f" — {artist} - {title}" if artist and title else ""
|
||||
subject = f"Reminder: Your karaoke video is waiting for review{song_info}"
|
||||
if artist and title:
|
||||
subject = t(locale, "emails.reviewReminder.subject", artist=artist, title=title)
|
||||
else:
|
||||
subject = t(locale, "emails.reviewReminder.subjectFallback")
|
||||
|
||||
review_url = f"{self.frontend_url}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}/app"
|
||||
locale_prefix = get_locale_prefix(locale)
|
||||
review_url = f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}{locale_prefix}/app"
|
||||
|
||||
extra_styles = """
|
||||
.alert {
|
||||
@@ -1039,36 +1061,35 @@ Get started: {self.frontend_url}
|
||||
"""
|
||||
|
||||
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
|
||||
song_name_text = f" for {artist} - {title}" if artist and title else ""
|
||||
|
||||
content = f"""
|
||||
<div class="alert">
|
||||
⏰ Your karaoke video is waiting for you!
|
||||
⏰ {t(locale, "emails.reviewReminder.alertHeading")}
|
||||
</div>
|
||||
|
||||
<p>Hi there! Just a friendly reminder that your karaoke video{song_name} is ready for review.</p>
|
||||
<p>{t(locale, "emails.reviewReminder.reminderIntro", song_name=song_name)}</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(review_url)}" class="review-btn">Review Your Video</a>
|
||||
<a href="{html.escape(review_url)}" class="review-btn">{t(locale, "emails.reviewReminder.reviewButton")}</a>
|
||||
</p>
|
||||
|
||||
<p>During the review, you can check the lyrics are correct and choose your preferred instrumental track. It usually only takes a few minutes!</p>
|
||||
<p>{t(locale, "emails.reviewReminder.reviewInstructions")}</p>
|
||||
|
||||
<p>If you're having any trouble with the review process, just reply to this email and I'll be happy to help you out.</p>
|
||||
<p>{t(locale, "emails.reviewReminder.helpOffer")}</p>
|
||||
|
||||
<div class="expiry-warning">
|
||||
⚠️ Please note: if the review isn't completed within the next <strong>24 hours</strong>,
|
||||
the job will automatically expire and your credit will be refunded.
|
||||
⚠️ {t(locale, "emails.reviewReminder.expiryWarning")}
|
||||
</div>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
text_content = (
|
||||
f"Reminder: Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} is ready for review.\n\n"
|
||||
f"Review it here: {review_url}\n\n"
|
||||
"If you're having trouble with the review process, just reply to this email and I'll help you out.\n\n"
|
||||
"Please note: if the review isn't completed within the next 24 hours, "
|
||||
"the job will automatically expire and your credit will be refunded."
|
||||
f"{t(locale, 'emails.reviewReminder.reminderIntro', song_name=song_name_text)}\n\n"
|
||||
f"{t(locale, 'emails.reviewReminder.reviewButton')}: {review_url}\n\n"
|
||||
f"{t(locale, 'emails.reviewReminder.helpOffer')}\n\n"
|
||||
f"{t(locale, 'emails.reviewReminder.expiryWarning')}"
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
@@ -1084,6 +1105,7 @@ Get started: {self.frontend_url}
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
credits_balance: int = 0,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send review expiry notification email.
|
||||
@@ -1100,8 +1122,10 @@ Get started: {self.frontend_url}
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
song_info = f" — {artist} - {title}" if artist and title else ""
|
||||
subject = f"Your karaoke video has expired{song_info}"
|
||||
if artist and title:
|
||||
subject = t(locale, "emails.reviewExpired.subject", artist=artist, title=title)
|
||||
else:
|
||||
subject = t(locale, "emails.reviewExpired.subjectFallback")
|
||||
|
||||
extra_styles = """
|
||||
.info-box {
|
||||
@@ -1133,33 +1157,32 @@ Get started: {self.frontend_url}
|
||||
"""
|
||||
|
||||
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
|
||||
song_name_text = f" for {artist} - {title}" if artist and title else ""
|
||||
credits_word = t(locale, "emails.reviewExpired.creditSingular") if credits_balance == 1 else t(locale, "emails.reviewExpired.creditPlural")
|
||||
|
||||
content = f"""
|
||||
<div class="info-box">
|
||||
Your karaoke video{song_name} has been automatically cancelled because the review
|
||||
wasn't completed within 48 hours.
|
||||
{t(locale, "emails.reviewExpired.cancelNotice", song_name=song_name)}
|
||||
</div>
|
||||
|
||||
<p>Don't worry — your credit has been refunded! Your current balance is
|
||||
<span class="credit-badge">{credits_balance} credit{'s' if credits_balance != 1 else ''}</span>.</p>
|
||||
<p>{t(locale, "emails.reviewExpired.refundNotice", credits_balance=credits_balance, credits_word=credits_word)}</p>
|
||||
|
||||
<p>You can create a new karaoke video anytime using your credits:</p>
|
||||
<p>{t(locale, "emails.reviewExpired.createNewPrompt")}</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(self.frontend_url)}/app" class="create-btn">Create New Video</a>
|
||||
<a href="{html.escape(self.frontend_url)}{get_locale_prefix(locale)}/app" class="create-btn">{t(locale, "emails.reviewExpired.createButton")}</a>
|
||||
</p>
|
||||
|
||||
<p>If you had any trouble with the review process or need help, just reply to this email — I'd love to help!</p>
|
||||
<p>{t(locale, "emails.reviewExpired.helpOffer")}</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
text_content = (
|
||||
f"Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} has been "
|
||||
"automatically cancelled because the review wasn't completed within 48 hours.\n\n"
|
||||
f"Your credit has been refunded. Current balance: {credits_balance} credit{'s' if credits_balance != 1 else ''}.\n\n"
|
||||
f"Create a new video anytime: {self.frontend_url}/app\n\n"
|
||||
"If you had any trouble or need help, just reply to this email."
|
||||
f"{t(locale, 'emails.reviewExpired.cancelNotice', song_name=song_name_text)}\n\n"
|
||||
f"{t(locale, 'emails.reviewExpired.refundNotice', credits_balance=credits_balance, credits_word=credits_word)}\n\n"
|
||||
f"{self.frontend_url}{get_locale_prefix(locale)}/app\n\n"
|
||||
f"{t(locale, 'emails.reviewExpired.helpOffer')}"
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
@@ -1176,6 +1199,7 @@ Get started: {self.frontend_url}
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send follow-up email when a deferred YouTube upload completes.
|
||||
@@ -1193,11 +1217,11 @@ Get started: {self.frontend_url}
|
||||
safe_artist = sanitize_filename(artist) if artist else None
|
||||
safe_title = sanitize_filename(title) if title else None
|
||||
if brand_code and safe_artist and safe_title:
|
||||
subject = f"{brand_code}: {safe_artist} - {safe_title} (YouTube upload ready!)"
|
||||
subject = t(locale, "emails.youtubeUpload.subjectWithBrand", brand_code=brand_code, artist=safe_artist, title=safe_title)
|
||||
elif safe_artist and safe_title:
|
||||
subject = f"{safe_artist} - {safe_title} (YouTube upload ready!)"
|
||||
subject = t(locale, "emails.youtubeUpload.subject", artist=safe_artist, title=safe_title)
|
||||
else:
|
||||
subject = "Your YouTube upload is ready!"
|
||||
subject = t(locale, "emails.youtubeUpload.subjectFallback")
|
||||
|
||||
extra_styles = """
|
||||
.content {
|
||||
@@ -1209,7 +1233,7 @@ Get started: {self.frontend_url}
|
||||
<div class="content">{html.escape(message_content)}</div>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
@@ -1226,6 +1250,7 @@ Get started: {self.frontend_url}
|
||||
title: str,
|
||||
job_id: str,
|
||||
notes: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send order confirmation email to customer for made-for-you orders.
|
||||
@@ -1240,7 +1265,7 @@ Get started: {self.frontend_url}
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
subject = f"Order Confirmed: {artist} - {title} | Nomad Karaoke"
|
||||
subject = t(locale, "emails.madeForYouConfirmation.subject", artist=artist, title=title)
|
||||
|
||||
extra_styles = """
|
||||
.order-details {
|
||||
@@ -1266,42 +1291,42 @@ Get started: {self.frontend_url}
|
||||
notes_html = ""
|
||||
notes_text = ""
|
||||
if notes:
|
||||
notes_html = f"<p><strong>Your Notes:</strong> {html.escape(notes)}</p>"
|
||||
notes_text = f"\nYour Notes: {notes}"
|
||||
notes_html = f"<p><strong>{t(locale, 'emails.madeForYouConfirmation.yourNotes')}</strong> {html.escape(notes)}</p>"
|
||||
notes_text = f"\n{t(locale, 'emails.madeForYouConfirmation.yourNotes')} {notes}"
|
||||
|
||||
content = f"""
|
||||
<h2>Thank You for Your Order!</h2>
|
||||
<h2>{t(locale, "emails.madeForYouConfirmation.thankYou")}</h2>
|
||||
|
||||
<div class="order-details">
|
||||
<h3>Order Details</h3>
|
||||
<p><strong>Order ID:</strong> {html.escape(job_id)}</p>
|
||||
<p><strong>Artist:</strong> {html.escape(artist)}</p>
|
||||
<p><strong>Title:</strong> {html.escape(title)}</p>
|
||||
<h3>{t(locale, "emails.madeForYouConfirmation.orderDetails")}</h3>
|
||||
<p><strong>{t(locale, "emails.madeForYouConfirmation.orderId")}</strong> {html.escape(job_id)}</p>
|
||||
<p><strong>{t(locale, "emails.madeForYouConfirmation.artist")}</strong> {html.escape(artist)}</p>
|
||||
<p><strong>{t(locale, "emails.madeForYouConfirmation.title")}</strong> {html.escape(title)}</p>
|
||||
{notes_html}
|
||||
</div>
|
||||
|
||||
<p>Our team will create your custom karaoke video within <span class="highlight">24 hours</span>.</p>
|
||||
<p>{t(locale, "emails.madeForYouConfirmation.deliveryTime", hours=24)}</p>
|
||||
|
||||
<p>You'll receive an email with download links as soon as your video is ready.</p>
|
||||
<p>{t(locale, "emails.madeForYouConfirmation.deliveryNotice")}</p>
|
||||
|
||||
<p><strong>No action needed</strong> - sit back and we'll take care of everything!</p>
|
||||
<p><strong>{t(locale, "emails.madeForYouConfirmation.noAction")}</strong></p>
|
||||
"""
|
||||
|
||||
text_content = f"""Thank You for Your Order!
|
||||
text_content = f"""{t(locale, "emails.madeForYouConfirmation.thankYou")}
|
||||
|
||||
Order Details:
|
||||
Order ID: {job_id}
|
||||
Artist: {artist}
|
||||
Title: {title}{notes_text}
|
||||
{t(locale, "emails.madeForYouConfirmation.orderDetails")}:
|
||||
{t(locale, "emails.madeForYouConfirmation.orderId")} {job_id}
|
||||
{t(locale, "emails.madeForYouConfirmation.artist")} {artist}
|
||||
{t(locale, "emails.madeForYouConfirmation.title")} {title}{notes_text}
|
||||
|
||||
Our team will create your custom karaoke video within 24 hours.
|
||||
{t(locale, "emails.madeForYouConfirmation.deliveryTime", hours=24)}
|
||||
|
||||
You'll receive an email with download links as soon as your video is ready.
|
||||
{t(locale, "emails.madeForYouConfirmation.deliveryNotice")}
|
||||
|
||||
No action needed - sit back and we'll take care of everything!
|
||||
{t(locale, "emails.madeForYouConfirmation.noAction")}
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
@@ -1662,59 +1687,53 @@ If the user looks legitimate, grant them credits from their admin page.
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_credit_denied_email(self, email: str, grant_type: str = "welcome") -> bool:
|
||||
def send_credit_denied_email(self, email: str, grant_type: str = "welcome", locale: str = "en") -> bool:
|
||||
"""
|
||||
Send a friendly-but-firm email when free credits are denied due to abuse signals.
|
||||
|
||||
CC'd to andrew@beveridge.uk so he can intervene if it's a false positive.
|
||||
The tone invites the user to reply if it's a mistake.
|
||||
"""
|
||||
subject = "About your Nomad Karaoke free credits"
|
||||
subject = t(locale, "emails.creditDenied.subject")
|
||||
|
||||
credit_type = "welcome credits" if grant_type == "welcome" else "feedback bonus credits"
|
||||
credit_type = t(locale, "emails.creditDenied.welcomeCredits") if grant_type == "welcome" else t(locale, "emails.creditDenied.feedbackCredits")
|
||||
|
||||
content = f"""
|
||||
<p>Hi there,</p>
|
||||
<p>{t(locale, "emails.creditDenied.greeting")}</p>
|
||||
|
||||
<p>Thanks for signing up for Nomad Karaoke!</p>
|
||||
<p>{t(locale, "emails.creditDenied.thankYou")}</p>
|
||||
|
||||
<p>Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected
|
||||
patterns that suggest this may not be your first account with us, and each karaoke generation job
|
||||
costs us real money in cloud computing and API fees.</p>
|
||||
<p>{t(locale, "emails.creditDenied.deniedMessage", credit_type=credit_type)}</p>
|
||||
|
||||
<p>We totally understand if this is a mistake! If you're a genuine new user, please just
|
||||
<strong>reply to this email</strong> and let Andrew (the founder) know. He built this service and is
|
||||
happy to grant you some free credits to try it out — he just asks that you provide honest feedback
|
||||
on the experience in return.</p>
|
||||
<p>{t(locale, "emails.creditDenied.mistakeNote")}</p>
|
||||
|
||||
<p>If you'd like to get started right away, you can also purchase credits:</p>
|
||||
<p>{t(locale, "emails.creditDenied.buyPrompt")}</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{self.buy_url}" class="button">Buy Credits</a>
|
||||
<a href="{self.buy_url}" class="button">{t(locale, "emails.creditDenied.buyButton")}</a>
|
||||
</p>
|
||||
|
||||
<p style="color: #999; font-size: 14px;">We keep costs low so we can offer the service affordably,
|
||||
which means we need to be careful about free credit abuse. Thanks for understanding!</p>
|
||||
<p style="color: #999; font-size: 14px;">{t(locale, "emails.creditDenied.costNote")}</p>
|
||||
|
||||
{self._get_email_signature()}
|
||||
"""
|
||||
|
||||
text_content = f"""Hi there,
|
||||
text_content = f"""{t(locale, "emails.creditDenied.greeting")}
|
||||
|
||||
Thanks for signing up for Nomad Karaoke!
|
||||
{t(locale, "emails.creditDenied.thankYou")}
|
||||
|
||||
Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected patterns that suggest this may not be your first account with us, and each karaoke generation job costs us real money in cloud computing and API fees.
|
||||
{t(locale, "emails.creditDenied.deniedMessage", credit_type=credit_type)}
|
||||
|
||||
We totally understand if this is a mistake! If you're a genuine new user, please just reply to this email and let Andrew (the founder) know. He built this service and is happy to grant you some free credits to try it out - he just asks that you provide honest feedback on the experience in return.
|
||||
{t(locale, "emails.creditDenied.mistakeNote")}
|
||||
|
||||
If you'd like to get started right away, you can also purchase credits:
|
||||
{t(locale, "emails.creditDenied.buyPrompt")}
|
||||
{self.buy_url}
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content)
|
||||
html_content = self._build_email_html(content, locale=locale)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=email,
|
||||
|
||||
@@ -161,8 +161,10 @@ STYLE_CACHE_DIR = Path("/var/cache/karaoke-gen/styles")
|
||||
def download_with_cache(gcs_uri: str, local_path: Path, cache_dir: Optional[Path] = STYLE_CACHE_DIR):
|
||||
"""Download a file from GCS, using a local disk cache to skip repeated downloads.
|
||||
|
||||
Cache key is SHA-256 of the GCS URI. Cache hits copy from disk instead of
|
||||
downloading. When cache_dir is None, downloads directly (no caching).
|
||||
Cache key is SHA-256 of the GCS URI. Cache hits are validated by comparing
|
||||
the cached file size against the GCS object size (via a lightweight metadata
|
||||
call). On size mismatch the stale entry is replaced.
|
||||
When cache_dir is None, downloads directly (no caching).
|
||||
"""
|
||||
if cache_dir is None:
|
||||
download_single_file_from_gcs(gcs_uri, local_path)
|
||||
@@ -173,9 +175,30 @@ def download_with_cache(gcs_uri: str, local_path: Path, cache_dir: Optional[Path
|
||||
cached_path = cache_dir / cache_key
|
||||
|
||||
if cached_path.exists():
|
||||
logger.info(f"Cache hit for {gcs_uri} -> {cached_path}")
|
||||
shutil.copy2(str(cached_path), str(local_path))
|
||||
return
|
||||
# Validate cached file against GCS object size
|
||||
try:
|
||||
parts = gcs_uri.replace("gs://", "").split("/", 1)
|
||||
bucket_name = parts[0]
|
||||
blob_name = parts[1] if len(parts) > 1 else ""
|
||||
blob = storage_client.bucket(bucket_name).blob(blob_name)
|
||||
blob.reload() # Fetch metadata (lightweight HEAD request)
|
||||
gcs_size = blob.size
|
||||
|
||||
cached_size = cached_path.stat().st_size
|
||||
if gcs_size is not None and cached_size != gcs_size:
|
||||
logger.warning(
|
||||
f"Cache stale for {gcs_uri}: cached={cached_size}B, GCS={gcs_size}B. Re-downloading."
|
||||
)
|
||||
cached_path.unlink()
|
||||
else:
|
||||
logger.info(f"Cache hit for {gcs_uri} -> {cached_path}")
|
||||
shutil.copy2(str(cached_path), str(local_path))
|
||||
return
|
||||
except Exception as e:
|
||||
# On transient GCS errors, serve from cache rather than failing the job
|
||||
logger.warning(f"Cache validation failed for {gcs_uri}: {e}. Serving from cache.")
|
||||
shutil.copy2(str(cached_path), str(local_path))
|
||||
return
|
||||
|
||||
logger.info(f"Cache miss for {gcs_uri}, downloading...")
|
||||
download_single_file_from_gcs(gcs_uri, local_path)
|
||||
@@ -287,143 +310,178 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
|
||||
|
||||
|
||||
def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest"):
|
||||
'''Run video rendering using OutputGenerator from the karaoke-gen wheel.
|
||||
"""Run video rendering using OutputGenerator from the karaoke-gen wheel.
|
||||
|
||||
Downloads corrections, audio, and style assets, then uses OutputGenerator
|
||||
to render karaoke video with synchronized lyrics. Uploads video and lyrics
|
||||
output files to GCS.
|
||||
'''
|
||||
Downloads corrections, audio, and style assets from GCS, runs OutputGenerator
|
||||
to produce with_vocals.mkv and subtitle files, then uploads results.
|
||||
Style assets use disk cache to avoid repeated downloads of the same theme.
|
||||
|
||||
This mirrors the logic in render_video_worker.py but runs on the GCE VM
|
||||
instead of Cloud Run, providing more memory and CPU for ffmpeg/libass.
|
||||
"""
|
||||
jobs[job_id]["status"] = "running"
|
||||
jobs[job_id]["progress"] = 5
|
||||
jobs[job_id]["output_files"] = []
|
||||
|
||||
try:
|
||||
# Import from karaoke-gen wheel (installed by ensure_latest_wheel)
|
||||
from backend.output_generator import OutputGenerator, OutputConfig
|
||||
from backend.services.countdown_processor import CountdownProcessor
|
||||
from backend.models.correction_result import CorrectionResult
|
||||
from backend.services.correction_operations import CorrectionOperations
|
||||
from backend.utils.style_utils import load_styles_from_gcs
|
||||
from backend.utils.filename_utils import sanitize_filename
|
||||
logger.info("Imported karaoke-gen wheel modules for render-video")
|
||||
# Import from installed karaoke-gen wheel
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
from karaoke_gen.style_loader import load_styles_from_gcs
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
# Download original corrections
|
||||
# 1. Download original corrections
|
||||
corrections_path = work_dir / "corrections.json"
|
||||
download_single_file_from_gcs(request.original_corrections_gcs_path, corrections_path)
|
||||
correction_result = CorrectionResult.from_json(corrections_path.read_text())
|
||||
jobs[job_id]["progress"] = 15
|
||||
logger.info(f"Loaded corrections from {request.original_corrections_gcs_path}")
|
||||
|
||||
# Apply updated corrections if provided
|
||||
with open(corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# 2. Apply user corrections if available
|
||||
if request.updated_corrections_gcs_path:
|
||||
updated_path = work_dir / "updated_corrections.json"
|
||||
updated_path = work_dir / "corrections_updated.json"
|
||||
download_single_file_from_gcs(request.updated_corrections_gcs_path, updated_path)
|
||||
updated_data = json.loads(updated_path.read_text())
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
correction_result, updated_data
|
||||
)
|
||||
logger.info(f"Applied updated corrections from {request.updated_corrections_gcs_path}")
|
||||
jobs[job_id]["progress"] = 20
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
if isinstance(updated_data, dict) and "corrections" in updated_data:
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
logger.info(f"[job:{job_id}] Applied user corrections")
|
||||
else:
|
||||
logger.warning(f"[job:{job_id}] corrections_updated.json exists but has no 'corrections' key, using base result")
|
||||
correction_result = base_result
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
# Download audio
|
||||
jobs[job_id]["progress"] = 25
|
||||
|
||||
# 3. Download audio
|
||||
audio_path = work_dir / "audio.flac"
|
||||
download_single_file_from_gcs(request.audio_gcs_path, audio_path)
|
||||
jobs[job_id]["progress"] = 30
|
||||
logger.info(f"Downloaded audio from {request.audio_gcs_path}")
|
||||
jobs[job_id]["progress"] = 35
|
||||
|
||||
# Run countdown processor
|
||||
countdown_processor = CountdownProcessor()
|
||||
correction_result, countdown_added, countdown_seconds = countdown_processor.process(
|
||||
correction_result, audio_path
|
||||
# 4. Process countdown intro
|
||||
countdown_processor = CountdownProcessor(cache_dir=str(work_dir), logger=logger)
|
||||
correction_result, audio_path_str, padding_added, padding_seconds = countdown_processor.process(
|
||||
correction_result=correction_result,
|
||||
audio_filepath=str(audio_path),
|
||||
)
|
||||
audio_path = Path(audio_path_str)
|
||||
jobs[job_id]["progress"] = 40
|
||||
logger.info(f"Countdown processing: added={countdown_added}, seconds={countdown_seconds}")
|
||||
|
||||
# Download style assets via load_styles_from_gcs (with caching)
|
||||
style_config, font_assets = load_styles_from_gcs(
|
||||
# 5. Download style assets (with disk cache for repeated themes)
|
||||
def cached_download(gcs_path, local_path):
|
||||
download_with_cache(gcs_path, Path(local_path), STYLE_CACHE_DIR)
|
||||
|
||||
styles_path, style_data = load_styles_from_gcs(
|
||||
style_params_gcs_path=request.style_params_gcs_path,
|
||||
style_assets=request.style_assets,
|
||||
download_fn=download_with_cache,
|
||||
work_dir=work_dir,
|
||||
temp_dir=str(work_dir),
|
||||
download_func=cached_download,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
# Register any downloaded fonts with fontconfig
|
||||
for asset_key, gcs_path in (request.style_assets or {}).items():
|
||||
if 'font' in asset_key.lower() and gcs_path.endswith(('.ttf', '.otf', '.woff', '.woff2')):
|
||||
fonts_dir = Path("/usr/local/share/fonts/custom")
|
||||
fonts_dir.mkdir(parents=True, exist_ok=True)
|
||||
font_filename = gcs_path.split("/")[-1]
|
||||
font_dest = fonts_dir / font_filename
|
||||
if not font_dest.exists():
|
||||
ext = os.path.splitext(gcs_path)[1]
|
||||
style_font = work_dir / "style" / f"{asset_key}{ext}"
|
||||
if style_font.exists():
|
||||
shutil.copy2(str(style_font), str(font_dest))
|
||||
subprocess.run(["fc-cache", "-fv"], capture_output=True)
|
||||
logger.info(f"Registered font: {font_filename}")
|
||||
|
||||
jobs[job_id]["progress"] = 50
|
||||
logger.info(f"Loaded style config with {len(font_assets)} font assets")
|
||||
|
||||
# Register font assets with fontconfig
|
||||
if font_assets:
|
||||
fonts_dir = Path("/usr/local/share/fonts/custom")
|
||||
fonts_dir.mkdir(parents=True, exist_ok=True)
|
||||
for font_path in font_assets:
|
||||
font_file = Path(font_path)
|
||||
if font_file.exists():
|
||||
dest_font = fonts_dir / font_file.name
|
||||
shutil.copy2(str(font_file), str(dest_font))
|
||||
logger.info(f"Installed font: {dest_font}")
|
||||
subprocess.run(["fc-cache", "-fv"], capture_output=True)
|
||||
logger.info("Updated fontconfig cache with style fonts")
|
||||
jobs[job_id]["progress"] = 55
|
||||
# 6. Configure and run OutputGenerator
|
||||
output_dir = work_dir / "output"
|
||||
cache_dir = work_dir / "cache"
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
cache_dir.mkdir(exist_ok=True)
|
||||
|
||||
# Configure OutputGenerator
|
||||
output_config = OutputConfig(
|
||||
config = OutputConfig(
|
||||
output_dir=str(output_dir),
|
||||
cache_dir=str(cache_dir),
|
||||
output_styles_json=styles_path,
|
||||
render_video=True,
|
||||
generate_cdg=False,
|
||||
generate_plain_text=True,
|
||||
generate_lrc=True,
|
||||
)
|
||||
|
||||
output_generator = OutputGenerator(
|
||||
correction_result=correction_result,
|
||||
audio_path=str(audio_path),
|
||||
output_dir=str(work_dir),
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
config=output_config,
|
||||
style_config=style_config,
|
||||
video_resolution=request.video_resolution,
|
||||
subtitle_offset_ms=request.subtitle_offset_ms,
|
||||
)
|
||||
|
||||
jobs[job_id]["progress"] = 60
|
||||
logger.info("Starting OutputGenerator.generate_outputs()")
|
||||
output_generator.generate_outputs()
|
||||
output_generator = OutputGenerator(config, logger)
|
||||
|
||||
safe_artist = sanitize_filename(request.artist) if request.artist else "Unknown"
|
||||
safe_title = sanitize_filename(request.title) if request.title else "Unknown"
|
||||
output_prefix = f"{safe_artist} - {safe_title}"
|
||||
|
||||
logger.info(f"[job:{job_id}] Generating outputs with prefix '{output_prefix}'")
|
||||
jobs[job_id]["progress"] = 55
|
||||
|
||||
outputs = output_generator.generate_outputs(
|
||||
transcription_corrected=correction_result,
|
||||
lyrics_results={},
|
||||
output_prefix=output_prefix,
|
||||
audio_filepath=str(audio_path),
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
)
|
||||
|
||||
jobs[job_id]["progress"] = 85
|
||||
logger.info("OutputGenerator.generate_outputs() complete")
|
||||
|
||||
# Upload outputs to GCS
|
||||
output_prefix = request.output_gcs_prefix.rstrip("/")
|
||||
output_mappings = [
|
||||
(work_dir / "videos" / "with_vocals.mkv", f"{output_prefix}/videos/with_vocals.mkv"),
|
||||
(work_dir / "lyrics" / "karaoke.ass", f"{output_prefix}/lyrics/karaoke.ass"),
|
||||
(work_dir / "lyrics" / "karaoke.lrc", f"{output_prefix}/lyrics/karaoke.lrc"),
|
||||
(work_dir / "lyrics" / "corrected.txt", f"{output_prefix}/lyrics/corrected.txt"),
|
||||
]
|
||||
# 7. Upload outputs to GCS
|
||||
output_prefix_gcs = request.output_gcs_prefix.rstrip("/")
|
||||
output_files = []
|
||||
|
||||
uploaded_files = []
|
||||
for local_file, gcs_path in output_mappings:
|
||||
if local_file.exists():
|
||||
upload_single_file_to_gcs(local_file, gcs_path)
|
||||
uploaded_files.append(gcs_path)
|
||||
logger.info(f"Uploaded {local_file.name} to {gcs_path}")
|
||||
else:
|
||||
logger.warning(f"Expected output file not found: {local_file}")
|
||||
if outputs.video and os.path.exists(outputs.video):
|
||||
gcs_path = f"{output_prefix_gcs}/videos/with_vocals.mkv"
|
||||
upload_single_file_to_gcs(Path(outputs.video), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
logger.info(f"[job:{job_id}] Uploaded with_vocals.mkv ({os.path.getsize(outputs.video)} bytes)")
|
||||
else:
|
||||
raise RuntimeError("Video generation failed - no output file produced")
|
||||
|
||||
if outputs.ass and os.path.exists(outputs.ass):
|
||||
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.ass"
|
||||
upload_single_file_to_gcs(Path(outputs.ass), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
|
||||
if outputs.lrc and os.path.exists(outputs.lrc):
|
||||
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.lrc"
|
||||
upload_single_file_to_gcs(Path(outputs.lrc), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
|
||||
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
|
||||
gcs_path = f"{output_prefix_gcs}/lyrics/corrected.txt"
|
||||
upload_single_file_to_gcs(Path(outputs.corrected_txt), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
|
||||
jobs[job_id]["output_files"] = uploaded_files
|
||||
jobs[job_id]["progress"] = 95
|
||||
|
||||
# Store metadata about countdown processing
|
||||
jobs[job_id]["output_files"] = output_files
|
||||
jobs[job_id]["metadata"] = {
|
||||
"countdown_padding_added": countdown_added,
|
||||
"countdown_padding_seconds": countdown_seconds,
|
||||
"countdown_padding_added": padding_added,
|
||||
"countdown_padding_seconds": padding_seconds if padding_added else 0,
|
||||
}
|
||||
|
||||
logger.info(f"Render video complete for job {job_id}. Uploaded {len(uploaded_files)} files.")
|
||||
return work_dir
|
||||
logger.info(f"[job:{job_id}] Render video complete. Output files: {output_files}")
|
||||
|
||||
except ImportError as e:
|
||||
error_msg = (
|
||||
f"Karaoke-gen wheel modules not available: {e}. "
|
||||
f"OutputGenerator not available: {e}. "
|
||||
"The karaoke-gen wheel must be installed. "
|
||||
"Check that ensure_latest_wheel() succeeded and wheel exists in GCS."
|
||||
"Check that ensure_latest_wheel() succeeded."
|
||||
)
|
||||
logger.error(error_msg)
|
||||
jobs[job_id]["status"] = "failed"
|
||||
@@ -431,7 +489,7 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
|
||||
raise RuntimeError(error_msg) from e
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Render video failed for job {job_id}: {e}")
|
||||
logger.error(f"[job:{job_id}] Render video failed: {e}")
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
raise
|
||||
@@ -505,6 +563,43 @@ def find_file(work_dir: Path, *patterns):
|
||||
return None
|
||||
|
||||
|
||||
def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) -> Path:
|
||||
"""Generate a MOV video from a static PNG image using FFmpeg.
|
||||
|
||||
This runs on the GCE encoding worker (not Cloud Run) because 4K H.264
|
||||
encoding requires more memory than the right-sized Cloud Run container
|
||||
provides (2Gi). See PR #640 / #647.
|
||||
|
||||
Args:
|
||||
png_path: Path to input PNG image
|
||||
mov_path: Path for output MOV video
|
||||
duration: Video duration in seconds (default 5)
|
||||
|
||||
Returns:
|
||||
Path to generated MOV file
|
||||
|
||||
Raises:
|
||||
RuntimeError: If FFmpeg fails
|
||||
"""
|
||||
command = [
|
||||
"ffmpeg", "-hide_banner", "-loglevel", "error", "-nostats", "-y",
|
||||
"-loop", "1", "-framerate", "30", "-i", str(png_path),
|
||||
"-f", "lavfi", "-i", "anullsrc",
|
||||
"-c:v", "libx264", "-r", "30", "-t", str(duration),
|
||||
"-pix_fmt", "yuv420p", "-vf", "scale=3840:2160",
|
||||
"-c:a", "aac", "-shortest",
|
||||
str(mov_path),
|
||||
]
|
||||
logger.info(f"Generating MOV from PNG: {png_path.name} -> {mov_path.name}")
|
||||
result = subprocess.run(command, capture_output=True, text=True, timeout=120)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"FFmpeg failed to generate {mov_path.name}: {result.stderr}")
|
||||
if not mov_path.exists() or mov_path.stat().st_size < 1024:
|
||||
raise RuntimeError(f"FFmpeg produced invalid output for {mov_path.name}")
|
||||
logger.info(f"Generated MOV: {mov_path.name} ({mov_path.stat().st_size} bytes)")
|
||||
return mov_path
|
||||
|
||||
|
||||
def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
'''Run encoding using LocalEncodingService (single source of truth).
|
||||
|
||||
@@ -534,10 +629,36 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
logger.info(f"Encoding for: {base_name}")
|
||||
|
||||
# Find input files in work_dir
|
||||
# Title/end screens are in screens/ subdirectory
|
||||
# Title/end screens: look for MOV first, fall back to generating from PNG.
|
||||
# Since PR #640 right-sized Cloud Run to 2Gi, the screens_worker only generates
|
||||
# PNG/JPG images — MOV video generation now happens here on the GCE worker.
|
||||
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov")
|
||||
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
|
||||
|
||||
# Get intro/end video durations from style config (default 5s)
|
||||
intro_duration = config.get("intro_video_duration", 5)
|
||||
end_duration = config.get("end_video_duration", 5)
|
||||
|
||||
# Generate title MOV from PNG if missing or invalid (< 1KB = empty shell)
|
||||
if not title_video or title_video.stat().st_size < 1024:
|
||||
title_png = find_file(work_dir, "screens/title.png", "*Title*.png", "*title*.png")
|
||||
if title_png:
|
||||
title_mov_path = title_png.parent / "title.mov"
|
||||
logger.info(f"Title MOV missing/invalid, generating from PNG: {title_png}")
|
||||
title_video = generate_mov_from_png(title_png, title_mov_path, duration=intro_duration)
|
||||
elif title_video:
|
||||
logger.warning(f"Title MOV is only {title_video.stat().st_size} bytes and no PNG found")
|
||||
|
||||
# Generate end MOV from PNG if missing or invalid
|
||||
if not end_video or (end_video and end_video.stat().st_size < 1024):
|
||||
end_png = find_file(work_dir, "screens/end.png", "*End*.png", "*end*.png")
|
||||
if end_png:
|
||||
end_mov_path = end_png.parent / "end.mov"
|
||||
logger.info(f"End MOV missing/invalid, generating from PNG: {end_png}")
|
||||
end_video = generate_mov_from_png(end_png, end_mov_path, duration=end_duration)
|
||||
elif end_video:
|
||||
logger.warning(f"End MOV is only {end_video.stat().st_size} bytes and no PNG found")
|
||||
|
||||
# Karaoke video - search for With Vocals or main karaoke video
|
||||
# IMPORTANT: Search order matters! Search specific paths first to avoid picking up
|
||||
# old encoding outputs from finals/ directory when re-encoding after reset
|
||||
|
||||
@@ -12,8 +12,10 @@ import logging
|
||||
import os
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from backend.i18n import get_locale_prefix
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.template_service import get_template_service
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -51,19 +53,30 @@ class JobNotificationService:
|
||||
self.frontend_url = os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
|
||||
self.backend_url = os.getenv("BACKEND_URL", "https://api.nomadkaraoke.com")
|
||||
|
||||
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None) -> str:
|
||||
def _get_user_locale(self, user_email: str) -> str:
|
||||
"""Look up user's locale preference from Firestore, defaulting to 'en'."""
|
||||
try:
|
||||
user_service = get_user_service()
|
||||
user = user_service.get_user(user_email)
|
||||
if user and user.locale:
|
||||
return user.locale
|
||||
except Exception:
|
||||
pass # Fall back to English
|
||||
return "en"
|
||||
|
||||
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None, locale: str = "en") -> str:
|
||||
"""Build the lyrics review URL for a job."""
|
||||
# Use hash-based routing for static hosting compatibility
|
||||
return f"{self.frontend_url}/app/jobs#/{job_id}/review"
|
||||
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/review"
|
||||
|
||||
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None) -> str:
|
||||
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None, locale: str = "en") -> str:
|
||||
"""Build the instrumental selection URL for a job."""
|
||||
# Use hash-based routing for static hosting compatibility
|
||||
return f"{self.frontend_url}/app/jobs#/{job_id}/instrumental"
|
||||
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/instrumental"
|
||||
|
||||
def _build_audio_edit_url(self, job_id: str) -> str:
|
||||
def _build_audio_edit_url(self, job_id: str, locale: str = "en") -> str:
|
||||
"""Build the audio edit URL for a job."""
|
||||
return f"{self.frontend_url}/app/jobs#/{job_id}/audio-edit"
|
||||
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/audio-edit"
|
||||
|
||||
async def send_job_completion_email(
|
||||
self,
|
||||
@@ -105,6 +118,9 @@ class JobNotificationService:
|
||||
return False
|
||||
|
||||
try:
|
||||
# Get user locale for email
|
||||
user_locale = self._get_user_locale(user_email)
|
||||
|
||||
# Render the completion message using template service
|
||||
message_content = self.template_service.render_job_completion(
|
||||
name=user_name,
|
||||
@@ -116,6 +132,7 @@ class JobNotificationService:
|
||||
feedback_url=FEEDBACK_FORM_URL,
|
||||
is_private=is_private,
|
||||
youtube_queued=youtube_queued,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
# Send the email with CC to admin
|
||||
@@ -126,6 +143,7 @@ class JobNotificationService:
|
||||
title=title,
|
||||
brand_code=brand_code,
|
||||
cc_admin=True,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
if success:
|
||||
@@ -171,10 +189,14 @@ class JobNotificationService:
|
||||
return False
|
||||
|
||||
try:
|
||||
# Get user locale for email
|
||||
user_locale = self._get_user_locale(user_email)
|
||||
|
||||
message_content = self.template_service.render_youtube_upload_complete(
|
||||
artist=artist,
|
||||
title=title,
|
||||
youtube_url=youtube_url,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
success = self.email_service.send_youtube_upload_complete(
|
||||
@@ -183,6 +205,7 @@ class JobNotificationService:
|
||||
artist=artist,
|
||||
title=title,
|
||||
brand_code=brand_code,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
if success:
|
||||
@@ -237,31 +260,37 @@ class JobNotificationService:
|
||||
return False
|
||||
|
||||
try:
|
||||
# Get user locale for email
|
||||
user_locale = self._get_user_locale(user_email)
|
||||
|
||||
# Render the appropriate template
|
||||
if action_type == "lyrics":
|
||||
review_url = self._build_review_url(job_id, audio_hash, review_token)
|
||||
review_url = self._build_review_url(job_id, audio_hash, review_token, locale=user_locale)
|
||||
message_content = self.template_service.render_action_needed_lyrics(
|
||||
name=user_name,
|
||||
artist=artist,
|
||||
title=title,
|
||||
review_url=review_url,
|
||||
locale=user_locale,
|
||||
)
|
||||
elif action_type == "instrumental":
|
||||
instrumental_url = self._build_instrumental_url(job_id, instrumental_token)
|
||||
instrumental_url = self._build_instrumental_url(job_id, instrumental_token, locale=user_locale)
|
||||
message_content = self.template_service.render_action_needed_instrumental(
|
||||
name=user_name,
|
||||
artist=artist,
|
||||
title=title,
|
||||
instrumental_url=instrumental_url,
|
||||
locale=user_locale,
|
||||
)
|
||||
elif action_type == "audio_edit":
|
||||
audio_edit_url = self._build_audio_edit_url(job_id)
|
||||
audio_edit_url = self._build_audio_edit_url(job_id, locale=user_locale)
|
||||
# Reuse the lyrics template but with the audio edit URL and different subject
|
||||
message_content = self.template_service.render_action_needed_lyrics(
|
||||
name=user_name,
|
||||
artist=artist,
|
||||
title=title,
|
||||
review_url=audio_edit_url,
|
||||
locale=user_locale,
|
||||
)
|
||||
else:
|
||||
logger.error(f"Unknown action type: {action_type}")
|
||||
@@ -274,6 +303,7 @@ class JobNotificationService:
|
||||
action_type=action_type,
|
||||
artist=artist,
|
||||
title=title,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
if success:
|
||||
|
||||
@@ -12,6 +12,7 @@ from pywebpush import webpush, WebPushException
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.models.user import User, PushSubscription
|
||||
from backend.i18n import t
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -239,15 +240,16 @@ class PushNotificationService:
|
||||
artist = job.get("artist", "Unknown Artist")
|
||||
title = job.get("title", "Unknown Title")
|
||||
tenant_id = job.get("tenant_id") or None
|
||||
locale = job.get("locale", "en")
|
||||
|
||||
if action_type == "lyrics":
|
||||
notif_title = "Review Lyrics"
|
||||
notif_body = f'"{title}" by {artist} needs lyrics review'
|
||||
notif_title = t(locale, "pushNotifications.reviewLyricsTitle")
|
||||
notif_body = t(locale, "pushNotifications.reviewLyricsBody", title=title, artist=artist)
|
||||
url = f"/app/jobs#/{job_id}/review"
|
||||
tag = f"lyrics-{job_id}"
|
||||
else: # instrumental
|
||||
notif_title = "Select Instrumental"
|
||||
notif_body = f'"{title}" by {artist} needs instrumental selection'
|
||||
notif_title = t(locale, "pushNotifications.selectInstrumentalTitle")
|
||||
notif_body = t(locale, "pushNotifications.selectInstrumentalBody", title=title, artist=artist)
|
||||
url = f"/app/jobs#/{job_id}/instrumental"
|
||||
tag = f"instrumental-{job_id}"
|
||||
|
||||
@@ -278,11 +280,12 @@ class PushNotificationService:
|
||||
artist = job.get("artist", "Unknown Artist")
|
||||
title = job.get("title", "Unknown Title")
|
||||
tenant_id = job.get("tenant_id") or None
|
||||
locale = job.get("locale", "en")
|
||||
|
||||
return await self.send_push(
|
||||
user_email=user_email,
|
||||
title="Video Ready!",
|
||||
body=f'Your karaoke video for "{title}" by {artist} is ready to download',
|
||||
title=t(locale, "pushNotifications.videoReadyTitle"),
|
||||
body=t(locale, "pushNotifications.videoReadyBody", title=title, artist=artist),
|
||||
url=f"/app/?job={job_id}",
|
||||
tag=f"complete-{job_id}",
|
||||
tenant_id=tenant_id,
|
||||
|
||||
@@ -14,6 +14,7 @@ import re
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -154,29 +155,48 @@ class TemplateService:
|
||||
logger.error(f"Failed to fetch template {blob_path}: {e}")
|
||||
return None
|
||||
|
||||
def get_job_completion_template(self) -> str:
|
||||
def get_job_completion_template(self, locale: str = "en") -> str:
|
||||
"""Get the job completion email template."""
|
||||
# Try locale-specific GCS template first, then default GCS, then localized default
|
||||
if locale != "en":
|
||||
template = self._fetch_template_from_gcs(f"{locale}/job-completion.txt")
|
||||
if template is not None:
|
||||
return template
|
||||
template = self._fetch_template_from_gcs("job-completion.txt")
|
||||
if template is None:
|
||||
logger.info("Using default job completion template")
|
||||
if template is not None:
|
||||
return template
|
||||
logger.info("Using default job completion template")
|
||||
if locale == "en":
|
||||
return DEFAULT_JOB_COMPLETION_TEMPLATE
|
||||
return template
|
||||
return self._build_localized_job_completion_template(locale)
|
||||
|
||||
def get_action_needed_lyrics_template(self) -> str:
|
||||
def get_action_needed_lyrics_template(self, locale: str = "en") -> str:
|
||||
"""Get the lyrics review reminder template."""
|
||||
if locale != "en":
|
||||
template = self._fetch_template_from_gcs(f"{locale}/action-needed-lyrics.txt")
|
||||
if template is not None:
|
||||
return template
|
||||
template = self._fetch_template_from_gcs("action-needed-lyrics.txt")
|
||||
if template is None:
|
||||
logger.info("Using default lyrics reminder template")
|
||||
if template is not None:
|
||||
return template
|
||||
logger.info("Using default lyrics reminder template")
|
||||
if locale == "en":
|
||||
return DEFAULT_ACTION_NEEDED_LYRICS_TEMPLATE
|
||||
return template
|
||||
return self._build_localized_action_lyrics_template(locale)
|
||||
|
||||
def get_action_needed_instrumental_template(self) -> str:
|
||||
def get_action_needed_instrumental_template(self, locale: str = "en") -> str:
|
||||
"""Get the instrumental selection reminder template."""
|
||||
if locale != "en":
|
||||
template = self._fetch_template_from_gcs(f"{locale}/action-needed-instrumental.txt")
|
||||
if template is not None:
|
||||
return template
|
||||
template = self._fetch_template_from_gcs("action-needed-instrumental.txt")
|
||||
if template is None:
|
||||
logger.info("Using default instrumental reminder template")
|
||||
if template is not None:
|
||||
return template
|
||||
logger.info("Using default instrumental reminder template")
|
||||
if locale == "en":
|
||||
return DEFAULT_ACTION_NEEDED_INSTRUMENTAL_TEMPLATE
|
||||
return template
|
||||
return self._build_localized_action_instrumental_template(locale)
|
||||
|
||||
def render_template(self, template: str, variables: Dict[str, Any]) -> str:
|
||||
"""
|
||||
@@ -215,6 +235,74 @@ class TemplateService:
|
||||
|
||||
return result.strip()
|
||||
|
||||
def _build_localized_job_completion_template(self, locale: str) -> str:
|
||||
"""Build a localized job completion template from translation keys."""
|
||||
ns = "emails.templates.jobCompletion"
|
||||
return f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.thanks")}
|
||||
|
||||
{t(locale, f"{ns}.youtubeLink")}
|
||||
{{youtube_url}}
|
||||
|
||||
{t(locale, f"{ns}.dropboxIntro")}
|
||||
{t(locale, f"{ns}.fileList")}
|
||||
|
||||
{{dropbox_url}}
|
||||
|
||||
{t(locale, f"{ns}.fixOffer")}
|
||||
|
||||
{t(locale, f"{ns}.feedbackRequest")}
|
||||
{{feedback_url}}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
|
||||
def _build_localized_action_lyrics_template(self, locale: str) -> str:
|
||||
"""Build a localized action-needed lyrics template."""
|
||||
ns = "emails.templates.actionLyrics"
|
||||
return f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.ready")}
|
||||
|
||||
{t(locale, f"{ns}.instructions")}
|
||||
|
||||
{t(locale, f"{ns}.reviewPrompt")}
|
||||
{{review_url}}
|
||||
|
||||
{t(locale, f"{ns}.duration")}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
|
||||
def _build_localized_action_instrumental_template(self, locale: str) -> str:
|
||||
"""Build a localized action-needed instrumental template."""
|
||||
ns = "emails.templates.actionInstrumental"
|
||||
return f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.almostDone")}
|
||||
|
||||
{t(locale, f"{ns}.instructions")}
|
||||
|
||||
{t(locale, f"{ns}.selectPrompt")}
|
||||
{{instrumental_url}}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
|
||||
def _build_localized_youtube_complete_template(self, locale: str) -> str:
|
||||
"""Build a localized YouTube upload complete template."""
|
||||
ns = "emails.templates.youtubeComplete"
|
||||
return f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.greatNews")}
|
||||
{{youtube_url}}
|
||||
|
||||
{t(locale, f"{ns}.delayNote")}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
|
||||
def render_job_completion(
|
||||
self,
|
||||
name: Optional[str] = None,
|
||||
@@ -226,6 +314,7 @@ class TemplateService:
|
||||
feedback_url: Optional[str] = None,
|
||||
is_private: bool = False,
|
||||
youtube_queued: bool = False,
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""
|
||||
Render the job completion email template.
|
||||
@@ -244,7 +333,7 @@ class TemplateService:
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self.get_job_completion_template()
|
||||
template = self.get_job_completion_template(locale)
|
||||
|
||||
# For private tracks, remove the YouTube section entirely
|
||||
if is_private:
|
||||
@@ -255,11 +344,18 @@ class TemplateService:
|
||||
)
|
||||
elif youtube_queued and not youtube_url:
|
||||
# Replace YouTube URL with pending message
|
||||
queued_msg = t(locale, "emails.templates.jobCompletion.youtubeQueued")
|
||||
youtube_link_text = t(locale, "emails.templates.jobCompletion.youtubeLink")
|
||||
template = template.replace(
|
||||
"Here's the link for the karaoke video published to YouTube:\n{youtube_url}",
|
||||
"Your YouTube upload is queued and will be processed automatically. "
|
||||
"You'll receive a follow-up email with the link shortly."
|
||||
f"{youtube_link_text}\n{{youtube_url}}",
|
||||
queued_msg
|
||||
)
|
||||
# Also handle the English default template pattern
|
||||
if "{youtube_url}" in template:
|
||||
template = template.replace(
|
||||
"Here's the link for the karaoke video published to YouTube:\n{youtube_url}",
|
||||
queued_msg
|
||||
)
|
||||
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
@@ -278,6 +374,7 @@ class TemplateService:
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
review_url: str = "",
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""
|
||||
Render the combined review reminder template.
|
||||
@@ -294,7 +391,7 @@ class TemplateService:
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self.get_action_needed_lyrics_template()
|
||||
template = self.get_action_needed_lyrics_template(locale)
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"artist": artist or "Unknown Artist",
|
||||
@@ -309,6 +406,7 @@ class TemplateService:
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
instrumental_url: str = "",
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""
|
||||
Render the instrumental selection reminder template.
|
||||
@@ -326,7 +424,7 @@ class TemplateService:
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self.get_action_needed_instrumental_template()
|
||||
template = self.get_action_needed_instrumental_template(locale)
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"artist": artist or "Unknown Artist",
|
||||
@@ -341,6 +439,7 @@ class TemplateService:
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""
|
||||
Render the YouTube upload complete follow-up email template.
|
||||
@@ -356,9 +455,16 @@ class TemplateService:
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
|
||||
if locale != "en":
|
||||
template = self._fetch_template_from_gcs(f"{locale}/youtube-upload-complete.txt")
|
||||
if template is not None:
|
||||
pass # Use locale-specific GCS template
|
||||
else:
|
||||
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
|
||||
else:
|
||||
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
|
||||
if template is None:
|
||||
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE
|
||||
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE if locale == "en" else self._build_localized_youtube_complete_template(locale)
|
||||
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
|
||||
@@ -282,7 +282,7 @@ class TestSubmitFeedbackEmailIntegration:
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# Verify email notification was called with matching args
|
||||
@@ -339,7 +339,7 @@ class TestSubmitFeedbackEmailIntegration:
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# User still gets credits even though email failed
|
||||
|
||||
@@ -319,3 +319,59 @@ class TestRenderVideoWorkerUsesCorrectedData:
|
||||
# Metadata and original_segments preserved
|
||||
assert original_data['metadata']['preserved'] is True
|
||||
assert original_data['original_segments'][0]['id'] == 1
|
||||
|
||||
|
||||
class TestCompleteReviewSkipsEmptyCorrections:
|
||||
"""Test that complete_review doesn't write corrections_updated.json when no corrections.
|
||||
|
||||
Bug scenario: Completing review via admin API without corrections payload writes
|
||||
an empty {} to corrections_updated.json. Downstream render workers then get
|
||||
KeyError: 'corrections' when processing it.
|
||||
"""
|
||||
|
||||
def test_no_corrections_key_skips_upload(self):
|
||||
"""When updated_data has only instrumental_selection, no corrections file is written."""
|
||||
# Simulate what the endpoint does with the corrections_to_save logic
|
||||
updated_data = {"instrumental_selection": "clean"}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# This is the guard we added
|
||||
should_write = corrections_to_save and "corrections" in corrections_to_save
|
||||
assert not should_write, "Should not write corrections_updated.json for empty payload"
|
||||
|
||||
def test_with_corrections_key_allows_upload(self):
|
||||
"""When updated_data has corrections, the file should be written."""
|
||||
updated_data = {
|
||||
"corrections": [{"id": 1, "type": "edit"}],
|
||||
"corrected_segments": [{"id": 1, "text": "fixed"}],
|
||||
"instrumental_selection": "with_backing",
|
||||
}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
should_write = corrections_to_save and "corrections" in corrections_to_save
|
||||
assert should_write, "Should write corrections_updated.json when corrections present"
|
||||
|
||||
def test_empty_dict_payload_skips_upload(self):
|
||||
"""When updated_data is effectively empty after removing instrumental_selection."""
|
||||
updated_data = {"instrumental_selection": "clean", "some_other_key": "value"}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# Has content but no "corrections" key
|
||||
should_write = corrections_to_save and "corrections" in corrections_to_save
|
||||
assert not should_write, "Should not write without corrections key"
|
||||
|
||||
def test_render_worker_handles_empty_corrections_gracefully(self):
|
||||
"""Document that render workers skip empty corrections_updated.json.
|
||||
|
||||
Both GCE and Cloud Run workers now check for 'corrections' key
|
||||
before passing to CorrectionOperations.update_correction_result_with_data().
|
||||
"""
|
||||
# Simulates what the workers do on download
|
||||
empty_updated_data = {}
|
||||
has_valid_corrections = empty_updated_data and "corrections" in empty_updated_data
|
||||
assert not has_valid_corrections, "Empty dict should not be treated as valid corrections"
|
||||
|
||||
# Dict with irrelevant keys
|
||||
bad_updated_data = {"some_key": "value"}
|
||||
has_valid_corrections = bad_updated_data and "corrections" in bad_updated_data
|
||||
assert not has_valid_corrections, "Dict without corrections key should not be valid"
|
||||
@@ -59,8 +59,8 @@ class TestSendReviewReminder:
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["html_content"]
|
||||
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["text_content"]
|
||||
assert "gen.nomadkaraoke.com/en/app/jobs#/abc123/review" in call_args.kwargs["html_content"]
|
||||
assert "gen.nomadkaraoke.com/en/app/jobs#/abc123/review" in call_args.kwargs["text_content"]
|
||||
|
||||
def test_content_includes_expiry_warning(self):
|
||||
"""Content should warn about 24h expiry."""
|
||||
@@ -153,4 +153,4 @@ class TestSendReviewExpired:
|
||||
credits_balance=2,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "gen.nomadkaraoke.com/app" in call_args.kwargs["html_content"]
|
||||
assert "gen.nomadkaraoke.com/en/app" in call_args.kwargs["html_content"]
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Tests for backend.i18n translation utility."""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from backend.i18n import t, get_locale_from_request, get_locale_prefix, SUPPORTED_LOCALES, DEFAULT_LOCALE, _load_translations
|
||||
|
||||
|
||||
class TestTranslationFunction:
|
||||
"""Tests for t() function."""
|
||||
|
||||
def test_returns_english_string(self):
|
||||
result = t("en", "jobs.notFound")
|
||||
assert result == "Job not found"
|
||||
|
||||
def test_dotted_key_path(self):
|
||||
result = t("en", "pushNotifications.reviewLyricsTitle")
|
||||
assert result == "Review Lyrics"
|
||||
|
||||
def test_interpolation(self):
|
||||
result = t("en", "jobs.notCompleted", status="downloading")
|
||||
assert result == "Only completed jobs can be edited. Current status: downloading"
|
||||
|
||||
def test_multiple_interpolation_vars(self):
|
||||
result = t("en", "jobs.durationMismatch", upload_duration="120", original_duration="180")
|
||||
assert "120s" in result
|
||||
assert "180s" in result
|
||||
|
||||
def test_spanish_returns_translated_string(self):
|
||||
result = t("es", "jobs.notFound")
|
||||
assert result == "Trabajo no encontrado"
|
||||
|
||||
def test_fallback_to_english_for_missing_key_in_other_locale(self):
|
||||
# Key that exists in en.json but not in es.json should fall back to English
|
||||
result = t("es", "nonexistent.key.path")
|
||||
assert result == "nonexistent.key.path" # Falls all the way to key itself
|
||||
|
||||
def test_returns_key_for_nonexistent_key(self):
|
||||
result = t("en", "nonexistent.key.path")
|
||||
assert result == "nonexistent.key.path"
|
||||
|
||||
def test_unsupported_locale_falls_back_to_english(self):
|
||||
result = t("fr", "jobs.notFound")
|
||||
assert result == "Job not found"
|
||||
|
||||
def test_empty_locale_falls_back_to_english(self):
|
||||
result = t("", "jobs.notFound")
|
||||
assert result == "Job not found"
|
||||
|
||||
def test_missing_interpolation_var_returns_template(self):
|
||||
# If kwargs are missing, return template string as-is
|
||||
result = t("en", "jobs.notCompleted")
|
||||
assert "{status}" in result
|
||||
|
||||
def test_all_supported_locales_load(self):
|
||||
for locale in SUPPORTED_LOCALES:
|
||||
translations = _load_translations(locale)
|
||||
assert isinstance(translations, dict)
|
||||
assert len(translations) > 0
|
||||
|
||||
|
||||
class TestGetLocaleFromRequest:
|
||||
"""Tests for get_locale_from_request()."""
|
||||
|
||||
def _make_request(self, accept_language: str = "") -> MagicMock:
|
||||
request = MagicMock()
|
||||
request.headers = {"accept-language": accept_language}
|
||||
return request
|
||||
|
||||
def test_simple_locale(self):
|
||||
request = self._make_request("de")
|
||||
assert get_locale_from_request(request) == "de"
|
||||
|
||||
def test_locale_with_region(self):
|
||||
request = self._make_request("es-MX")
|
||||
assert get_locale_from_request(request) == "es"
|
||||
|
||||
def test_quality_weighted_list(self):
|
||||
request = self._make_request("fr;q=0.9,de;q=0.8,en;q=0.7")
|
||||
# fr is not supported, de is next
|
||||
assert get_locale_from_request(request) == "de"
|
||||
|
||||
def test_complex_accept_language(self):
|
||||
request = self._make_request("en-US,en;q=0.9,de;q=0.8")
|
||||
assert get_locale_from_request(request) == "en"
|
||||
|
||||
def test_unsupported_locale_returns_default(self):
|
||||
request = self._make_request("ja")
|
||||
assert get_locale_from_request(request) == DEFAULT_LOCALE
|
||||
|
||||
def test_empty_header_returns_default(self):
|
||||
request = self._make_request("")
|
||||
assert get_locale_from_request(request) == DEFAULT_LOCALE
|
||||
|
||||
def test_missing_header_returns_default(self):
|
||||
request = MagicMock()
|
||||
request.headers = {}
|
||||
assert get_locale_from_request(request) == DEFAULT_LOCALE
|
||||
|
||||
|
||||
class TestGetLocalePrefix:
|
||||
"""Tests for get_locale_prefix()."""
|
||||
|
||||
def test_english(self):
|
||||
assert get_locale_prefix("en") == "/en"
|
||||
|
||||
def test_spanish(self):
|
||||
assert get_locale_prefix("es") == "/es"
|
||||
|
||||
def test_german(self):
|
||||
assert get_locale_prefix("de") == "/de"
|
||||
|
||||
def test_unsupported_returns_english(self):
|
||||
assert get_locale_prefix("fr") == "/en"
|
||||
|
||||
def test_empty_returns_english(self):
|
||||
assert get_locale_prefix("") == "/en"
|
||||
@@ -22,7 +22,7 @@ class TestURLBuilding:
|
||||
|
||||
url = service._build_review_url("job-123")
|
||||
|
||||
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
|
||||
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
|
||||
|
||||
def test_build_review_url_ignores_legacy_params(self):
|
||||
"""Test review URL ignores legacy audio_hash and review_token params."""
|
||||
@@ -33,7 +33,7 @@ class TestURLBuilding:
|
||||
url = service._build_review_url("job-123", audio_hash="abc123", review_token="token456")
|
||||
|
||||
# URL should be the simple consolidated route
|
||||
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
|
||||
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
|
||||
# No query params
|
||||
assert "?" not in url
|
||||
|
||||
@@ -45,7 +45,7 @@ class TestURLBuilding:
|
||||
# Note: job IDs with slashes would be unusual in real usage
|
||||
url = service._build_review_url("abc-def-123")
|
||||
|
||||
assert url == "https://gen.nomadkaraoke.com/app/jobs#/abc-def-123/review"
|
||||
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/abc-def-123/review"
|
||||
|
||||
def test_build_instrumental_url_basic(self):
|
||||
"""Test basic instrumental URL building."""
|
||||
@@ -54,7 +54,7 @@ class TestURLBuilding:
|
||||
|
||||
url = service._build_instrumental_url("job-123")
|
||||
|
||||
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
|
||||
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/instrumental"
|
||||
|
||||
def test_build_instrumental_url_ignores_legacy_params(self):
|
||||
"""Test instrumental URL ignores legacy instrumental_token param."""
|
||||
@@ -65,7 +65,7 @@ class TestURLBuilding:
|
||||
url = service._build_instrumental_url("job-123", instrumental_token="inst-token")
|
||||
|
||||
# URL should be the simple consolidated route
|
||||
assert url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
|
||||
assert url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/instrumental"
|
||||
# No query params
|
||||
assert "?" not in url
|
||||
|
||||
@@ -312,7 +312,7 @@ class TestActionReminderEmail:
|
||||
# Verify the review URL was passed to template
|
||||
call_kwargs = service.template_service.render_action_needed_lyrics.call_args.kwargs
|
||||
review_url = call_kwargs.get('review_url')
|
||||
assert review_url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/review"
|
||||
assert review_url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/review"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_instrumental_reminder_includes_url(self):
|
||||
@@ -334,7 +334,7 @@ class TestActionReminderEmail:
|
||||
# Verify the instrumental URL was passed to template
|
||||
call_kwargs = service.template_service.render_action_needed_instrumental.call_args.kwargs
|
||||
instrumental_url = call_kwargs.get('instrumental_url')
|
||||
assert instrumental_url == "https://gen.nomadkaraoke.com/app/jobs#/job-123/instrumental"
|
||||
assert instrumental_url == "https://gen.nomadkaraoke.com/en/app/jobs#/job-123/instrumental"
|
||||
|
||||
|
||||
class TestGetCompletionMessage:
|
||||
|
||||
@@ -90,12 +90,16 @@ class TestExceptionHandlers:
|
||||
credits_required=1,
|
||||
)
|
||||
|
||||
response = await insufficient_credits_exception_handler(request=None, exc=exc)
|
||||
from unittest.mock import MagicMock
|
||||
mock_request = MagicMock()
|
||||
mock_request.headers = {"accept-language": "en"}
|
||||
|
||||
response = await insufficient_credits_exception_handler(request=mock_request, exc=exc)
|
||||
|
||||
assert response.status_code == 402
|
||||
import json
|
||||
body = json.loads(response.body)
|
||||
assert body["detail"] == "No credits remaining"
|
||||
assert body["detail"] == "Insufficient credits for this operation"
|
||||
assert body["credits_available"] == 0
|
||||
assert body["credits_required"] == 1
|
||||
assert body["buy_url"] == "/#pricing"
|
||||
|
||||
@@ -120,12 +120,12 @@ class TestProcessStaleReviews:
|
||||
mock_job_manager.cancel_job.assert_called_once_with(
|
||||
"job-123", reason="Review not completed within 48 hours"
|
||||
)
|
||||
mock_email_service.send_review_expired.assert_called_once_with(
|
||||
to_email="user@test.com",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
credits_balance=2,
|
||||
)
|
||||
call_kwargs = mock_email_service.send_review_expired.call_args.kwargs
|
||||
assert call_kwargs["to_email"] == "user@test.com"
|
||||
assert call_kwargs["artist"] == "Test Artist"
|
||||
assert call_kwargs["title"] == "Test Song"
|
||||
assert call_kwargs["credits_balance"] == 2
|
||||
assert "locale" in call_kwargs # locale now passed from user profile
|
||||
|
||||
async def test_expires_job_over_48h_with_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
|
||||
"""Should expire job >48h even if reminder was already sent (no duplicate reminder)."""
|
||||
@@ -153,12 +153,12 @@ class TestProcessStaleReviews:
|
||||
|
||||
assert result["reminders_sent"] == 1
|
||||
assert result["jobs_expired"] == 0
|
||||
mock_email_service.send_review_reminder.assert_called_once_with(
|
||||
to_email="user@test.com",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
job_id="job-123",
|
||||
)
|
||||
call_kwargs = mock_email_service.send_review_reminder.call_args.kwargs
|
||||
assert call_kwargs["to_email"] == "user@test.com"
|
||||
assert call_kwargs["artist"] == "Test Artist"
|
||||
assert call_kwargs["title"] == "Test Song"
|
||||
assert call_kwargs["job_id"] == "job-123"
|
||||
assert "locale" in call_kwargs
|
||||
# Should update state_data with expiry_reminder_sent flag
|
||||
mock_firestore.update_job.assert_called_once()
|
||||
call_args = mock_firestore.update_job.call_args
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Tests for the /api/health/system-status endpoint."""
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_encoding_status():
|
||||
return {
|
||||
"configured": True,
|
||||
"enabled": True,
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"active_jobs": 0,
|
||||
"queue_length": 0,
|
||||
"wheel_version": "0.155.3",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_flacfetch_status():
|
||||
return {
|
||||
"configured": True,
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": "0.19.1",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_separator_status():
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": "0.4.3",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_encoding_worker_config():
|
||||
"""Mock EncodingWorkerConfig dataclass."""
|
||||
config = MagicMock()
|
||||
config.primary_vm = "encoding-worker-b"
|
||||
config.primary_ip = "34.10.189.118"
|
||||
config.primary_version = "0.155.3"
|
||||
config.primary_deployed_at = "2026-03-31T18:10:00Z"
|
||||
config.secondary_vm = "encoding-worker-a"
|
||||
config.secondary_ip = "34.57.78.246"
|
||||
config.secondary_version = "0.155.2"
|
||||
config.secondary_deployed_at = "2026-03-29T14:00:00Z"
|
||||
config.last_swap_at = "2026-03-31T18:10:00Z"
|
||||
config.deploy_in_progress = False
|
||||
config.deploy_in_progress_since = None
|
||||
config.last_activity_at = None
|
||||
return config
|
||||
|
||||
|
||||
class TestSystemStatusPublic:
|
||||
"""Tests for unauthenticated /api/health/system-status."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_all_services(
|
||||
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status
|
||||
):
|
||||
from backend.api.routes.health import system_status
|
||||
|
||||
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
|
||||
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
|
||||
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
|
||||
patch("backend.api.routes.health.VERSION", "0.155.3"), \
|
||||
patch("backend.api.routes.health.COMMIT_SHA", "8e2a949a"), \
|
||||
patch("backend.api.routes.health.PR_NUMBER", "644"), \
|
||||
patch("backend.api.routes.health.PR_TITLE", "fix: blue-green deploy"), \
|
||||
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
|
||||
|
||||
result = await system_status(auth=None)
|
||||
|
||||
assert "services" in result
|
||||
services = result["services"]
|
||||
|
||||
# All 5 services present
|
||||
assert "frontend" in services
|
||||
assert "backend" in services
|
||||
assert "encoder" in services
|
||||
assert "flacfetch" in services
|
||||
assert "separator" in services
|
||||
|
||||
# Backend has build metadata
|
||||
backend_svc = services["backend"]
|
||||
assert backend_svc["version"] == "0.155.3"
|
||||
assert backend_svc["commit_sha"] == "8e2a949a"
|
||||
assert backend_svc["pr_number"] == "644"
|
||||
|
||||
# Encoder has status
|
||||
assert services["encoder"]["status"] == "ok"
|
||||
assert services["encoder"]["version"] == "0.155.3"
|
||||
|
||||
# No admin_details without auth
|
||||
assert "admin_details" not in services["encoder"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_offline_service(self, mock_flacfetch_status, mock_separator_status):
|
||||
from backend.api.routes.health import system_status
|
||||
|
||||
offline_encoding = {
|
||||
"configured": True,
|
||||
"enabled": True,
|
||||
"available": False,
|
||||
"error": "Connection refused",
|
||||
}
|
||||
|
||||
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=offline_encoding), \
|
||||
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
|
||||
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
|
||||
patch("backend.api.routes.health.VERSION", "0.155.3"), \
|
||||
patch("backend.api.routes.health.COMMIT_SHA", ""), \
|
||||
patch("backend.api.routes.health.PR_NUMBER", ""), \
|
||||
patch("backend.api.routes.health.PR_TITLE", ""), \
|
||||
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
|
||||
|
||||
result = await system_status(auth=None)
|
||||
|
||||
assert result["services"]["encoder"]["status"] == "offline"
|
||||
|
||||
|
||||
class TestSystemStatusAdmin:
|
||||
"""Tests for admin-authenticated /api/health/system-status."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_gets_bluegreen_details(
|
||||
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status, mock_encoding_worker_config
|
||||
):
|
||||
from backend.api.routes.health import system_status
|
||||
from backend.services.auth_service import UserType
|
||||
|
||||
mock_auth = ("token123", UserType.ADMIN, -1)
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_config.return_value = mock_encoding_worker_config
|
||||
|
||||
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
|
||||
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
|
||||
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
|
||||
patch("backend.api.routes.health.VERSION", "0.155.3"), \
|
||||
patch("backend.api.routes.health.COMMIT_SHA", ""), \
|
||||
patch("backend.api.routes.health.PR_NUMBER", ""), \
|
||||
patch("backend.api.routes.health.PR_TITLE", ""), \
|
||||
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"), \
|
||||
patch("backend.api.routes.health._get_encoding_worker_manager", return_value=mock_manager):
|
||||
|
||||
result = await system_status(auth=mock_auth)
|
||||
|
||||
encoder = result["services"]["encoder"]
|
||||
assert "admin_details" in encoder
|
||||
admin = encoder["admin_details"]
|
||||
assert admin["primary_vm"] == "encoding-worker-b"
|
||||
assert admin["secondary_vm"] == "encoding-worker-a"
|
||||
assert admin["last_swap_at"] == "2026-03-31T18:10:00Z"
|
||||
assert admin["deploy_in_progress"] is False
|
||||
@@ -56,7 +56,7 @@ class TestSendMagicLinkTenantParams:
|
||||
assert "Nomad Karaoke" in html_content
|
||||
assert "Nomad Karaoke" in text_content
|
||||
# Default URL should be used
|
||||
assert f"{email_service.frontend_url}/auth/verify" in html_content
|
||||
assert f"{email_service.frontend_url}/en/auth/verify" in html_content
|
||||
|
||||
def test_tenant_url_used_in_magic_link(self, email_service):
|
||||
"""When tenant_frontend_url is provided, magic link points to tenant domain."""
|
||||
@@ -70,8 +70,8 @@ class TestSendMagicLinkTenantParams:
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
|
||||
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in html_content
|
||||
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in text_content
|
||||
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in html_content
|
||||
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in text_content
|
||||
# Should NOT contain default URL
|
||||
assert "gen.nomadkaraoke.com" not in html_content
|
||||
|
||||
@@ -124,7 +124,7 @@ class TestSendMagicLinkTenantParams:
|
||||
html_content = call_args[0][2]
|
||||
|
||||
assert subject == "Sign in to Vocal Star"
|
||||
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=token123" in html_content
|
||||
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=token123" in html_content
|
||||
# Check sender email override was passed through
|
||||
assert call_args[1]["from_email_override"] == "vocalstar@nomadkaraoke.com"
|
||||
|
||||
|
||||
@@ -621,6 +621,111 @@ class TestPackagingValidation:
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
|
||||
|
||||
class TestPackagingTrailingPeriodRegression:
|
||||
"""Regression test for job 4117228f: title ending with period caused TXT failure.
|
||||
|
||||
Root cause: The orchestrator's sanitize_filename() strips trailing periods,
|
||||
but the CDG generator's internal _sanitize_filename() did not, causing a
|
||||
filename mismatch between the MP3 inside the CDG ZIP and what TXT expected.
|
||||
Fix: Pass sanitized artist/title to CDG generator and use returned MP3 path.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cdg_packaging_uses_sanitized_artist_title(self):
|
||||
"""Test that CDG packaging passes sanitized (not raw) artist/title."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
lrc_file = os.path.join(temp_dir, "test.lrc")
|
||||
audio_file = os.path.join(temp_dir, "test.flac")
|
||||
|
||||
with open(lrc_file, "w") as f:
|
||||
f.write("[00:00.00]Test lyrics")
|
||||
with open(audio_file, "w") as f:
|
||||
f.write("dummy audio")
|
||||
|
||||
# Title ends with period - this triggered the bug
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="KARAOKE",
|
||||
title="Song Title.", # Trailing period
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path=audio_file,
|
||||
lrc_file_path=lrc_file,
|
||||
output_dir=temp_dir,
|
||||
enable_cdg=True,
|
||||
cdg_styles={"background_color": "black"},
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with patch.object(orchestrator, "_get_packaging_service") as mock_get:
|
||||
mock_service = MagicMock()
|
||||
mock_service.create_cdg_package.return_value = (
|
||||
f"{temp_dir}/cdg.zip",
|
||||
f"{temp_dir}/test.mp3",
|
||||
f"{temp_dir}/test.cdg",
|
||||
)
|
||||
mock_get.return_value = mock_service
|
||||
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
call_kwargs = mock_service.create_cdg_package.call_args[1]
|
||||
# Artist/title should be sanitized (trailing period stripped)
|
||||
assert call_kwargs["artist"] == "KARAOKE"
|
||||
assert call_kwargs["title"] == "Song Title" # No trailing period
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_txt_uses_mp3_path_from_cdg_generation(self):
|
||||
"""Test that TXT generation uses the actual MP3 path returned by CDG, not a constructed one."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
lrc_file = os.path.join(temp_dir, "test.lrc")
|
||||
audio_file = os.path.join(temp_dir, "test.flac")
|
||||
# Create a real MP3 file at the path CDG would return
|
||||
mp3_from_cdg = os.path.join(temp_dir, "actual_cdg_output.mp3")
|
||||
|
||||
with open(lrc_file, "w") as f:
|
||||
f.write("[00:00.00]Test lyrics")
|
||||
with open(audio_file, "w") as f:
|
||||
f.write("dummy audio")
|
||||
with open(mp3_from_cdg, "w") as f:
|
||||
f.write("dummy mp3")
|
||||
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="KARAOKE",
|
||||
title="Song Title.", # Trailing period
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path=audio_file,
|
||||
lrc_file_path=lrc_file,
|
||||
output_dir=temp_dir,
|
||||
enable_cdg=True,
|
||||
enable_txt=True,
|
||||
cdg_styles={"background_color": "black"},
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with patch.object(orchestrator, "_get_packaging_service") as mock_get:
|
||||
mock_service = MagicMock()
|
||||
# CDG returns a path that differs from constructed path
|
||||
mock_service.create_cdg_package.return_value = (
|
||||
f"{temp_dir}/cdg.zip",
|
||||
mp3_from_cdg, # Actual MP3 path from CDG
|
||||
f"{temp_dir}/test.cdg",
|
||||
)
|
||||
mock_service.create_txt_package.return_value = (
|
||||
f"{temp_dir}/txt.zip",
|
||||
f"{temp_dir}/test.txt",
|
||||
)
|
||||
mock_get.return_value = mock_service
|
||||
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
# TXT should have been called with the actual CDG MP3 path
|
||||
mock_service.create_txt_package.assert_called_once()
|
||||
txt_call_kwargs = mock_service.create_txt_package.call_args[1]
|
||||
assert txt_call_kwargs["mp3_file"] == mp3_from_cdg
|
||||
|
||||
|
||||
class TestVideoWorkerOrchestratorEncoding:
|
||||
"""Test encoding stage."""
|
||||
|
||||
@@ -1256,6 +1361,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
job.gdrive_folder_id = None
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
job.file_urls = {'screens': {'title_png': 'jobs/test-123/screens/title.png', 'end_png': 'jobs/test-123/screens/end.png'}}
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
@@ -1269,7 +1375,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
assert config.title == "Test Title"
|
||||
assert config.enable_cdg is True
|
||||
assert config.enable_youtube_upload is True
|
||||
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).mov"
|
||||
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).png"
|
||||
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental Clean).flac"
|
||||
|
||||
def test_create_config_from_job_with_existing_instrumental(self):
|
||||
@@ -1290,6 +1396,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
job.gdrive_folder_id = None
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = "gs://bucket/instrumental.mp3"
|
||||
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
@@ -1329,6 +1436,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
job.gdrive_folder_id = None
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
{
|
||||
"auth": {
|
||||
"unknownService": "Unbekannter Dienst: {service}",
|
||||
"invalidCredentials": "Die folgenden Dienste müssen neu autorisiert werden: {services}",
|
||||
"validCredentials": "Alle angeforderten Anmeldeinformationen sind gültig",
|
||||
"youtubeAuthInstructions": "Besuche {verification_url} und gib den Code ein: {user_code}",
|
||||
"youtubeAuthStartFailed": "Fehler beim Starten der YouTube-Geräteauthentifizierung: {error}",
|
||||
"gdriveLinkInstructions": "Besuche {verification_url} und gib den Code ein: {user_code}",
|
||||
"gdriveAuthStartFailed": "Fehler beim Starten der Google Drive-Geräteauthentifizierung: {error}",
|
||||
"discordAlertNotConfigured": "Discord-Alert-Webhook nicht konfiguriert"
|
||||
},
|
||||
"jobs": {
|
||||
"created": "Auftrag erfolgreich erstellt. Verarbeitung gestartet.",
|
||||
"authError": "Authentifizierungsfehler: Keine Benutzeridentität verfügbar",
|
||||
"noDefaultTheme": "Kein Standard-Theme konfiguriert. Bitte wende dich an den Support oder gib eine theme_id an.",
|
||||
"notFound": "Auftrag nicht gefunden",
|
||||
"noPermissionAccess": "Du hast keine Berechtigung, auf diesen Auftrag zuzugreifen",
|
||||
"noPermissionEdit": "Du hast keine Berechtigung, diesen Auftrag zu bearbeiten",
|
||||
"noPermissionDelete": "Du hast keine Berechtigung, diesen Auftrag zu löschen",
|
||||
"noPermissionModify": "Du hast keine Berechtigung, diesen Auftrag zu ändern",
|
||||
"notCompleted": "Nur abgeschlossene Aufträge können bearbeitet werden. Aktueller Status: {status}",
|
||||
"alreadyBeingEdited": "Dieser Auftrag wird bereits bearbeitet (Ausgaben wurden bereits gelöscht)",
|
||||
"cleanupFailed": "Bereinigung für {services} fehlgeschlagen. Auftrag nicht geändert. Bitte versuche es erneut oder kontaktiere den Support.",
|
||||
"reopened": "Track zur Bearbeitung wieder geöffnet. Vorherige Ausgaben wurden entfernt.",
|
||||
"invalidDatetimeFormat": "Ungültiges {field}-Format: {value}",
|
||||
"listError": "Fehler beim Auflisten der Aufträge: {error}",
|
||||
"deleteError": "Fehler beim Löschen des Auftrags {job_id}: {error}",
|
||||
"deletionPreview": "Füge &confirm=true hinzu, um die Löschung auszuführen",
|
||||
"deletionRequiresFilters": "Mindestens ein Filter (environment, client_id, status, created_before) ist erforderlich",
|
||||
"bulkDeleteError": "Fehler beim massenhaften Löschen von Aufträgen: {error}",
|
||||
"reviewNotReady": "Auftrag noch nicht bereit für die Überprüfung (aktueller Status: {status})",
|
||||
"correctionsUnavailable": "Korrekturdaten nicht verfügbar",
|
||||
"audioUnavailable": "Audio für die Überprüfung nicht verfügbar",
|
||||
"reviewCannotStart": "Überprüfung kann nicht gestartet werden",
|
||||
"jobNotInReviewState": "Auftrag befindet sich nicht im Überprüfungsstatus (aktueller Status: {status})",
|
||||
"correctionsProcessing": "Korrekturen gespeichert. Rufe /complete-review auf, wenn du fertig bist.",
|
||||
"editLogSaveFailed": "Fehler beim Speichern des Bearbeitungsprotokolls für Auftrag {job_id}: {error}",
|
||||
"stemsMissing": "Dem Auftrag fehlen erforderliche Stems (instrumental_clean und/oder backing_vocals)",
|
||||
"customInstrumentalFailed": "Fehler beim Erstellen des benutzerdefinierten Instrumentals für Auftrag {job_id}: {error}",
|
||||
"audioProcessingFailed": "Fehler beim Verarbeiten der Audiodatei: {error}",
|
||||
"durationMismatch": "Dauer stimmt nicht überein: Hochgeladene Datei ist {upload_duration}s lang, aber das Original-Audio ist {original_duration}s lang. Das Instrumental muss genau {original_duration}s (±0.5s) lang sein.",
|
||||
"reviewNotInState": "Auftrag befindet sich nicht im Überprüfungsstatus (aktueller Status: {status})",
|
||||
"noLyricsDetected": "Überprüfung kann nicht abgeschlossen werden: Es wurde kein Text im Audio erkannt. Dies kann passieren, wenn das Eingabe-Audio keinen Gesang enthält (z. B. ein Karaoke-Track oder Instrumental). Du kannst zurückgehen und den Text manuell mit 'Alle ersetzen' einfügen oder diesen Auftrag abbrechen und es mit einer Audiodatei versuchen, die Gesang enthält.",
|
||||
"reviewCompleteStartRendering": "Überprüfung abgeschlossen. Rendern des Videos gestartet.",
|
||||
"reviewCompleteError": "Fehler beim Abschließen der Überprüfung für Auftrag {job_id}: {error}",
|
||||
"instrumentalSelectionRequired": "instrumental_selection ist erforderlich. Muss 'clean' oder 'with_backing' sein.",
|
||||
"invalidInstrumentalSelection": "Ungültige instrumental_selection. Muss eines der folgenden sein: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental ausgewählt. Video-Generierung gestartet.",
|
||||
"instrumentalSelectionError": "Fehler bei der Auswahl des Instrumentals für Auftrag {job_id}: {error}",
|
||||
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Auftrag nicht gefunden",
|
||||
"reviewNotReady": "Auftrag noch nicht bereit für die Überprüfung (aktueller Status: {status})",
|
||||
"correctionsNotFound": "Korrekturdaten nicht gefunden. Die Textverarbeitung ist möglicherweise noch nicht abgeschlossen.",
|
||||
"correctionsLoadFailed": "Fehler beim Laden der Korrekturen: {error}",
|
||||
"audioNotFound": "Audiodatei nicht gefunden",
|
||||
"audioServeError": "Fehler beim Bereitstellen von Audio: {error}",
|
||||
"instrumentalSelectionRequired": "instrumental_selection ist erforderlich. Muss 'clean' oder 'with_backing' sein.",
|
||||
"invalidInstrumentalSelection": "Ungültige instrumental_selection. Muss eines der folgenden sein: {valid_selections}",
|
||||
"reviewCompletedError": "Fehler beim Abschließen der Überprüfung: {error}",
|
||||
"handlersUpdateNotImplemented": "Handler-Updates noch nicht implementiert",
|
||||
"lyricsAddError": "Fehler beim Hinzufügen des Textes: {error}",
|
||||
"lyricsAddInvalidRequest": "Ungültige Anfrage zum Hinzufügen von Text: {error}",
|
||||
"lyricsSearchError": "Fehler bei der Textsuche: {error}",
|
||||
"lyricsSearchInvalidRequest": "Ungültige Anfrage zur Textsuche: {error}",
|
||||
"lyricsSearchNoResults": "Kein passender Text bei keinem Anbieter gefunden",
|
||||
"previewVideoGenerationError": "Fehler beim Generieren des Vorschau-Videos: {error}",
|
||||
"previewVideoNotFound": "Vorschau-Video nicht gefunden",
|
||||
"previewVideoStreamError": "Fehler beim Streamen des Vorschau-Videos: {error}",
|
||||
"annotationSaveError": "Fehler beim Speichern der Anmerkungen: {error}",
|
||||
"waveformGenerationError": "Fehler beim Generieren der Wellenform-Daten: {error}",
|
||||
"waveformNoAudio": "Kein Audio für Wellenform verfügbar",
|
||||
"sessionSaveError": "Korrekturdaten sind erforderlich"
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Audiosuche ist für diesen Mandanten nicht aktiviert",
|
||||
"disabled": "Audiosuche ist nicht verfügbar",
|
||||
"downloadError": "Download für Auftrag {job_id} fehlgeschlagen: {error}",
|
||||
"jobNotFound": "Auftrag {job_id} nicht gefunden",
|
||||
"noSearchResults": "Keine Suchergebnisse verfügbar",
|
||||
"invalidSelectionIndex": "Ungültiger Auswahlindex {selection_index}. Gültiger Bereich: 0-{max}",
|
||||
"selectionError": "Fehler bei der Audioauswahl für Auftrag {job_id}: {error}",
|
||||
"youtubeDownloadError": "YouTube-Download fehlgeschlagen: {error}",
|
||||
"torrentDownloadError": "Download von {source} ohne Remote-flacfetch-Dienst nicht möglich. Konfiguriere FLACFETCH_API_URL.",
|
||||
"remoteDownloadNoSearchId": "Keine source_id oder remote_search_id für {source}-Download verfügbar",
|
||||
"remoteDownloadCompleteNoPath": "Remote-Download abgeschlossen, aber kein Dateipfad zurückgegeben",
|
||||
"spotifyDownloadError": "Download von Spotify ohne Remote-flacfetch-Dienst nicht möglich. Konfiguriere FLACFETCH_API_URL.",
|
||||
"genericDownloadError": "Unbekannter Quellentyp: {source}, versuche generischen Download",
|
||||
"jobNotFoundDuringDownload": "Auftrag {job_id} während des Hintergrund-Downloads nicht gefunden",
|
||||
"selectAudioError": "Fehler bei der Audioauswahl für Auftrag {job_id}: {error}",
|
||||
"searchAudioError": "Fehler bei der Audiosuche: {error}",
|
||||
"searchCreatedSuccessfully": "Auftrag erstellt. Suche nach Audio...",
|
||||
"autoDownloadStarted": "Bestes Ergebnis automatisch ausgewählt. Download startet..."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
"magicLinkSent": "Wenn diese E-Mail-Adresse registriert ist, erhältst du in Kürze einen Anmeldelink.",
|
||||
"emailServiceNotConfigured": "E-Mail-Dienst ist nicht verfügbar. Bitte kontaktiere den Support.",
|
||||
"emailDomainNotAllowed": "E-Mail-Domain für diesen Mandanten nicht zulässig",
|
||||
"invalidToken": "Ungültiges Token",
|
||||
"verifyError": "Verifizierung fehlgeschlagen: {message}",
|
||||
"magicLinkSuccess": "Erfolgreich angemeldet",
|
||||
"logoutSuccess": "Erfolgreich abgemeldet",
|
||||
"userNotFound": "Benutzer nicht gefunden",
|
||||
"creditPackagesError": "Fehler beim Laden der Guthaben-Pakete: {error}",
|
||||
"stripeSendError": "Fehler beim Senden des Stripe-Checkout-Links: {error}",
|
||||
"stripeWebhookProcessingError": "Fehler bei der Verarbeitung des Stripe-Webhooks: {error}",
|
||||
"feedbackSaveError": "Fehler beim Speichern des Feedbacks: {error}",
|
||||
"feedbackNotEligible": "Benutzer ist nicht für Feedback berechtigt"
|
||||
},
|
||||
"fileUpload": {
|
||||
"invalidTheme": "Theme nicht gefunden: {theme_id}. Verwende GET /api/themes, um verfügbare Themes aufzulisten.",
|
||||
"uploadSuccess": "Datei erfolgreich hochgeladen. Verarbeitung gestartet.",
|
||||
"uploadError": "Fehler beim Hochladen der Datei: {error}",
|
||||
"urlDownloadError": "Fehler beim Herunterladen von der URL: {error}",
|
||||
"invalidContentType": "Ungültiger Inhaltstyp: {content_type}",
|
||||
"fileSizeError": "Datei ist zu groß: {size}. Maximum: {max_size}",
|
||||
"invalidFileType": "Ungültiger Dateityp: {file_type}",
|
||||
"multipleAudioFilesNotAllowed": "Es kann nur eine Audiodatei hochgeladen werden",
|
||||
"noAudioFileProvided": "Keine Audiodatei bereitgestellt",
|
||||
"urlCreationSuccess": "Auftrag erstellt. Upload-URLs generiert.",
|
||||
"urlCreationError": "Fehler beim Erstellen des Auftrags mit Upload-URLs: {error}",
|
||||
"uploadsCompleteSuccess": "Uploads abgeschlossen. Verarbeitung gestartet.",
|
||||
"uploadsCompleteError": "Fehler beim Abschließen der Uploads: {error}",
|
||||
"noUploadedFiles": "Keine hochgeladenen Dateien angegeben",
|
||||
"styleUploadUrlsSuccess": "Style-Upload-URLs generiert.",
|
||||
"styleUploadsCompleteSuccess": "Style-Dateien aktualisiert. Verarbeitung neu gestartet.",
|
||||
"styleUploadsCompleteError": "Fehler beim Abschließen der Style-Uploads: {error}"
|
||||
},
|
||||
"catalog": {
|
||||
"rateLimitExceeded": "Ratenlimit überschritten. Maximal {max_requests} Kataloganfragen pro Minute.",
|
||||
"catalogSearchError": "Fehler bei der Katalogsuche: {error}",
|
||||
"communityCheckError": "Fehler beim Überprüfen der Community-Versionen: {error}"
|
||||
},
|
||||
"themes": {
|
||||
"themesLoadError": "Fehler beim Laden der Themes",
|
||||
"themeNotFound": "Theme nicht gefunden: {theme_id}",
|
||||
"themeLoadError": "Fehler beim Laden des Themes",
|
||||
"previewNotAvailable": "Keine Vorschau für Theme verfügbar: {theme_id}",
|
||||
"previewLoadError": "Fehler beim Laden der Theme-Vorschau",
|
||||
"youtubeDescriptionNotFound": "Theme nicht gefunden: {theme_id}",
|
||||
"youtubeDescriptionLoadError": "Fehler beim Laden der YouTube-Beschreibung"
|
||||
},
|
||||
"tenant": {
|
||||
"assetNotFound": "Asset nicht gefunden"
|
||||
},
|
||||
"push": {
|
||||
"disabled": "Push-Benachrichtigungen sind nicht aktiviert",
|
||||
"userEmailNotAvailable": "Benutzer-E-Mail nicht verfügbar",
|
||||
"missingEncryptionKeys": "Erforderliche Schlüssel fehlen (p256dh, auth)",
|
||||
"subscriptionSaveFailed": "Fehler beim Speichern des Abonnements",
|
||||
"subscriptionRegistered": "Push-Abonnement erfolgreich registriert",
|
||||
"subscriptionNotFound": "Abonnement entfernt (oder wurde nicht gefunden)",
|
||||
"subscriptionRemoved": "Push-Abonnement erfolgreich entfernt",
|
||||
"testNotificationSent": "Testbenachrichtigung an {sent_count} Gerät(e) gesendet"
|
||||
},
|
||||
"pushNotifications": {
|
||||
"reviewLyricsTitle": "Textüberprüfung",
|
||||
"reviewLyricsBody": "\"{title}\" von {artist} benötigt eine Textüberprüfung",
|
||||
"selectInstrumentalTitle": "Instrumental auswählen",
|
||||
"selectInstrumentalBody": "\"{title}\" von {artist} benötigt eine Instrumentalauswahl",
|
||||
"videoReadyTitle": "Video fertig!",
|
||||
"videoReadyBody": "Dein Karaoke-Video für \"{title}\" von {artist} ist zum Download bereit"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Ungültiges Domain-Format",
|
||||
"domainAddedToBl": "Domain '{domain}' zur Blockliste für Wegwerf-Domains hinzugefügt",
|
||||
"domainNotFoundInBl": "Domain nicht in der Blockliste gefunden",
|
||||
"domainRemovedFromBl": "Domain '{domain}' aus der Blockliste für Wegwerf-Domains entfernt",
|
||||
"domainAddedToAllowlist": "Domain '{domain}' zur Allowlist hinzugefügt",
|
||||
"domainNotFoundInAllowlist": "Domain nicht in der Allowlist gefunden",
|
||||
"domainRemovedFromAllowlist": "Domain '{domain}' aus der Allowlist entfernt",
|
||||
"syncComplete": "{external_count} externe Domains synchronisiert ({added} hinzugefügt, {removed} entfernt)",
|
||||
"invalidEmailFormat": "Ungültiges E-Mail-Format",
|
||||
"emailAddedToBl": "E-Mail '{email}' zur Liste blockierter E-Mails hinzugefügt",
|
||||
"emailNotFoundInBl": "E-Mail nicht in der Blockliste gefunden",
|
||||
"emailRemovedFromBl": "E-Mail '{email}' aus der Liste blockierter E-Mails entfernt",
|
||||
"invalidIPAddress": "Ungültige IP-Adresse",
|
||||
"ipAddedToBl": "IP '{ip_address}' zur Liste blockierter IPs hinzugefügt",
|
||||
"ipNotFoundInBl": "IP nicht in der Blockliste gefunden",
|
||||
"ipRemovedFromBl": "IP '{ip_address}' aus der Liste blockierter IPs entfernt",
|
||||
"youtubeUploadNotFound": "Upload für Auftrag {job_id} nicht gefunden oder nicht in einem wiederholbaren Status",
|
||||
"youtubeUploadQueuedForRetry": "YouTube-Upload für Auftrag {job_id} für erneuten Versuch in die Warteschlange eingereiht",
|
||||
"youtubeQueueProcessingStarted": "Verarbeitung der YouTube-Warteschlange im Hintergrund gestartet"
|
||||
},
|
||||
"rateLimits": {
|
||||
"configNotFound": "Ratenlimit-Konfiguration nicht gefunden: {config_id}",
|
||||
"configUpdateError": "Fehler beim Aktualisieren der Ratenlimit-Konfiguration: {error}"
|
||||
},
|
||||
"errors": {
|
||||
"insufficientCredits": "Unzureichendes Guthaben für diesen Vorgang",
|
||||
"insufficientCreditsBuyUrl": "/#pricing"
|
||||
},
|
||||
"emails": {
|
||||
"magicLink": {
|
||||
"subject": "Melde dich bei {brand_name} an",
|
||||
"greeting": "Hallo,",
|
||||
"signInPrompt": "Klicke auf den Button unten, um dich bei {brand_name} anzumelden:",
|
||||
"signInButton": "Anmelden",
|
||||
"expiryWarning": "Dieser Link läuft in 15 Minuten ab und kann nur einmal verwendet werden.",
|
||||
"fallbackLink": "Wenn der Button nicht funktioniert, kopiere diesen Link und füge ihn in deinen Browser ein:",
|
||||
"ignoreNote": "Wenn du diese E-Mail nicht angefordert hast, kannst du sie getrost ignorieren."
|
||||
},
|
||||
"welcome": {
|
||||
"subject": "Willkommen bei Nomad Karaoke!",
|
||||
"welcomeGreeting": "Willkommen bei Nomad Karaoke!",
|
||||
"turnAnySong": "Verwandle jeden Song in wenigen Minuten in ein professionelles Karaoke-Video.",
|
||||
"freeCreditsLabel": "Kostenloses Guthaben",
|
||||
"freeCreditsNote": "Jedes Guthaben reicht für ein professionelles Karaoke-Video",
|
||||
"howItWorks": "So funktioniert's:",
|
||||
"step1Title": "1. Suche nach einem Song",
|
||||
"step1Desc": "Gib Künstler und Titel ein, und wir finden hochwertiges Audio.",
|
||||
"step2Title": "2. Unser System zaubert",
|
||||
"step2Desc": "Wir trennen den Gesang, transkribieren den Text und synchronisieren alles perfekt.",
|
||||
"step3Title": "3. Überprüfen & anpassen",
|
||||
"step3Desc": "Passe den Text bei Bedarf an und wähle dein Instrumental.",
|
||||
"step4Title": "4. Hol dir dein Video",
|
||||
"step4Desc": "Lade dein 4K-Karaoke-Video herunter oder lade es direkt auf YouTube hoch.",
|
||||
"feedbackBonus": "Stelle 2 Videos fertig und erhalte 2 weitere kostenlose Guthaben, indem du dein Feedback teilst!",
|
||||
"getStartedButton": "Loslegen"
|
||||
},
|
||||
"creditsAdded": {
|
||||
"subject": "{credits} Guthaben zu deinem Nomad Karaoke-Konto hinzugefügt",
|
||||
"greatNews": "Tolle Neuigkeiten!",
|
||||
"creditsAddedMessage": "{credits} Guthaben wurden deinem Konto hinzugefügt.",
|
||||
"yourBalance": "Dein Kontostand:",
|
||||
"credits": "Guthaben",
|
||||
"eachCreditLets": "Mit jedem Guthaben kannst du ein professionelles Karaoke-Video erstellen mit:",
|
||||
"featureVocalSeparation": "KI-gestützte Gesangs-/Instrumentaltrennung",
|
||||
"featureLyrics": "Synchronisierter Text mit Timing auf Wortebene",
|
||||
"feature4k": "4K-Videoausgabe",
|
||||
"featureYoutube": "YouTube-Upload",
|
||||
"createButton": "Jetzt Karaoke erstellen"
|
||||
},
|
||||
"jobCompletion": {
|
||||
"subjectWithBrand": "{brand_code}: {artist} - {title} (Dein Karaoke-Video ist fertig!)",
|
||||
"subject": "{artist} - {title} (Dein Karaoke-Video ist fertig!)",
|
||||
"subjectFallback": "Dein Karaoke-Video ist fertig!"
|
||||
},
|
||||
"youtubeUpload": {
|
||||
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube-Upload bereit!)",
|
||||
"subject": "{artist} - {title} (YouTube-Upload bereit!)",
|
||||
"subjectFallback": "Dein YouTube-Upload ist bereit!"
|
||||
},
|
||||
"actionReminder": {
|
||||
"lyricsSubject": "Aktion erforderlich: Textüberprüfung für {artist} - {title}",
|
||||
"lyricsSubjectFallback": "Aktion erforderlich: Textüberprüfung",
|
||||
"instrumentalSubject": "Aktion erforderlich: Instrumental auswählen für {artist} - {title}",
|
||||
"instrumentalSubjectFallback": "Aktion erforderlich: Instrumental auswählen",
|
||||
"audioEditSubject": "Aktion erforderlich für {artist} - {title}",
|
||||
"audioEditSubjectFallback": "Aktion erforderlich",
|
||||
"alertHeading": "Dein Karaoke-Video benötigt deine Eingabe!"
|
||||
},
|
||||
"reviewReminder": {
|
||||
"subject": "Erinnerung: Dein Karaoke-Video wartet auf Überprüfung — {artist} - {title}",
|
||||
"subjectFallback": "Erinnerung: Dein Karaoke-Video wartet auf Überprüfung",
|
||||
"alertHeading": "Dein Karaoke-Video wartet auf dich!",
|
||||
"reminderIntro": "Nur eine kurze Erinnerung, dass dein Karaoke-Video{song_name} zur Überprüfung bereit ist.",
|
||||
"reviewButton": "Dein Video überprüfen",
|
||||
"reviewInstructions": "Während der Überprüfung kannst du kontrollieren, ob der Text korrekt ist, und deine bevorzugte Instrumentalspur auswählen. Das dauert normalerweise nur wenige Minuten!",
|
||||
"helpOffer": "Wenn du Probleme mit dem Überprüfungsprozess hast, antworte einfach auf diese E-Mail und ich helfe dir gerne weiter.",
|
||||
"expiryWarning": "Bitte beachte: Wenn die Überprüfung nicht innerhalb der nächsten 24 Stunden abgeschlossen wird, läuft der Auftrag automatisch ab und dein Guthaben wird erstattet."
|
||||
},
|
||||
"reviewExpired": {
|
||||
"subject": "Dein Karaoke-Video ist abgelaufen — {artist} - {title}",
|
||||
"subjectFallback": "Dein Karaoke-Video ist abgelaufen",
|
||||
"cancelNotice": "Dein Karaoke-Video{song_name} wurde automatisch abgebrochen, da die Überprüfung nicht innerhalb von 48 Stunden abgeschlossen wurde.",
|
||||
"refundNotice": "Keine Sorge — dein Guthaben wurde erstattet! Dein aktueller Kontostand beträgt {credits_balance} {credits_word}.",
|
||||
"creditSingular": "Guthaben",
|
||||
"creditPlural": "Guthaben",
|
||||
"createNewPrompt": "Du kannst jederzeit ein neues Karaoke-Video mit deinem Guthaben erstellen:",
|
||||
"createButton": "Neues Video erstellen",
|
||||
"helpOffer": "Wenn du Probleme mit dem Überprüfungsprozess hattest oder Hilfe benötigst, antworte einfach auf diese E-Mail — ich helfe dir gerne!"
|
||||
},
|
||||
"creditDenied": {
|
||||
"subject": "Über dein kostenloses Nomad Karaoke-Guthaben",
|
||||
"greeting": "Hallo,",
|
||||
"thankYou": "Danke für deine Anmeldung bei Nomad Karaoke!",
|
||||
"deniedMessage": "Leider konnten wir dir dieses Mal dein kostenloses {credit_type} nicht gewähren. Unser System hat Muster erkannt, die darauf hindeuten, dass dies möglicherweise nicht dein erstes Konto bei uns ist, und jeder Karaoke-Generierungsauftrag kostet uns echtes Geld an Cloud-Computing- und API-Gebühren.",
|
||||
"mistakeNote": "Wir verstehen vollkommen, wenn das ein Fehler ist! Wenn du ein echter neuer Benutzer bist, antworte einfach auf diese E-Mail und lass es Andrew (dem Gründer) wissen. Er hat diesen Dienst entwickelt und gibt dir gerne ein paar kostenlose Guthaben zum Ausprobieren — er bittet dich nur darum, im Gegenzug ehrliches Feedback zur Erfahrung zu geben.",
|
||||
"buyPrompt": "Wenn du sofort loslegen möchtest, kannst du auch Guthaben kaufen:",
|
||||
"buyButton": "Guthaben kaufen",
|
||||
"costNote": "Wir halten die Kosten niedrig, damit wir den Dienst günstig anbieten können, was bedeutet, dass wir bei Missbrauch von kostenlosem Guthaben vorsichtig sein müssen. Danke für dein Verständnis!",
|
||||
"welcomeCredits": "Willkommens-Guthaben",
|
||||
"feedbackCredits": "Feedback-Bonus-Guthaben"
|
||||
},
|
||||
"madeForYouConfirmation": {
|
||||
"subject": "Bestellung bestätigt: {artist} - {title} | Nomad Karaoke",
|
||||
"thankYou": "Vielen Dank für deine Bestellung!",
|
||||
"orderDetails": "Bestelldetails",
|
||||
"orderId": "Bestell-ID:",
|
||||
"artist": "Künstler:",
|
||||
"title": "Titel:",
|
||||
"yourNotes": "Deine Notizen:",
|
||||
"deliveryTime": "Unser Team wird dein individuelles Karaoke-Video innerhalb von {hours} Stunden erstellen.",
|
||||
"deliveryNotice": "Du erhältst eine E-Mail mit Download-Links, sobald dein Video fertig ist.",
|
||||
"noAction": "Keine Aktion erforderlich — lehn dich zurück und wir kümmern uns um alles!"
|
||||
},
|
||||
"shared": {
|
||||
"footerHelp": "Wenn etwas nicht perfekt ist, antworte einfach auf diese E-Mail und ich werde es beheben!"
|
||||
},
|
||||
"templates": {
|
||||
"jobCompletion": {
|
||||
"greeting": "Hallo {name},",
|
||||
"thanks": "Danke für deine Bestellung!",
|
||||
"youtubeLink": "Hier ist der Link für das auf YouTube veröffentlichte Karaoke-Video:",
|
||||
"dropboxIntro": "Hier ist der Dropbox-Ordner mit allen fertigen Dateien und Quelldateien, einschließlich:",
|
||||
"fileList": "- \"(Final Karaoke Lossless).mkv\": kombiniertes Karaoke-Video in 4K H264 mit verlustfreiem FLAC-Audio\n- \"(Final Karaoke).mp4\": kombiniertes Karaoke-Video mit Titel-/Endbildschirm in 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": kombiniertes Karaoke-Video in 720p H264/AAC (kleinere Datei für ältere Systeme)\n- \"(With Vocals).mp4\": Video zum Mitsingen in 4K H264/AAC mit Originalgesang\n- \"(Karaoke).mov\": Karaoke-Videoausgabe von MidiCo (ohne Titel-/Endbildschirm)\n- \"(Title).mov\"/\"(End).mov\": Titelkarten- und Endbildschirm-Videos\n- \"(Final Karaoke CDG).zip\": CDG+MP3-Format für ältere/kommerzielle Karaoke-Systeme\n- \"(Final Karaoke TXT).zip\": TXT+MP3-Format für Power Karaoke\n- stems/*.flac: verschiedene getrennte Instrumental- und Gesangs-Audio-Stems im verlustfreien Format\n- lyrics/*.txt Songtexte aus verschiedenen Quellen im reinen Textformat",
|
||||
"fixOffer": "Lass mich wissen, wenn etwas nicht perfekt ist. Ich passe es gerne an oder behebe es. Wenn du ein anderes Format benötigst, kann ich es wahrscheinlich für dich konvertieren!",
|
||||
"feedbackRequest": "Wenn du einen Moment Zeit hast, würde ich mich sehr über dein Feedback freuen (dauert 2 Minuten):",
|
||||
"signOff": "Nochmals vielen Dank und einen schönen Tag!\n-Andrew",
|
||||
"youtubeQueued": "Dein YouTube-Upload ist in der Warteschlange und wird automatisch verarbeitet. Du erhältst in Kürze eine Folge-E-Mail mit dem Link."
|
||||
},
|
||||
"actionLyrics": {
|
||||
"greeting": "Hallo {name},",
|
||||
"ready": "Dein Karaoke-Video für \"{artist} - {title}\" ist zur Überprüfung bereit!",
|
||||
"instructions": "Unser System hat den Text transkribiert und synchronisiert, aber er benötigt möglicherweise einige Korrekturen. Du kannst auch deine bevorzugte Instrumentalspur (mit oder ohne Hintergrundgesang) auswählen.",
|
||||
"reviewPrompt": "Bitte überprüfe deinen Text und wähle ein Instrumental aus:",
|
||||
"duration": "Das dauert normalerweise nur wenige Minuten.",
|
||||
"signOff": "Danke!\n-Andrew"
|
||||
},
|
||||
"actionInstrumental": {
|
||||
"greeting": "Hallo {name},",
|
||||
"almostDone": "Dein Karaoke-Video für \"{artist} - {title}\" ist fast fertig!",
|
||||
"instructions": "Wir haben das Audio in verschiedene Versionen getrennt. Bitte wähle aus, welche Instrumentalspur du für das endgültige Video verwenden möchtest.",
|
||||
"selectPrompt": "Wähle hier dein Instrumental aus:",
|
||||
"signOff": "Danke!\n-Andrew"
|
||||
},
|
||||
"youtubeComplete": {
|
||||
"greeting": "Hallo {name},",
|
||||
"greatNews": "Tolle Neuigkeiten! Dein Karaoke-Video für \"{artist} - {title}\" wurde auf YouTube hochgeladen:",
|
||||
"delayNote": "Dieser Upload hat sich kurz verzögert, während unsere Systeme andere Uploads verarbeitet haben, aber jetzt ist alles bereit.",
|
||||
"signOff": "Danke!\n-Andrew"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
{
|
||||
"auth": {
|
||||
"unknownService": "Unknown service: {service}",
|
||||
"invalidCredentials": "The following services need re-authorization: {services}",
|
||||
"validCredentials": "All requested credentials are valid",
|
||||
"youtubeAuthInstructions": "Visit {verification_url} and enter code: {user_code}",
|
||||
"youtubeAuthStartFailed": "Failed to start YouTube device auth: {error}",
|
||||
"gdriveLinkInstructions": "Visit {verification_url} and enter code: {user_code}",
|
||||
"gdriveAuthStartFailed": "Failed to start Google Drive device auth: {error}",
|
||||
"discordAlertNotConfigured": "Discord alert webhook not configured"
|
||||
},
|
||||
"jobs": {
|
||||
"created": "Job created successfully. Processing started.",
|
||||
"authError": "Authentication error: no user identity available",
|
||||
"noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.",
|
||||
"notFound": "Job not found",
|
||||
"noPermissionAccess": "You don't have permission to access this job",
|
||||
"noPermissionEdit": "You don't have permission to edit this job",
|
||||
"noPermissionDelete": "You don't have permission to delete this job",
|
||||
"noPermissionModify": "You don't have permission to modify this job",
|
||||
"notCompleted": "Only completed jobs can be edited. Current status: {status}",
|
||||
"alreadyBeingEdited": "This job is already being edited (outputs were already deleted)",
|
||||
"cleanupFailed": "Cleanup failed for {services}. Job not modified. Please try again or contact support.",
|
||||
"reopened": "Track reopened for editing. Previous outputs have been removed.",
|
||||
"invalidDatetimeFormat": "Invalid {field} format: {value}",
|
||||
"listError": "Error listing jobs: {error}",
|
||||
"deleteError": "Error deleting job {job_id}: {error}",
|
||||
"deletionPreview": "Add &confirm=true to execute deletion",
|
||||
"deletionRequiresFilters": "At least one filter (environment, client_id, status, created_before) is required",
|
||||
"bulkDeleteError": "Error bulk deleting jobs: {error}",
|
||||
"reviewNotReady": "Job not ready for review (current status: {status})",
|
||||
"correctionsUnavailable": "Corrections data not available",
|
||||
"audioUnavailable": "Audio not available for review",
|
||||
"reviewCannotStart": "Cannot start review",
|
||||
"jobNotInReviewState": "Job not in review state (current status: {status})",
|
||||
"correctionsProcessing": "Corrections saved. Call /complete-review when done.",
|
||||
"editLogSaveFailed": "Error saving edit log for job {job_id}: {error}",
|
||||
"stemsMissing": "Job missing required stems (instrumental_clean and/or backing_vocals)",
|
||||
"customInstrumentalFailed": "Error creating custom instrumental for job {job_id}: {error}",
|
||||
"audioProcessingFailed": "Failed to process audio file: {error}",
|
||||
"durationMismatch": "Duration mismatch: uploaded file is {upload_duration}s but original audio is {original_duration}s. The instrumental must be exactly {original_duration}s (±0.5s).",
|
||||
"reviewNotInState": "Job not in review state (current status: {status})",
|
||||
"noLyricsDetected": "Cannot complete review: no lyrics were detected in the audio. This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). You can go back and paste lyrics manually using 'Replace All', or cancel this job and try again with an audio file that contains vocals.",
|
||||
"reviewCompleteStartRendering": "Review complete. Video rendering started.",
|
||||
"reviewCompleteError": "Error completing review for job {job_id}: {error}",
|
||||
"instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.",
|
||||
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental selected. Video generation started.",
|
||||
"instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}",
|
||||
"downloadUrlsError": "Error getting download URLs: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job not found",
|
||||
"reviewNotReady": "Job not ready for review (current status: {status})",
|
||||
"correctionsNotFound": "Corrections data not found. Lyrics processing may not be complete.",
|
||||
"correctionsLoadFailed": "Error loading corrections: {error}",
|
||||
"audioNotFound": "Audio file not found",
|
||||
"audioServeError": "Error serving audio: {error}",
|
||||
"instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.",
|
||||
"invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}",
|
||||
"reviewCompletedError": "Error completing review: {error}",
|
||||
"handlersUpdateNotImplemented": "Handler updates not yet implemented",
|
||||
"lyricsAddError": "Failed to add lyrics: {error}",
|
||||
"lyricsAddInvalidRequest": "Invalid add lyrics request: {error}",
|
||||
"lyricsSearchError": "Failed to search lyrics: {error}",
|
||||
"lyricsSearchInvalidRequest": "Invalid search lyrics request: {error}",
|
||||
"lyricsSearchNoResults": "No matching lyrics found from any provider",
|
||||
"previewVideoGenerationError": "Failed to generate preview video: {error}",
|
||||
"previewVideoNotFound": "Preview video not found",
|
||||
"previewVideoStreamError": "Error streaming preview video: {error}",
|
||||
"annotationSaveError": "Error saving annotations: {error}",
|
||||
"waveformGenerationError": "Error generating waveform data: {error}",
|
||||
"waveformNoAudio": "No audio available for waveform",
|
||||
"sessionSaveError": "Correction data is required"
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Audio search is not enabled for this tenant",
|
||||
"disabled": "Audio search is not available",
|
||||
"downloadError": "Download failed for job {job_id}: {error}",
|
||||
"jobNotFound": "Job {job_id} not found",
|
||||
"noSearchResults": "No search results available",
|
||||
"invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}",
|
||||
"selectionError": "Error during audio selection for job {job_id}: {error}",
|
||||
"youtubeDownloadError": "YouTube download failed: {error}",
|
||||
"torrentDownloadError": "Cannot download from {source} without remote flacfetch service. Configure FLACFETCH_API_URL.",
|
||||
"remoteDownloadNoSearchId": "No source_id or remote_search_id available for {source} download",
|
||||
"remoteDownloadCompleteNoPath": "Remote download completed but no file path returned",
|
||||
"spotifyDownloadError": "Cannot download from Spotify without remote flacfetch service. Configure FLACFETCH_API_URL.",
|
||||
"genericDownloadError": "Unknown source type: {source}, attempting generic download",
|
||||
"jobNotFoundDuringDownload": "Job {job_id} not found during background download",
|
||||
"selectAudioError": "Error selecting audio for job {job_id}: {error}",
|
||||
"searchAudioError": "Error searching audio: {error}",
|
||||
"searchCreatedSuccessfully": "Job created. Searching for audio...",
|
||||
"autoDownloadStarted": "Best result selected automatically. Download starting..."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
"magicLinkSent": "If this email is registered, you will receive a sign-in link shortly.",
|
||||
"emailServiceNotConfigured": "Email service is not available. Please contact support.",
|
||||
"emailDomainNotAllowed": "Email domain not allowed for this tenant",
|
||||
"invalidToken": "Invalid token",
|
||||
"verifyError": "Verification failed: {message}",
|
||||
"magicLinkSuccess": "Successfully signed in",
|
||||
"logoutSuccess": "Successfully logged out",
|
||||
"userNotFound": "User not found",
|
||||
"creditPackagesError": "Error loading credit packages: {error}",
|
||||
"stripeSendError": "Error sending Stripe checkout link: {error}",
|
||||
"stripeWebhookProcessingError": "Error processing Stripe webhook: {error}",
|
||||
"feedbackSaveError": "Error saving feedback: {error}",
|
||||
"feedbackNotEligible": "User not eligible for feedback"
|
||||
},
|
||||
"fileUpload": {
|
||||
"invalidTheme": "Theme not found: {theme_id}. Use GET /api/themes to list available themes.",
|
||||
"uploadSuccess": "File uploaded successfully. Processing started.",
|
||||
"uploadError": "Error uploading file: {error}",
|
||||
"urlDownloadError": "Error downloading from URL: {error}",
|
||||
"invalidContentType": "Invalid content type: {content_type}",
|
||||
"fileSizeError": "File is too large: {size}. Maximum: {max_size}",
|
||||
"invalidFileType": "Invalid file type: {file_type}",
|
||||
"multipleAudioFilesNotAllowed": "Only one audio file can be uploaded",
|
||||
"noAudioFileProvided": "No audio file provided",
|
||||
"urlCreationSuccess": "Job created. Upload URLs generated.",
|
||||
"urlCreationError": "Error creating job with upload URLs: {error}",
|
||||
"uploadsCompleteSuccess": "Uploads complete. Processing started.",
|
||||
"uploadsCompleteError": "Error completing uploads: {error}",
|
||||
"noUploadedFiles": "No uploaded files specified",
|
||||
"styleUploadUrlsSuccess": "Style upload URLs generated.",
|
||||
"styleUploadsCompleteSuccess": "Style files updated. Processing restarted.",
|
||||
"styleUploadsCompleteError": "Error completing style uploads: {error}"
|
||||
},
|
||||
"catalog": {
|
||||
"rateLimitExceeded": "Rate limit exceeded. Maximum {max_requests} catalog requests per minute.",
|
||||
"catalogSearchError": "Error searching catalog: {error}",
|
||||
"communityCheckError": "Error checking community versions: {error}"
|
||||
},
|
||||
"themes": {
|
||||
"themesLoadError": "Failed to load themes",
|
||||
"themeNotFound": "Theme not found: {theme_id}",
|
||||
"themeLoadError": "Failed to load theme",
|
||||
"previewNotAvailable": "No preview available for theme: {theme_id}",
|
||||
"previewLoadError": "Failed to load theme preview",
|
||||
"youtubeDescriptionNotFound": "Theme not found: {theme_id}",
|
||||
"youtubeDescriptionLoadError": "Failed to load YouTube description"
|
||||
},
|
||||
"tenant": {
|
||||
"assetNotFound": "Asset not found"
|
||||
},
|
||||
"push": {
|
||||
"disabled": "Push notifications are not enabled",
|
||||
"userEmailNotAvailable": "User email not available",
|
||||
"missingEncryptionKeys": "Missing required keys (p256dh, auth)",
|
||||
"subscriptionSaveFailed": "Failed to save subscription",
|
||||
"subscriptionRegistered": "Push subscription registered successfully",
|
||||
"subscriptionNotFound": "Subscription removed (or was not found)",
|
||||
"subscriptionRemoved": "Push subscription removed successfully",
|
||||
"testNotificationSent": "Test notification sent to {sent_count} device(s)"
|
||||
},
|
||||
"pushNotifications": {
|
||||
"reviewLyricsTitle": "Review Lyrics",
|
||||
"reviewLyricsBody": "\"{title}\" by {artist} needs lyrics review",
|
||||
"selectInstrumentalTitle": "Select Instrumental",
|
||||
"selectInstrumentalBody": "\"{title}\" by {artist} needs instrumental selection",
|
||||
"videoReadyTitle": "Video Ready!",
|
||||
"videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Invalid domain format",
|
||||
"domainAddedToBl": "Domain '{domain}' added to disposable domains blocklist",
|
||||
"domainNotFoundInBl": "Domain not found in blocklist",
|
||||
"domainRemovedFromBl": "Domain '{domain}' removed from disposable domains blocklist",
|
||||
"domainAddedToAllowlist": "Domain '{domain}' added to allowlist",
|
||||
"domainNotFoundInAllowlist": "Domain not found in allowlist",
|
||||
"domainRemovedFromAllowlist": "Domain '{domain}' removed from allowlist",
|
||||
"syncComplete": "Synced {external_count} external domains ({added} added, {removed} removed)",
|
||||
"invalidEmailFormat": "Invalid email format",
|
||||
"emailAddedToBl": "Email '{email}' added to blocked emails list",
|
||||
"emailNotFoundInBl": "Email not found in blocklist",
|
||||
"emailRemovedFromBl": "Email '{email}' removed from blocked emails list",
|
||||
"invalidIPAddress": "Invalid IP address",
|
||||
"ipAddedToBl": "IP '{ip_address}' added to blocked IPs list",
|
||||
"ipNotFoundInBl": "IP not found in blocklist",
|
||||
"ipRemovedFromBl": "IP '{ip_address}' removed from blocked IPs list",
|
||||
"youtubeUploadNotFound": "Upload not found or not in retryable state for job {job_id}",
|
||||
"youtubeUploadQueuedForRetry": "YouTube upload for job {job_id} queued for retry",
|
||||
"youtubeQueueProcessingStarted": "YouTube queue processing started in background"
|
||||
},
|
||||
"rateLimits": {
|
||||
"configNotFound": "Rate limit config not found: {config_id}",
|
||||
"configUpdateError": "Error updating rate limit config: {error}"
|
||||
},
|
||||
"errors": {
|
||||
"insufficientCredits": "Insufficient credits for this operation",
|
||||
"insufficientCreditsBuyUrl": "/#pricing"
|
||||
},
|
||||
"emails": {
|
||||
"magicLink": {
|
||||
"subject": "Sign in to {brand_name}",
|
||||
"greeting": "Hi there,",
|
||||
"signInPrompt": "Click the button below to sign in to {brand_name}:",
|
||||
"signInButton": "Sign In",
|
||||
"expiryWarning": "This link expires in 15 minutes and can only be used once.",
|
||||
"fallbackLink": "If the button doesn't work, copy and paste this link into your browser:",
|
||||
"ignoreNote": "If you didn't request this email, you can safely ignore it."
|
||||
},
|
||||
"welcome": {
|
||||
"subject": "Welcome to Nomad Karaoke!",
|
||||
"welcomeGreeting": "Welcome to Nomad Karaoke!",
|
||||
"turnAnySong": "Turn any song into a professional karaoke video in minutes.",
|
||||
"freeCreditsLabel": "Free Credits",
|
||||
"freeCreditsNote": "Each credit creates one professional karaoke video",
|
||||
"howItWorks": "Here's how it works:",
|
||||
"step1Title": "1. Search for a song",
|
||||
"step1Desc": "Enter the artist and title, and we'll find high-quality audio.",
|
||||
"step2Title": "2. Our system works its magic",
|
||||
"step2Desc": "We separate vocals, transcribe lyrics, and sync everything perfectly.",
|
||||
"step3Title": "3. Review & customize",
|
||||
"step3Desc": "Fine-tune the lyrics if needed, choose your instrumental.",
|
||||
"step4Title": "4. Get your video",
|
||||
"step4Desc": "Download your 4K karaoke video or upload directly to YouTube.",
|
||||
"feedbackBonus": "Complete 2 videos and earn 2 more free credits by sharing your feedback!",
|
||||
"getStartedButton": "Get Started"
|
||||
},
|
||||
"creditsAdded": {
|
||||
"subject": "{credits} credits added to your Nomad Karaoke account",
|
||||
"greatNews": "Great news!",
|
||||
"creditsAddedMessage": "{credits} credits have been added to your account.",
|
||||
"yourBalance": "Your balance:",
|
||||
"credits": "credits",
|
||||
"eachCreditLets": "Each credit lets you create one professional karaoke video with:",
|
||||
"featureVocalSeparation": "AI-powered vocal/instrumental separation",
|
||||
"featureLyrics": "Synchronized lyrics with word-level timing",
|
||||
"feature4k": "4K video output",
|
||||
"featureYoutube": "YouTube upload",
|
||||
"createButton": "Create Karaoke Now"
|
||||
},
|
||||
"jobCompletion": {
|
||||
"subjectWithBrand": "{brand_code}: {artist} - {title} (Your karaoke video is ready!)",
|
||||
"subject": "{artist} - {title} (Your karaoke video is ready!)",
|
||||
"subjectFallback": "Your karaoke video is ready!"
|
||||
},
|
||||
"youtubeUpload": {
|
||||
"subjectWithBrand": "{brand_code}: {artist} - {title} (YouTube upload ready!)",
|
||||
"subject": "{artist} - {title} (YouTube upload ready!)",
|
||||
"subjectFallback": "Your YouTube upload is ready!"
|
||||
},
|
||||
"actionReminder": {
|
||||
"lyricsSubject": "Action needed: Review lyrics for {artist} - {title}",
|
||||
"lyricsSubjectFallback": "Action needed: Review lyrics",
|
||||
"instrumentalSubject": "Action needed: Select instrumental for {artist} - {title}",
|
||||
"instrumentalSubjectFallback": "Action needed: Select instrumental",
|
||||
"audioEditSubject": "Action needed for {artist} - {title}",
|
||||
"audioEditSubjectFallback": "Action needed",
|
||||
"alertHeading": "Your karaoke video needs input from you!"
|
||||
},
|
||||
"reviewReminder": {
|
||||
"subject": "Reminder: Your karaoke video is waiting for review — {artist} - {title}",
|
||||
"subjectFallback": "Reminder: Your karaoke video is waiting for review",
|
||||
"alertHeading": "Your karaoke video is waiting for you!",
|
||||
"reminderIntro": "Just a friendly reminder that your karaoke video{song_name} is ready for review.",
|
||||
"reviewButton": "Review Your Video",
|
||||
"reviewInstructions": "During the review, you can check the lyrics are correct and choose your preferred instrumental track. It usually only takes a few minutes!",
|
||||
"helpOffer": "If you're having any trouble with the review process, just reply to this email and I'll be happy to help you out.",
|
||||
"expiryWarning": "Please note: if the review isn't completed within the next 24 hours, the job will automatically expire and your credit will be refunded."
|
||||
},
|
||||
"reviewExpired": {
|
||||
"subject": "Your karaoke video has expired — {artist} - {title}",
|
||||
"subjectFallback": "Your karaoke video has expired",
|
||||
"cancelNotice": "Your karaoke video{song_name} has been automatically cancelled because the review wasn't completed within 48 hours.",
|
||||
"refundNotice": "Don't worry — your credit has been refunded! Your current balance is {credits_balance} {credits_word}.",
|
||||
"creditSingular": "credit",
|
||||
"creditPlural": "credits",
|
||||
"createNewPrompt": "You can create a new karaoke video anytime using your credits:",
|
||||
"createButton": "Create New Video",
|
||||
"helpOffer": "If you had any trouble with the review process or need help, just reply to this email — I'd love to help!"
|
||||
},
|
||||
"creditDenied": {
|
||||
"subject": "About your Nomad Karaoke free credits",
|
||||
"greeting": "Hi there,",
|
||||
"thankYou": "Thanks for signing up for Nomad Karaoke!",
|
||||
"deniedMessage": "Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected patterns that suggest this may not be your first account with us, and each karaoke generation job costs us real money in cloud computing and API fees.",
|
||||
"mistakeNote": "We totally understand if this is a mistake! If you're a genuine new user, please just reply to this email and let Andrew (the founder) know. He built this service and is happy to grant you some free credits to try it out — he just asks that you provide honest feedback on the experience in return.",
|
||||
"buyPrompt": "If you'd like to get started right away, you can also purchase credits:",
|
||||
"buyButton": "Buy Credits",
|
||||
"costNote": "We keep costs low so we can offer the service affordably, which means we need to be careful about free credit abuse. Thanks for understanding!",
|
||||
"welcomeCredits": "welcome credits",
|
||||
"feedbackCredits": "feedback bonus credits"
|
||||
},
|
||||
"madeForYouConfirmation": {
|
||||
"subject": "Order Confirmed: {artist} - {title} | Nomad Karaoke",
|
||||
"thankYou": "Thank You for Your Order!",
|
||||
"orderDetails": "Order Details",
|
||||
"orderId": "Order ID:",
|
||||
"artist": "Artist:",
|
||||
"title": "Title:",
|
||||
"yourNotes": "Your Notes:",
|
||||
"deliveryTime": "Our team will create your custom karaoke video within {hours} hours.",
|
||||
"deliveryNotice": "You'll receive an email with download links as soon as your video is ready.",
|
||||
"noAction": "No action needed — sit back and we'll take care of everything!"
|
||||
},
|
||||
"shared": {
|
||||
"footerHelp": "If anything isn't perfect, just reply to this email and I'll fix it!"
|
||||
},
|
||||
"templates": {
|
||||
"jobCompletion": {
|
||||
"greeting": "Hi {name},",
|
||||
"thanks": "Thanks for your order!",
|
||||
"youtubeLink": "Here's the link for the karaoke video published to YouTube:",
|
||||
"dropboxIntro": "Here's the dropbox folder with all the finished files and source files, including:",
|
||||
"fileList": "- \"(Final Karaoke Lossless).mkv\": combined karaoke video in 4k H264 with lossless FLAC audio\n- \"(Final Karaoke).mp4\": combined karaoke video with title/end screen in 4k H264/AAC\n- \"(Final Karaoke 720p).mp4\": combined karaoke video in 720p H264/AAC (smaller file for older systems)\n- \"(With Vocals).mp4\": sing along video in 4k H264/AAC with original vocals\n- \"(Karaoke).mov\": karaoke video output from MidiCo (no title/end screen)\n- \"(Title).mov\"/\"(End).mov\": title card and end screen videos\n- \"(Final Karaoke CDG).zip\": CDG+MP3 format for older/commercial karaoke systems\n- \"(Final Karaoke TXT).zip\": TXT+MP3 format for Power Karaoke\n- stems/*.flac: various separated instrumental and vocal audio stems in lossless format\n- lyrics/*.txt song lyrics from various sources in plain text format",
|
||||
"fixOffer": "Let me know if anything isn't perfect and I'll happily tweak / fix, or if you need it in any other format I can probably convert it for you!",
|
||||
"feedbackRequest": "If you have a moment, I'd really appreciate your feedback (takes 2 minutes):",
|
||||
"signOff": "Thanks again and have a great day!\n-Andrew",
|
||||
"youtubeQueued": "Your YouTube upload is queued and will be processed automatically. You'll receive a follow-up email with the link shortly."
|
||||
},
|
||||
"actionLyrics": {
|
||||
"greeting": "Hi {name},",
|
||||
"ready": "Your karaoke video for \"{artist} - {title}\" is ready for review!",
|
||||
"instructions": "Our system has transcribed and synchronized the lyrics, but they may need some corrections. You'll also be able to select your preferred instrumental track (with or without backing vocals).",
|
||||
"reviewPrompt": "Please review your lyrics and select an instrumental:",
|
||||
"duration": "This usually takes just a few minutes.",
|
||||
"signOff": "Thanks!\n-Andrew"
|
||||
},
|
||||
"actionInstrumental": {
|
||||
"greeting": "Hi {name},",
|
||||
"almostDone": "Your karaoke video for \"{artist} - {title}\" is almost done!",
|
||||
"instructions": "We've separated the audio into different versions. Please select which instrumental track you'd like to use for the final video.",
|
||||
"selectPrompt": "Select your instrumental here:",
|
||||
"signOff": "Thanks!\n-Andrew"
|
||||
},
|
||||
"youtubeComplete": {
|
||||
"greeting": "Hi {name},",
|
||||
"greatNews": "Great news! Your karaoke video for \"{artist} - {title}\" has been uploaded to YouTube:",
|
||||
"delayNote": "This upload was briefly delayed while our systems processed other uploads, but everything is all set now.",
|
||||
"signOff": "Thanks!\n-Andrew"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
{
|
||||
"auth": {
|
||||
"unknownService": "Servicio desconocido: {service}",
|
||||
"invalidCredentials": "Los siguientes servicios necesitan reautorización: {services}",
|
||||
"validCredentials": "Todas las credenciales solicitadas son válidas",
|
||||
"youtubeAuthInstructions": "Visita {verification_url} e ingresa el código: {user_code}",
|
||||
"youtubeAuthStartFailed": "Error al iniciar la autenticación del dispositivo en YouTube: {error}",
|
||||
"gdriveLinkInstructions": "Visita {verification_url} e ingresa el código: {user_code}",
|
||||
"gdriveAuthStartFailed": "Error al iniciar la autenticación del dispositivo en Google Drive: {error}",
|
||||
"discordAlertNotConfigured": "Webhook de alerta de Discord no configurado"
|
||||
},
|
||||
"jobs": {
|
||||
"created": "Trabajo creado con éxito. Se ha iniciado el procesamiento.",
|
||||
"authError": "Error de autenticación: no hay identidad de usuario disponible",
|
||||
"noDefaultTheme": "No hay un tema predeterminado configurado. Por favor, contacta a soporte o especifica un theme_id.",
|
||||
"notFound": "Trabajo no encontrado",
|
||||
"noPermissionAccess": "No tienes permiso para acceder a este trabajo",
|
||||
"noPermissionEdit": "No tienes permiso para editar este trabajo",
|
||||
"noPermissionDelete": "No tienes permiso para eliminar este trabajo",
|
||||
"noPermissionModify": "No tienes permiso para modificar este trabajo",
|
||||
"notCompleted": "Solo se pueden editar los trabajos completados. Estado actual: {status}",
|
||||
"alreadyBeingEdited": "Este trabajo ya se está editando (los archivos de salida ya fueron eliminados)",
|
||||
"cleanupFailed": "Error en la limpieza de {services}. El trabajo no fue modificado. Por favor, intenta de nuevo o contacta a soporte.",
|
||||
"reopened": "Pista reabierta para edición. Los archivos de salida anteriores han sido eliminados.",
|
||||
"invalidDatetimeFormat": "Formato de {field} inválido: {value}",
|
||||
"listError": "Error al listar trabajos: {error}",
|
||||
"deleteError": "Error al eliminar el trabajo {job_id}: {error}",
|
||||
"deletionPreview": "Agrega &confirm=true para ejecutar la eliminación",
|
||||
"deletionRequiresFilters": "Se requiere al menos un filtro (environment, client_id, status, created_before)",
|
||||
"bulkDeleteError": "Error al eliminar trabajos en masa: {error}",
|
||||
"reviewNotReady": "El trabajo no está listo para revisión (estado actual: {status})",
|
||||
"correctionsUnavailable": "Datos de corrección no disponibles",
|
||||
"audioUnavailable": "Audio no disponible para revisión",
|
||||
"reviewCannotStart": "No se puede iniciar la revisión",
|
||||
"jobNotInReviewState": "El trabajo no está en estado de revisión (estado actual: {status})",
|
||||
"correctionsProcessing": "Correcciones guardadas. Llama a /complete-review cuando termines.",
|
||||
"editLogSaveFailed": "Error al guardar el registro de edición para el trabajo {job_id}: {error}",
|
||||
"stemsMissing": "Al trabajo le faltan pistas de audio requeridas (instrumental_clean y/o backing_vocals)",
|
||||
"customInstrumentalFailed": "Error al crear el instrumental personalizado para el trabajo {job_id}: {error}",
|
||||
"audioProcessingFailed": "Error al procesar el archivo de audio: {error}",
|
||||
"durationMismatch": "Discrepancia de duración: el archivo subido dura {upload_duration}s pero el audio original dura {original_duration}s. El instrumental debe durar exactamente {original_duration}s (±0.5s).",
|
||||
"reviewNotInState": "El trabajo no está en estado de revisión (estado actual: {status})",
|
||||
"noLyricsDetected": "No se puede completar la revisión: no se detectaron letras en el audio. Esto puede suceder cuando el audio de entrada no tiene voces (ej. una pista de karaoke o instrumental). Puedes volver y pegar las letras manualmente usando 'Reemplazar todo', o cancelar este trabajo e intentar de nuevo con un archivo de audio que contenga voces.",
|
||||
"reviewCompleteStartRendering": "Revisión completada. Se ha iniciado el renderizado de video.",
|
||||
"reviewCompleteError": "Error al completar la revisión para el trabajo {job_id}: {error}",
|
||||
"instrumentalSelectionRequired": "Se requiere instrumental_selection. Debe ser 'clean' o 'with_backing'.",
|
||||
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental seleccionado. Se ha iniciado la generación de video.",
|
||||
"instrumentalSelectionError": "Error al seleccionar el instrumental para el trabajo {job_id}: {error}",
|
||||
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Trabajo no encontrado",
|
||||
"reviewNotReady": "El trabajo no está listo para revisión (estado actual: {status})",
|
||||
"correctionsNotFound": "Datos de corrección no encontrados. El procesamiento de letras puede no estar completo.",
|
||||
"correctionsLoadFailed": "Error al cargar las correcciones: {error}",
|
||||
"audioNotFound": "Archivo de audio no encontrado",
|
||||
"audioServeError": "Error al servir el audio: {error}",
|
||||
"instrumentalSelectionRequired": "Se requiere instrumental_selection. Debe ser 'clean' o 'with_backing'.",
|
||||
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
|
||||
"reviewCompletedError": "Error al completar la revisión: {error}",
|
||||
"handlersUpdateNotImplemented": "Actualizaciones de manejadores aún no implementadas",
|
||||
"lyricsAddError": "Error al agregar letras: {error}",
|
||||
"lyricsAddInvalidRequest": "Solicitud para agregar letras inválida: {error}",
|
||||
"lyricsSearchError": "Error al buscar letras: {error}",
|
||||
"lyricsSearchInvalidRequest": "Solicitud de búsqueda de letras inválida: {error}",
|
||||
"lyricsSearchNoResults": "No se encontraron letras coincidentes en ningún proveedor",
|
||||
"previewVideoGenerationError": "Error al generar el video de vista previa: {error}",
|
||||
"previewVideoNotFound": "Video de vista previa no encontrado",
|
||||
"previewVideoStreamError": "Error al transmitir el video de vista previa: {error}",
|
||||
"annotationSaveError": "Error al guardar las anotaciones: {error}",
|
||||
"waveformGenerationError": "Error al generar los datos de la forma de onda: {error}",
|
||||
"waveformNoAudio": "No hay audio disponible para la forma de onda",
|
||||
"sessionSaveError": "Se requieren datos de corrección"
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "La búsqueda de audio no está habilitada para este inquilino",
|
||||
"disabled": "La búsqueda de audio no está disponible",
|
||||
"downloadError": "Error de descarga para el trabajo {job_id}: {error}",
|
||||
"jobNotFound": "Trabajo {job_id} no encontrado",
|
||||
"noSearchResults": "No hay resultados de búsqueda disponibles",
|
||||
"invalidSelectionIndex": "Índice de selección inválido {selection_index}. Rango válido: 0-{max}",
|
||||
"selectionError": "Error durante la selección de audio para el trabajo {job_id}: {error}",
|
||||
"youtubeDownloadError": "Error en la descarga de YouTube: {error}",
|
||||
"torrentDownloadError": "No se puede descargar de {source} sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
|
||||
"remoteDownloadNoSearchId": "No hay source_id o remote_search_id disponible para la descarga de {source}",
|
||||
"remoteDownloadCompleteNoPath": "Descarga remota completada pero no se devolvió la ruta del archivo",
|
||||
"spotifyDownloadError": "No se puede descargar de Spotify sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
|
||||
"genericDownloadError": "Tipo de fuente desconocido: {source}, intentando descarga genérica",
|
||||
"jobNotFoundDuringDownload": "Trabajo {job_id} no encontrado durante la descarga en segundo plano",
|
||||
"selectAudioError": "Error al seleccionar el audio para el trabajo {job_id}: {error}",
|
||||
"searchAudioError": "Error al buscar audio: {error}",
|
||||
"searchCreatedSuccessfully": "Trabajo creado. Buscando audio...",
|
||||
"autoDownloadStarted": "Mejor resultado seleccionado automáticamente. Iniciando descarga..."
|
||||
},
|
||||
"users": {
|
||||
"disposableEmailBlocked": "disposable_email_not_allowed",
|
||||
"magicLinkSent": "Si este correo está registrado, recibirás un enlace de inicio de sesión en breve.",
|
||||
"emailServiceNotConfigured": "El servicio de correo electrónico no está disponible. Por favor, contacta a soporte.",
|
||||
"emailDomainNotAllowed": "Dominio de correo no permitido para este inquilino",
|
||||
"invalidToken": "Token inválido",
|
||||
"verifyError": "Verificación fallida: {message}",
|
||||
"magicLinkSuccess": "Sesión iniciada con éxito",
|
||||
"logoutSuccess": "Sesión cerrada con éxito",
|
||||
"userNotFound": "Usuario no encontrado",
|
||||
"creditPackagesError": "Error al cargar los paquetes de créditos: {error}",
|
||||
"stripeSendError": "Error al enviar el enlace de pago de Stripe: {error}",
|
||||
"stripeWebhookProcessingError": "Error al procesar el webhook de Stripe: {error}",
|
||||
"feedbackSaveError": "Error al guardar los comentarios: {error}",
|
||||
"feedbackNotEligible": "Usuario no elegible para dar comentarios"
|
||||
},
|
||||
"fileUpload": {
|
||||
"invalidTheme": "Tema no encontrado: {theme_id}. Usa GET /api/themes para listar los temas disponibles.",
|
||||
"uploadSuccess": "Archivo subido con éxito. Se ha iniciado el procesamiento.",
|
||||
"uploadError": "Error al subir el archivo: {error}",
|
||||
"urlDownloadError": "Error al descargar desde la URL: {error}",
|
||||
"invalidContentType": "Tipo de contenido inválido: {content_type}",
|
||||
"fileSizeError": "El archivo es demasiado grande: {size}. Máximo: {max_size}",
|
||||
"invalidFileType": "Tipo de archivo inválido: {file_type}",
|
||||
"multipleAudioFilesNotAllowed": "Solo se puede subir un archivo de audio",
|
||||
"noAudioFileProvided": "No se proporcionó ningún archivo de audio",
|
||||
"urlCreationSuccess": "Trabajo creado. URLs de subida generadas.",
|
||||
"urlCreationError": "Error al crear el trabajo con URLs de subida: {error}",
|
||||
"uploadsCompleteSuccess": "Subidas completadas. Se ha iniciado el procesamiento.",
|
||||
"uploadsCompleteError": "Error al completar las subidas: {error}",
|
||||
"noUploadedFiles": "No se especificaron archivos subidos",
|
||||
"styleUploadUrlsSuccess": "URLs de subida de estilo generadas.",
|
||||
"styleUploadsCompleteSuccess": "Archivos de estilo actualizados. Se ha reiniciado el procesamiento.",
|
||||
"styleUploadsCompleteError": "Error al completar las subidas de estilo: {error}"
|
||||
},
|
||||
"catalog": {
|
||||
"rateLimitExceeded": "Límite de tasa excedido. Máximo {max_requests} solicitudes de catálogo por minuto.",
|
||||
"catalogSearchError": "Error al buscar en el catálogo: {error}",
|
||||
"communityCheckError": "Error al comprobar las versiones de la comunidad: {error}"
|
||||
},
|
||||
"themes": {
|
||||
"themesLoadError": "Error al cargar los temas",
|
||||
"themeNotFound": "Tema no encontrado: {theme_id}",
|
||||
"themeLoadError": "Error al cargar el tema",
|
||||
"previewNotAvailable": "No hay vista previa disponible para el tema: {theme_id}",
|
||||
"previewLoadError": "Error al cargar la vista previa del tema",
|
||||
"youtubeDescriptionNotFound": "Tema no encontrado: {theme_id}",
|
||||
"youtubeDescriptionLoadError": "Error al cargar la descripción de YouTube"
|
||||
},
|
||||
"tenant": {
|
||||
"assetNotFound": "Activo no encontrado"
|
||||
},
|
||||
"push": {
|
||||
"disabled": "Las notificaciones push no están habilitadas",
|
||||
"userEmailNotAvailable": "Correo del usuario no disponible",
|
||||
"missingEncryptionKeys": "Faltan claves requeridas (p256dh, auth)",
|
||||
"subscriptionSaveFailed": "Error al guardar la suscripción",
|
||||
"subscriptionRegistered": "Suscripción push registrada con éxito",
|
||||
"subscriptionNotFound": "Suscripción eliminada (o no fue encontrada)",
|
||||
"subscriptionRemoved": "Suscripción push eliminada con éxito",
|
||||
"testNotificationSent": "Notificación de prueba enviada a {sent_count} dispositivo(s)"
|
||||
},
|
||||
"pushNotifications": {
|
||||
"reviewLyricsTitle": "Revisión de letras",
|
||||
"reviewLyricsBody": "\"{title}\" de {artist} necesita revisión de letras",
|
||||
"selectInstrumentalTitle": "Seleccionar instrumental",
|
||||
"selectInstrumentalBody": "\"{title}\" de {artist} necesita selección de instrumental",
|
||||
"videoReadyTitle": "¡Video listo!",
|
||||
"videoReadyBody": "Tu video de karaoke para \"{title}\" de {artist} está listo para descargar"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Formato de dominio inválido",
|
||||
"domainAddedToBl": "Dominio '{domain}' agregado a la lista de bloqueo de dominios desechables",
|
||||
"domainNotFoundInBl": "Dominio no encontrado en la lista de bloqueo",
|
||||
"domainRemovedFromBl": "Dominio '{domain}' eliminado de la lista de bloqueo de dominios desechables",
|
||||
"domainAddedToAllowlist": "Dominio '{domain}' agregado a la lista de permitidos",
|
||||
"domainNotFoundInAllowlist": "Dominio no encontrado en la lista de permitidos",
|
||||
"domainRemovedFromAllowlist": "Dominio '{domain}' eliminado de la lista de permitidos",
|
||||
"syncComplete": "Sincronizados {external_count} dominios externos ({added} agregados, {removed} eliminados)",
|
||||
"invalidEmailFormat": "Formato de correo inválido",
|
||||
"emailAddedToBl": "Correo '{email}' agregado a la lista de correos bloqueados",
|
||||
"emailNotFoundInBl": "Correo no encontrado en la lista de bloqueo",
|
||||
"emailRemovedFromBl": "Correo '{email}' eliminado de la lista de correos bloqueados",
|
||||
"invalidIPAddress": "Dirección IP inválida",
|
||||
"ipAddedToBl": "IP '{ip_address}' agregada a la lista de IPs bloqueadas",
|
||||
"ipNotFoundInBl": "IP no encontrada en la lista de bloqueo",
|
||||
"ipRemovedFromBl": "IP '{ip_address}' eliminada de la lista de IPs bloqueadas",
|
||||
"youtubeUploadNotFound": "Subida no encontrada o no en estado reintentable para el trabajo {job_id}",
|
||||
"youtubeUploadQueuedForRetry": "Subida a YouTube para el trabajo {job_id} en cola para reintento",
|
||||
"youtubeQueueProcessingStarted": "Procesamiento de la cola de YouTube iniciado en segundo plano"
|
||||
},
|
||||
"rateLimits": {
|
||||
"configNotFound": "Configuración de límite de tasa no encontrada: {config_id}",
|
||||
"configUpdateError": "Error al actualizar la configuración de límite de tasa: {error}"
|
||||
},
|
||||
"errors": {
|
||||
"insufficientCredits": "Créditos insuficientes para esta operación",
|
||||
"insufficientCreditsBuyUrl": "/#pricing"
|
||||
},
|
||||
"emails": {
|
||||
"magicLink": {
|
||||
"subject": "Inicia sesión en {brand_name}",
|
||||
"greeting": "Hola,",
|
||||
"signInPrompt": "Haz clic en el botón de abajo para iniciar sesión en {brand_name}:",
|
||||
"signInButton": "Iniciar sesión",
|
||||
"expiryWarning": "Este enlace expira en 15 minutos y solo puede usarse una vez.",
|
||||
"fallbackLink": "Si el botón no funciona, copia y pega este enlace en tu navegador:",
|
||||
"ignoreNote": "Si no solicitaste este correo, puedes ignorarlo de forma segura."
|
||||
},
|
||||
"welcome": {
|
||||
"subject": "¡Bienvenido a Nomad Karaoke!",
|
||||
"welcomeGreeting": "¡Bienvenido a Nomad Karaoke!",
|
||||
"turnAnySong": "Convierte cualquier canción en un video de karaoke profesional en minutos.",
|
||||
"freeCreditsLabel": "Créditos gratis",
|
||||
"freeCreditsNote": "Cada crédito crea un video de karaoke profesional",
|
||||
"howItWorks": "Así es como funciona:",
|
||||
"step1Title": "1. Busca una canción",
|
||||
"step1Desc": "Ingresa el artista y el título, y encontraremos audio de alta calidad.",
|
||||
"step2Title": "2. Nuestro sistema hace su magia",
|
||||
"step2Desc": "Hacemos la separación vocal, transcribimos las letras y sincronizamos todo perfectamente.",
|
||||
"step3Title": "3. Revisa y personaliza",
|
||||
"step3Desc": "Ajusta las letras si es necesario, elige tu instrumental.",
|
||||
"step4Title": "4. Obtén tu video",
|
||||
"step4Desc": "Descarga tu video de karaoke en 4K o súbelo directamente a YouTube.",
|
||||
"feedbackBonus": "¡Completa 2 videos y gana 2 créditos gratis más compartiendo tus comentarios!",
|
||||
"getStartedButton": "Comenzar"
|
||||
},
|
||||
"creditsAdded": {
|
||||
"subject": "{credits} créditos agregados a tu cuenta de Nomad Karaoke",
|
||||
"greatNews": "¡Excelentes noticias!",
|
||||
"creditsAddedMessage": "Se han agregado {credits} créditos a tu cuenta.",
|
||||
"yourBalance": "Tu saldo:",
|
||||
"credits": "créditos",
|
||||
"eachCreditLets": "Cada crédito te permite crear un video de karaoke profesional con:",
|
||||
"featureVocalSeparation": "Separación vocal/instrumental impulsada por IA",
|
||||
"featureLyrics": "Letras sincronizadas con tiempo a nivel de palabra",
|
||||
"feature4k": "Salida de video en 4K",
|
||||
"featureYoutube": "Subida a YouTube",
|
||||
"createButton": "Crear karaoke ahora"
|
||||
},
|
||||
"jobCompletion": {
|
||||
"subjectWithBrand": "{brand_code}: {artist} - {title} (¡Tu video de karaoke está listo!)",
|
||||
"subject": "{artist} - {title} (¡Tu video de karaoke está listo!)",
|
||||
"subjectFallback": "¡Tu video de karaoke está listo!"
|
||||
},
|
||||
"youtubeUpload": {
|
||||
"subjectWithBrand": "{brand_code}: {artist} - {title} (¡Subida a YouTube lista!)",
|
||||
"subject": "{artist} - {title} (¡Subida a YouTube lista!)",
|
||||
"subjectFallback": "¡Tu subida a YouTube está lista!"
|
||||
},
|
||||
"actionReminder": {
|
||||
"lyricsSubject": "Acción requerida: Revisión de letras para {artist} - {title}",
|
||||
"lyricsSubjectFallback": "Acción requerida: Revisión de letras",
|
||||
"instrumentalSubject": "Acción requerida: Seleccionar instrumental para {artist} - {title}",
|
||||
"instrumentalSubjectFallback": "Acción requerida: Seleccionar instrumental",
|
||||
"audioEditSubject": "Acción requerida para {artist} - {title}",
|
||||
"audioEditSubjectFallback": "Acción requerida",
|
||||
"alertHeading": "¡Tu video de karaoke necesita tu atención!"
|
||||
},
|
||||
"reviewReminder": {
|
||||
"subject": "Recordatorio: Tu video de karaoke está esperando revisión — {artist} - {title}",
|
||||
"subjectFallback": "Recordatorio: Tu video de karaoke está esperando revisión",
|
||||
"alertHeading": "¡Tu video de karaoke te está esperando!",
|
||||
"reminderIntro": "Solo un recordatorio amistoso de que tu video de karaoke{song_name} está listo para revisión.",
|
||||
"reviewButton": "Revisar tu video",
|
||||
"reviewInstructions": "Durante la revisión, puedes comprobar que las letras son correctas y elegir tu pista instrumental preferida. ¡Normalmente solo toma unos minutos!",
|
||||
"helpOffer": "Si tienes algún problema con el proceso de revisión, solo responde a este correo y estaré encantado de ayudarte.",
|
||||
"expiryWarning": "Ten en cuenta: si la revisión no se completa dentro de las próximas 24 horas, el trabajo expirará automáticamente y se te reembolsará tu crédito."
|
||||
},
|
||||
"reviewExpired": {
|
||||
"subject": "Tu video de karaoke ha expirado — {artist} - {title}",
|
||||
"subjectFallback": "Tu video de karaoke ha expirado",
|
||||
"cancelNotice": "Tu video de karaoke{song_name} ha sido cancelado automáticamente porque la revisión no se completó en 48 horas.",
|
||||
"refundNotice": "No te preocupes — ¡tu crédito ha sido reembolsado! Tu saldo actual es de {credits_balance} {credits_word}.",
|
||||
"creditSingular": "crédito",
|
||||
"creditPlural": "créditos",
|
||||
"createNewPrompt": "Puedes crear un nuevo video de karaoke en cualquier momento usando tus créditos:",
|
||||
"createButton": "Crear nuevo video",
|
||||
"helpOffer": "Si tuviste algún problema con el proceso de revisión o necesitas ayuda, solo responde a este correo — ¡me encantaría ayudar!"
|
||||
},
|
||||
"creditDenied": {
|
||||
"subject": "Sobre tus créditos gratis de Nomad Karaoke",
|
||||
"greeting": "Hola,",
|
||||
"thankYou": "¡Gracias por registrarte en Nomad Karaoke!",
|
||||
"deniedMessage": "Lamentablemente, no pudimos otorgar tus {credit_type} gratis esta vez. Nuestro sistema detectó patrones que sugieren que esta podría no ser tu primera cuenta con nosotros, y cada trabajo de generación de karaoke nos cuesta dinero real en computación en la nube y tarifas de API.",
|
||||
"mistakeNote": "¡Entendemos totalmente si esto es un error! Si eres un usuario nuevo genuino, por favor solo responde a este correo y házselo saber a Andrew (el fundador). Él construyó este servicio y estará feliz de otorgarte algunos créditos gratis para que lo pruebes — solo te pide que a cambio proporciones comentarios honestos sobre la experiencia.",
|
||||
"buyPrompt": "Si deseas comenzar de inmediato, también puedes comprar créditos:",
|
||||
"buyButton": "Comprar créditos",
|
||||
"costNote": "Mantenemos los costos bajos para poder ofrecer el servicio de manera asequible, lo que significa que debemos tener cuidado con el abuso de créditos gratis. ¡Gracias por entender!",
|
||||
"welcomeCredits": "créditos de bienvenida",
|
||||
"feedbackCredits": "créditos de bonificación por comentarios"
|
||||
},
|
||||
"madeForYouConfirmation": {
|
||||
"subject": "Pedido confirmado: {artist} - {title} | Nomad Karaoke",
|
||||
"thankYou": "¡Gracias por tu pedido!",
|
||||
"orderDetails": "Detalles del pedido",
|
||||
"orderId": "ID del pedido:",
|
||||
"artist": "Artista:",
|
||||
"title": "Título:",
|
||||
"yourNotes": "Tus notas:",
|
||||
"deliveryTime": "Nuestro equipo creará tu video de karaoke personalizado en {hours} horas.",
|
||||
"deliveryNotice": "Recibirás un correo con enlaces de descarga tan pronto como tu video esté listo.",
|
||||
"noAction": "No se necesita ninguna acción — ¡relájate y nos encargaremos de todo!"
|
||||
},
|
||||
"shared": {
|
||||
"footerHelp": "Si algo no es perfecto, ¡solo responde a este correo y lo arreglaré!"
|
||||
},
|
||||
"templates": {
|
||||
"jobCompletion": {
|
||||
"greeting": "Hola {name},",
|
||||
"thanks": "¡Gracias por tu pedido!",
|
||||
"youtubeLink": "Aquí tienes el enlace del video de karaoke publicado en YouTube:",
|
||||
"dropboxIntro": "Aquí tienes la carpeta de Dropbox con todos los archivos terminados y archivos fuente, incluyendo:",
|
||||
"fileList": "- \"(Final Karaoke Lossless).mkv\": video de karaoke combinado en 4K H264 con audio FLAC sin pérdida\n- \"(Final Karaoke).mp4\": video de karaoke combinado con pantalla de título/pantalla final en 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": video de karaoke combinado en 720p H264/AAC (archivo más pequeño para sistemas más antiguos)\n- \"(With Vocals).mp4\": video para cantar junto en 4K H264/AAC con voces originales\n- \"(Karaoke).mov\": salida de video de karaoke de MidiCo (sin pantalla de título/pantalla final)\n- \"(Title).mov\"/\"(End).mov\": videos de tarjeta de título y pantalla final\n- \"(Final Karaoke CDG).zip\": formato CDG+MP3 para sistemas de karaoke más antiguos/comerciales\n- \"(Final Karaoke TXT).zip\": formato TXT+MP3 para Power Karaoke\n- stems/*.flac: varias pistas de audio instrumentales y vocales separadas en formato sin pérdida\n- lyrics/*.txt letras de canciones de varias fuentes en formato de texto sin formato",
|
||||
"fixOffer": "Avísame si algo no es perfecto y con gusto lo ajustaré / arreglaré, o si lo necesitas en cualquier otro formato, ¡probablemente pueda convertirlo para ti!",
|
||||
"feedbackRequest": "Si tienes un momento, realmente apreciaría tus comentarios (toma 2 minutos):",
|
||||
"signOff": "¡Gracias de nuevo y que tengas un gran día!\n-Andrew",
|
||||
"youtubeQueued": "Tu subida a YouTube está en cola y se procesará automáticamente. Recibirás un correo de seguimiento con el enlace en breve."
|
||||
},
|
||||
"actionLyrics": {
|
||||
"greeting": "Hola {name},",
|
||||
"ready": "¡Tu video de karaoke para \"{artist} - {title}\" está listo para revisión!",
|
||||
"instructions": "Nuestro sistema ha transcrito y sincronizado las letras, pero pueden necesitar algunas correcciones. También podrás seleccionar tu pista instrumental preferida (con o sin coros).",
|
||||
"reviewPrompt": "Por favor revisa tus letras y selecciona un instrumental:",
|
||||
"duration": "Esto normalmente toma solo unos minutos.",
|
||||
"signOff": "¡Gracias!\n-Andrew"
|
||||
},
|
||||
"actionInstrumental": {
|
||||
"greeting": "Hola {name},",
|
||||
"almostDone": "¡Tu video de karaoke para \"{artist} - {title}\" está casi listo!",
|
||||
"instructions": "Hemos separado el audio en diferentes versiones. Por favor selecciona qué pista instrumental te gustaría usar para el video final.",
|
||||
"selectPrompt": "Selecciona tu instrumental aquí:",
|
||||
"signOff": "¡Gracias!\n-Andrew"
|
||||
},
|
||||
"youtubeComplete": {
|
||||
"greeting": "Hola {name},",
|
||||
"greatNews": "¡Excelentes noticias! Tu video de karaoke para \"{artist} - {title}\" ha sido subido a YouTube:",
|
||||
"delayNote": "Esta subida se retrasó brevemente mientras nuestros sistemas procesaban otras subidas, pero todo está listo ahora.",
|
||||
"signOff": "¡Gracias!\n-Andrew"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,3 +25,18 @@ def get_version() -> str:
|
||||
|
||||
|
||||
VERSION = get_version()
|
||||
|
||||
# Build metadata — set by CI during deployment
|
||||
COMMIT_SHA = os.environ.get("COMMIT_SHA", "")
|
||||
PR_NUMBER = os.environ.get("PR_NUMBER", "")
|
||||
PR_TITLE = os.environ.get("PR_TITLE", "")
|
||||
STARTUP_TIME = None # Set on first import
|
||||
|
||||
|
||||
def _get_startup_time() -> str:
|
||||
"""Record when the backend process started (proxy for deploy time)."""
|
||||
from datetime import datetime, timezone
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
STARTUP_TIME = _get_startup_time()
|
||||
@@ -319,12 +319,17 @@ async def process_render_video(job_id: str) -> bool:
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
|
||||
# Same construction path as preview — prevents divergence
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
job_log.info("Applied user corrections via CorrectionOperations")
|
||||
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
|
||||
if isinstance(updated_data, dict) and "corrections" in updated_data:
|
||||
# Same construction path as preview — prevents divergence
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
job_log.info("Applied user corrections via CorrectionOperations")
|
||||
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
|
||||
else:
|
||||
job_log.warning("corrections_updated.json exists but has no 'corrections' key, using base result")
|
||||
logger.warning(f"Job {job_id}: corrections_updated.json has no 'corrections' key, using base result")
|
||||
correction_result = base_result
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
|
||||
@@ -385,7 +385,9 @@ async def _generate_title_screen(
|
||||
|
||||
logger.info(f"Job {job_id}: Title format - bg_image: {title_format.get('background_image')}, font: {title_format.get('font')}")
|
||||
|
||||
# Generate title screen (synchronous method)
|
||||
# Generate title screen images only (MOV video is generated on GCE encoding worker)
|
||||
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
|
||||
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
|
||||
video_generator.create_title_video(
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
@@ -393,12 +395,13 @@ async def _generate_title_screen(
|
||||
output_image_filepath_noext=output_image_filepath_noext,
|
||||
output_video_filepath=output_video_filepath,
|
||||
existing_title_image=title_format.get('existing_image'),
|
||||
intro_video_duration=intro_duration
|
||||
intro_video_duration=0,
|
||||
)
|
||||
|
||||
if os.path.exists(output_video_filepath):
|
||||
logger.info(f"Job {job_id}: Title screen generated at {output_video_filepath}")
|
||||
return output_video_filepath
|
||||
|
||||
output_png = f"{output_image_filepath_noext}.png"
|
||||
if os.path.exists(output_png):
|
||||
logger.info(f"Job {job_id}: Title screen image generated at {output_png}")
|
||||
return output_png
|
||||
else:
|
||||
logger.error(f"Job {job_id}: Title screen generation returned no file")
|
||||
return None
|
||||
@@ -457,7 +460,9 @@ async def _generate_end_screen(
|
||||
|
||||
logger.info(f"Job {job_id}: End format - bg_image: {end_format.get('background_image')}, font: {end_format.get('font')}")
|
||||
|
||||
# Generate end screen (synchronous method)
|
||||
# Generate end screen images only (MOV video is generated on GCE encoding worker)
|
||||
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
|
||||
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
|
||||
video_generator.create_end_video(
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
@@ -465,12 +470,13 @@ async def _generate_end_screen(
|
||||
output_image_filepath_noext=output_image_filepath_noext,
|
||||
output_video_filepath=output_video_filepath,
|
||||
existing_end_image=end_format.get('existing_image'),
|
||||
end_video_duration=end_duration
|
||||
end_video_duration=0,
|
||||
)
|
||||
|
||||
if os.path.exists(output_video_filepath):
|
||||
logger.info(f"Job {job_id}: End screen generated at {output_video_filepath}")
|
||||
return output_video_filepath
|
||||
|
||||
output_png = f"{output_image_filepath_noext}.png"
|
||||
if os.path.exists(output_png):
|
||||
logger.info(f"Job {job_id}: End screen image generated at {output_png}")
|
||||
return output_png
|
||||
else:
|
||||
logger.error(f"Job {job_id}: End screen generation returned no file")
|
||||
return None
|
||||
@@ -488,46 +494,34 @@ async def _upload_screens(
|
||||
end_screen_path: str
|
||||
) -> None:
|
||||
"""
|
||||
Upload title and end screens to GCS (video + images).
|
||||
|
||||
Upload title and end screen images to GCS.
|
||||
|
||||
Single Responsibility: Only handles uploads.
|
||||
|
||||
VideoGenerator creates .mov, .jpg, and .png files when configured with
|
||||
output_png=True and output_jpg=True. We upload all three formats
|
||||
for feature parity with the local CLI.
|
||||
|
||||
|
||||
VideoGenerator creates .jpg and .png files when configured with
|
||||
output_png=True and output_jpg=True. MOV video generation is handled
|
||||
by the GCE encoding worker (not Cloud Run) to avoid OOM with 4K H.264.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
job_manager: Job manager instance
|
||||
storage: Storage service instance
|
||||
title_screen_path: Path to title screen video (.mov)
|
||||
end_screen_path: Path to end screen video (.mov)
|
||||
title_screen_path: Path to title screen image (.png)
|
||||
end_screen_path: Path to end screen image (.png)
|
||||
"""
|
||||
# Upload title screen video
|
||||
title_gcs_path = f"jobs/{job_id}/screens/title.mov"
|
||||
title_url = storage.upload_file(title_screen_path, title_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'screens', 'title', title_url)
|
||||
logger.info(f"Job {job_id}: Uploaded title screen video")
|
||||
|
||||
# Upload title screen images (.jpg and .png - created by VideoGenerator)
|
||||
title_base = title_screen_path.replace('.mov', '')
|
||||
for ext, key in [('.jpg', 'title_jpg'), ('.png', 'title_png')]:
|
||||
# Upload title screen images (.png and .jpg)
|
||||
title_base = title_screen_path.replace('.png', '')
|
||||
for ext, key in [('.png', 'title_png'), ('.jpg', 'title_jpg')]:
|
||||
image_path = f"{title_base}{ext}"
|
||||
if os.path.exists(image_path):
|
||||
gcs_path = f"jobs/{job_id}/screens/title{ext}"
|
||||
url = storage.upload_file(image_path, gcs_path)
|
||||
job_manager.update_file_url(job_id, 'screens', key, url)
|
||||
logger.info(f"Job {job_id}: Uploaded title screen image ({ext})")
|
||||
|
||||
# Upload end screen video
|
||||
end_gcs_path = f"jobs/{job_id}/screens/end.mov"
|
||||
end_url = storage.upload_file(end_screen_path, end_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'screens', 'end', end_url)
|
||||
logger.info(f"Job {job_id}: Uploaded end screen video")
|
||||
|
||||
# Upload end screen images (.jpg and .png - created by VideoGenerator)
|
||||
end_base = end_screen_path.replace('.mov', '')
|
||||
for ext, key in [('.jpg', 'end_jpg'), ('.png', 'end_png')]:
|
||||
|
||||
# Upload end screen images (.png and .jpg)
|
||||
end_base = end_screen_path.replace('.png', '')
|
||||
for ext, key in [('.png', 'end_png'), ('.jpg', 'end_jpg')]:
|
||||
image_path = f"{end_base}{ext}"
|
||||
if os.path.exists(image_path):
|
||||
gcs_path = f"jobs/{job_id}/screens/end{ext}"
|
||||
|
||||
@@ -117,11 +117,21 @@ async def process_stale_reviews() -> Dict[str, Any]:
|
||||
user_service = get_user_service()
|
||||
credits_balance = user_service.check_credits(job.user_email)
|
||||
|
||||
# Look up user locale for email
|
||||
user_locale = "en"
|
||||
try:
|
||||
user = user_service.get_user(job.user_email)
|
||||
if user and user.locale:
|
||||
user_locale = user.locale
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
email_service.send_review_expired(
|
||||
to_email=job.user_email,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
credits_balance=credits_balance,
|
||||
locale=user_locale,
|
||||
)
|
||||
except Exception as email_err:
|
||||
logger.error(
|
||||
@@ -143,11 +153,23 @@ async def process_stale_reviews() -> Dict[str, Any]:
|
||||
# Send reminder email
|
||||
if job.user_email:
|
||||
try:
|
||||
# Look up user locale for email
|
||||
user_locale = "en"
|
||||
try:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
user = user_service.get_user(job.user_email)
|
||||
if user and user.locale:
|
||||
user_locale = user.locale
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
email_service.send_review_reminder(
|
||||
to_email=job.user_email,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
job_id=job.job_id,
|
||||
locale=user_locale,
|
||||
)
|
||||
except Exception as email_err:
|
||||
logger.error(
|
||||
|
||||
@@ -121,13 +121,12 @@ async def _encode_via_gce(
|
||||
|
||||
def progress_callback(progress: int):
|
||||
# Update job progress (encoding is 75-95% of total)
|
||||
# Use update_job instead of transition_to_state since job is already in ENCODING state
|
||||
scaled_progress = 75 + int(progress * 0.2) # Map 0-100 to 75-95
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.ENCODING,
|
||||
progress=scaled_progress,
|
||||
message=f"Encoding videos ({progress}%)"
|
||||
)
|
||||
job_manager.update_job(job_id, {
|
||||
'progress': scaled_progress,
|
||||
'message': f"Encoding videos ({progress}%)",
|
||||
})
|
||||
|
||||
try:
|
||||
# Submit and wait for encoding
|
||||
@@ -1232,9 +1231,11 @@ def _validate_prerequisites(job) -> bool:
|
||||
logger.error(f"Job {job.job_id}: Invalid instrumental selection: {instrumental_selection}")
|
||||
return False
|
||||
|
||||
# Check screens exist
|
||||
# Check screens exist (MOV or PNG — MOV is no longer uploaded, PNG is the new default)
|
||||
screens = job.file_urls.get('screens', {})
|
||||
if not screens.get('title') or not screens.get('end'):
|
||||
has_title = screens.get('title') or screens.get('title_png')
|
||||
has_end = screens.get('end') or screens.get('end_png')
|
||||
if not has_title or not has_end:
|
||||
logger.error(f"Job {job.job_id}: Missing title or end screen")
|
||||
return False
|
||||
|
||||
@@ -1288,19 +1289,24 @@ async def _setup_working_directory(
|
||||
|
||||
log_progress("Setting up working directory")
|
||||
|
||||
# Download title screen
|
||||
log_progress("Downloading title screen...")
|
||||
title_url = job.file_urls['screens']['title']
|
||||
title_path = os.path.join(temp_dir, f"{base_name} (Title).mov")
|
||||
storage.download_file(title_url, title_path)
|
||||
log_progress("Downloaded title screen")
|
||||
|
||||
# Download end screen
|
||||
log_progress("Downloading end screen...")
|
||||
end_url = job.file_urls['screens']['end']
|
||||
end_path = os.path.join(temp_dir, f"{base_name} (End).mov")
|
||||
storage.download_file(end_url, end_path)
|
||||
log_progress("Downloaded end screen")
|
||||
# Download title screen (PNG — MOV video is generated by the GCE encoding worker)
|
||||
screens = job.file_urls.get('screens', {})
|
||||
title_url = screens.get('title') or screens.get('title_png')
|
||||
if title_url:
|
||||
ext = os.path.splitext(title_url)[1] or '.png'
|
||||
title_path = os.path.join(temp_dir, f"{base_name} (Title){ext}")
|
||||
log_progress(f"Downloading title screen ({ext})...")
|
||||
storage.download_file(title_url, title_path)
|
||||
log_progress("Downloaded title screen")
|
||||
|
||||
# Download end screen (PNG — MOV video is generated by the GCE encoding worker)
|
||||
end_url = screens.get('end') or screens.get('end_png')
|
||||
if end_url:
|
||||
ext = os.path.splitext(end_url)[1] or '.png'
|
||||
end_path = os.path.join(temp_dir, f"{base_name} (End){ext}")
|
||||
log_progress(f"Downloading end screen ({ext})...")
|
||||
storage.download_file(end_url, end_path)
|
||||
log_progress("Downloaded end screen")
|
||||
|
||||
# Download lyrics video (with vocals) - this is the largest file, ~1-2GB
|
||||
log_progress("Downloading karaoke video (largest file, may take 1-2 minutes)...")
|
||||
|
||||
@@ -321,6 +321,9 @@ class VideoWorkerOrchestrator:
|
||||
base_name = f"{safe_artist} - {safe_title}"
|
||||
packaging_service = self._get_packaging_service()
|
||||
|
||||
# Track the actual MP3 path from CDG generation for use by TXT
|
||||
cdg_mp3_path = None
|
||||
|
||||
# Generate CDG package
|
||||
if self.config.enable_cdg:
|
||||
if self.config.lrc_has_countdown_padding:
|
||||
@@ -343,12 +346,15 @@ class VideoWorkerOrchestrator:
|
||||
f"{base_name} (Karaoke).cdg"
|
||||
)
|
||||
|
||||
# Pass sanitized artist/title to ensure filenames inside the ZIP
|
||||
# match what we expect (the CDG generator has its own sanitization
|
||||
# that may differ, e.g. not stripping trailing periods)
|
||||
zip_file, mp3_file, cdg_file = packaging_service.create_cdg_package(
|
||||
lrc_file=self.config.lrc_file_path,
|
||||
audio_file=self.config.instrumental_audio_path,
|
||||
output_zip_path=cdg_zip_path,
|
||||
artist=self.config.artist,
|
||||
title=self.config.title,
|
||||
artist=safe_artist,
|
||||
title=safe_title,
|
||||
output_mp3_path=mp3_path,
|
||||
output_cdg_path=cdg_path,
|
||||
lrc_has_countdown_padding=self.config.lrc_has_countdown_padding,
|
||||
@@ -356,6 +362,7 @@ class VideoWorkerOrchestrator:
|
||||
)
|
||||
|
||||
self.result.final_karaoke_cdg_zip = zip_file
|
||||
cdg_mp3_path = mp3_file
|
||||
self.job_log.info(f"CDG package created: {zip_file}")
|
||||
|
||||
except Exception as e:
|
||||
@@ -366,8 +373,9 @@ class VideoWorkerOrchestrator:
|
||||
if self.config.enable_txt:
|
||||
self.job_log.info("Generating TXT package")
|
||||
try:
|
||||
# TXT package needs MP3 file (from CDG generation or create it)
|
||||
mp3_path = os.path.join(
|
||||
# TXT package needs MP3 file from CDG generation.
|
||||
# Prefer the actual path returned by CDG, fall back to constructed path.
|
||||
mp3_path = cdg_mp3_path or os.path.join(
|
||||
self.config.output_dir,
|
||||
f"{base_name} (Karaoke).mp3"
|
||||
)
|
||||
@@ -836,6 +844,22 @@ class VideoWorkerOrchestrator:
|
||||
# Never fail the pipeline for validation
|
||||
|
||||
|
||||
def _screen_ext(job, screen_type: str) -> str:
|
||||
"""Get the file extension for a screen (title/end) based on what's in GCS.
|
||||
|
||||
New jobs have only PNG (MOV is generated by GCE encoding worker).
|
||||
Legacy jobs may still have MOV uploaded by the old screens_worker.
|
||||
"""
|
||||
screens = job.file_urls.get('screens', {})
|
||||
# Check for MOV first (legacy), then fall back to PNG (new)
|
||||
url = screens.get(screen_type) or screens.get(f'{screen_type}_png')
|
||||
if url:
|
||||
ext = os.path.splitext(url)[1]
|
||||
if ext:
|
||||
return ext
|
||||
return '.png'
|
||||
|
||||
|
||||
def create_orchestrator_config_from_job(
|
||||
job,
|
||||
temp_dir: str,
|
||||
@@ -893,12 +917,12 @@ def create_orchestrator_config_from_job(
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
|
||||
# Input files
|
||||
title_video_path=os.path.join(temp_dir, f"{base_name} (Title).mov"),
|
||||
# Input files — use actual extension from GCS (PNG for new jobs, MOV for legacy)
|
||||
title_video_path=os.path.join(temp_dir, f"{base_name} (Title){_screen_ext(job, 'title')}"),
|
||||
# Use actual extension from GCS path (typically .mkv) instead of hardcoding .mov
|
||||
karaoke_video_path=os.path.join(temp_dir, f"{base_name} (With Vocals){os.path.splitext(job.file_urls.get('videos', {}).get('with_vocals', '.mkv'))[1] or '.mkv'}"),
|
||||
instrumental_audio_path=instrumental_path,
|
||||
end_video_path=os.path.join(temp_dir, f"{base_name} (End).mov"),
|
||||
end_video_path=os.path.join(temp_dir, f"{base_name} (End){_screen_ext(job, 'end')}"),
|
||||
lrc_file_path=os.path.join(temp_dir, f"{base_name} (Karaoke).lrc"),
|
||||
title_jpg_path=os.path.join(temp_dir, f"{base_name} (Title).jpg"),
|
||||
|
||||
|
||||
@@ -1055,3 +1055,34 @@ For this bug, the missing test was: "does `transcribe_lyrics()` return `lyrics_d
|
||||
|
||||
**Key insight:** Background cron jobs need monitoring for auth failures — a 401 from a scheduler is silent by default. When adding new Cloud Scheduler endpoints, verify the auth flow end-to-end (check Cloud Logging for 200s after deployment). Don't assume OIDC "just works" with custom auth middleware — Cloud Tasks uses `X-Admin-Token` (custom header) for a reason, while Cloud Scheduler only sends OIDC.
|
||||
|
||||
### GCE Disk Cache Must Validate Content, Not Just URI (Mar 2026)
|
||||
|
||||
**Problem:** The GCE encoding worker's style asset disk cache (`/var/cache/karaoke-gen/styles/`) keyed on `SHA-256(GCS URI)`. When a file at a GCS path was replaced with different content (e.g., fixing corrupt 106-byte placeholder PNGs with correct 2.8MB files), the cache served the stale version indefinitely.
|
||||
|
||||
**Fix:** On cache hit, do a lightweight `blob.reload()` (HEAD request) to get the GCS object's current size. Compare with cached file size — re-download on mismatch. One metadata call per cache hit is a small price vs serving corrupt assets.
|
||||
|
||||
**Key insight:** Any local disk cache of remote objects needs a staleness check. URI-only cache keys assume content is immutable at that path — which is rarely guaranteed in GCS/S3. Size is the cheapest validation; for stronger guarantees, compare ETags or generation numbers.
|
||||
|
||||
### Don't Write Empty Sentinel Files to GCS (Mar 2026)
|
||||
|
||||
**Problem:** The review complete endpoint wrote `corrections_updated.json` to GCS even when no corrections were provided (e.g., admin API reset + complete without correction data). It wrote `{}` (empty dict). Downstream, render workers check `file_exists("corrections_updated.json")` — if present, they download and pass it to `CorrectionOperations.update_correction_result_with_data()` which does `updated_data["corrections"]`, causing `KeyError`.
|
||||
|
||||
**Fix:** (1) Root cause: Don't write `corrections_updated.json` unless the payload actually contains a `"corrections"` key. (2) Defensive: Both GCE and Cloud Run workers validate the downloaded JSON has the expected structure before processing, falling back to base result if not.
|
||||
|
||||
**Key insight:** When a file's existence is used as a boolean signal ("corrections were updated"), never write it with empty/invalid content. The existence check and content processing must agree on what constitutes a valid file. Apply defense in depth: fix the writer AND validate in readers.
|
||||
|
||||
### i18n: Keep Providers in Root Layout When Admin Pages Exist (Apr 2026)
|
||||
|
||||
**Problem:** The Phase 1/2 i18n pattern (public-website, karaoke-decide) stripped the root `app/layout.tsx` bare and moved all providers into `app/[locale]/layout.tsx`. This doesn't work for karaoke-gen because admin pages at `app/admin/` sit outside the `[locale]` route segment and need ThemeProvider/TenantProvider.
|
||||
|
||||
**Fix:** Keep shared providers (ThemeProvider, TenantProvider, ImpersonationBannerWrapper, ServiceWorkerRegistration, GoogleAnalytics) in root layout. Only add NextIntlClientProvider to `[locale]/layout.tsx`. Admin pages inherit root providers without locale context.
|
||||
|
||||
**Key insight:** When adding `[locale]` routing to a project with routes that should NOT be locale-prefixed (admin, API, etc.), don't blindly follow the "strip root layout" pattern. Keep shared providers in root so all route segments can access them.
|
||||
|
||||
### i18n: Mock next-intl in Jest by Loading en.json (Apr 2026)
|
||||
|
||||
**Problem:** Adding `useTranslations` to components caused 27 test suites to fail — Jest can't handle ESM exports from `next-intl`, and even after fixing that, tests that assert on English text (e.g., `screen.getByText("Review Lyrics")`) fail because the mock returns translation keys instead of English strings.
|
||||
|
||||
**Fix:** Mock `next-intl` in `jest.setup.js` with a function that loads the actual `messages/en.json` and resolves dotted key paths to real English strings. Tests see the same text users see, no test assertions need updating. The mock supports interpolation (`{count}`, ICU plurals).
|
||||
|
||||
**Key insight:** For i18n refactors, make the test mock return real translations, not keys. This lets existing tests validate that the i18n wiring produces correct output without changing every assertion. The mock is ~20 lines and eliminates hundreds of test updates.
|
||||
@@ -36,6 +36,7 @@
|
||||
| **Community version detection** | Working (via karaokenerds.com) |
|
||||
| **Review session backup/restore** | Working (auto-save + restore UI) |
|
||||
| **Review reminder & auto-expiry** | Working (24h reminder, 48h cancel + refund) |
|
||||
| **i18n / Multilingual (frontend)** | Working (next-intl, en/es/de, 1062 strings, [locale] routing) |
|
||||
|
||||
## Known Issues
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# Plan: Move Screen Video Generation to GCE Encoding Worker
|
||||
|
||||
**Created:** 2026-03-31
|
||||
**Branch:** feat/sess-20260331-1619-investigate-render-failure
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Screen video generation (title.mov, end.mov) currently runs FFmpeg in the Cloud Run API container via `VideoGenerator._create_video_from_image()`. After PR #640 right-sized Cloud Run to 2CPU/2Gi, the 4K H.264 encoding OOMs silently (producing 36-byte empty MOV shells). This breaks all downstream encoding since `encode_lossless_mp4` can't concatenate corrupt inputs.
|
||||
|
||||
Fix: Stop generating MOV in screens_worker. Generate them on the GCE encoding worker (which has adequate resources) just before the encoding step.
|
||||
|
||||
## Root Cause
|
||||
|
||||
- `VideoGenerator._create_video_from_image()` uses `os.system()` — silently swallows FFmpeg failures
|
||||
- 4K H.264 encoding needs more than 2Gi RAM
|
||||
- screens_worker checks `os.path.exists(output_video_filepath)` — the 36-byte shell passes this check
|
||||
- All jobs since the Cloud Run right-sizing (March 31) are affected
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### 1. screens_worker.py — Stop generating MOV videos
|
||||
|
||||
**Changes:**
|
||||
- In `_generate_title_screen`: pass `intro_video_duration=0` to skip MOV creation, return PNG path
|
||||
- In `_generate_end_screen`: pass `end_video_duration=0` to skip MOV creation, return PNG path
|
||||
- In `_upload_screens`: only upload PNG and JPG (remove MOV upload logic)
|
||||
- Update function return types/docstrings to reflect image-only output
|
||||
|
||||
**Why duration=0 works:** `VideoGenerator._save_output_files` already has `if duration > 0:` guard around `_create_video_from_image`.
|
||||
|
||||
### 2. gce_encoding/main.py — Generate MOV from PNG before encoding
|
||||
|
||||
**Changes in `run_encoding()`:**
|
||||
- After `find_file` for title/end videos, check if they're missing or invalid (< 1KB)
|
||||
- If missing/invalid, look for corresponding PNG: `screens/title.png`, `screens/end.png`
|
||||
- Generate MOV from PNG using `subprocess.run()` with proper error handling
|
||||
- Use same FFmpeg command as `_create_video_from_image` but with error checking
|
||||
- Log clearly when generating MOV from PNG vs using existing MOV
|
||||
|
||||
**Backwards compatible:** Old jobs with valid MOVs still work. New jobs with only PNGs get MOVs generated on GCE.
|
||||
|
||||
### 3. Fix `_create_video_from_image` error handling (defensive)
|
||||
|
||||
**Changes in `karaoke_gen/video_generator.py`:**
|
||||
- Replace `os.system()` with `subprocess.run(check=True)`
|
||||
- Log stderr on failure
|
||||
- This protects the local CLI path too
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/workers/screens_worker.py` | Modify | Stop generating MOV, return/upload images only |
|
||||
| `backend/services/gce_encoding/main.py` | Modify | Generate MOV from PNG in `run_encoding()` |
|
||||
| `karaoke_gen/video_generator.py` | Modify | Replace `os.system()` with `subprocess.run()` |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- Unit tests for GCE worker MOV generation helper
|
||||
- Verify existing encoding tests still pass
|
||||
- Manually re-run job f0d51a0a after deploy to confirm fix
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Revert the 3 files. The old behavior (generating MOV in Cloud Run) would still fail with 2Gi, but increasing memory to 4Gi would restore it.
|
||||
@@ -0,0 +1,215 @@
|
||||
# Plan: Karaoke-Gen i18n Multilingual (Phase 3)
|
||||
|
||||
**Created:** 2026-04-03
|
||||
**Branch:** `feat/sess-20260403-1115-i18n-multilingual`
|
||||
**Worktree:** `/Users/andrew/Projects/nomadkaraoke/karaoke-gen-i18n-multilingual`
|
||||
**Status:** Draft
|
||||
|
||||
## Context
|
||||
|
||||
This is Phase 3 of the i18n multilingual initiative. Phases 1+2 shipped successfully for public-website (205 strings) and karaoke-decide (811 frontend + 47 backend strings). The patterns are proven — we're replicating them in karaoke-gen, the most complex project (many frontend surfaces + multi-layered backend).
|
||||
|
||||
## Scope Decisions
|
||||
|
||||
| Decision | Choice | Rationale |
|
||||
|----------|--------|-----------|
|
||||
| Admin pages (`/admin/*`) | **Exclude** from i18n | Internal-only, ~30% more strings for zero user impact. Can add later. |
|
||||
| Tenant default locale | **Out of scope** | Orthogonal to user locale; user's localStorage/browser detection suffices |
|
||||
| Hash routing compatibility | **No conflict** | Hash (`#/jobId/review`) is client-side only, preserved across locale changes |
|
||||
| Providers in root layout | **Keep in root** | Unlike Phase 1/2, karaoke-gen has admin pages outside `[locale]` that need ThemeProvider/TenantProvider. Only NextIntlClientProvider moves to `[locale]/layout.tsx`. |
|
||||
|
||||
## Architecture: Frontend Key Difference from Phase 1/2
|
||||
|
||||
karaoke-gen has admin pages at `app/admin/` that must NOT be under `[locale]` routing. So:
|
||||
|
||||
- **Root `app/layout.tsx`**: Keeps `<html>`, `<body>`, ThemeProvider, TenantProvider, ImpersonationBannerWrapper, ServiceWorkerRegistration, GoogleAnalytics. Remove hardcoded `lang="en"`.
|
||||
- **`app/[locale]/layout.tsx`**: Adds NextIntlClientProvider + inline `<script>` to set `document.documentElement.lang`. Uses `generateStaticParams` for locale pre-rendering.
|
||||
- **`app/admin/layout.tsx`**: Unchanged — inherits root providers, no locale context needed.
|
||||
|
||||
## PR Breakdown (4 PRs)
|
||||
|
||||
### PR 1: Frontend Infrastructure + Page Migration (~250 strings)
|
||||
**Goal:** Set up next-intl, `[locale]` routing, move all user-facing pages under locale prefix.
|
||||
|
||||
**Create:**
|
||||
- `frontend/i18n/routing.ts` — locale config, `createNavigation`
|
||||
- `frontend/i18n/request.ts` — message loading for next-intl
|
||||
- `frontend/messages/en.json` — all user-facing strings (namespaced: `common`, `landing`, `dashboard`, `auth`, `payment`, `jobFlow`, `lyricsReview`, `instrumentalReview`, `audioEditor`, `audioSearch`, `credits`, `feedback`, `push`, `status`)
|
||||
- `frontend/app/[locale]/layout.tsx` — NextIntlClientProvider, `generateStaticParams`, lang script
|
||||
- `frontend/app/[locale]/page.tsx` — landing page (moved from `app/page.tsx`)
|
||||
- `frontend/app/[locale]/app/page.tsx` — dashboard
|
||||
- `frontend/app/[locale]/app/jobs/[[...slug]]/page.tsx` — job router
|
||||
- `frontend/app/[locale]/app/jobs/[[...slug]]/client.tsx` — job client component
|
||||
- `frontend/app/[locale]/auth/verify/page.tsx` — magic link verify
|
||||
- `frontend/app/[locale]/payment/success/page.tsx` — payment success
|
||||
- `frontend/app/[locale]/order/success/page.tsx` — order success
|
||||
- `frontend/components/LanguageSwitcher.tsx` — dropdown in header
|
||||
- `frontend/scripts/translate.py` — copy from karaoke-decide
|
||||
- `frontend/scripts/glossary.json` — extended with karaoke-gen terms
|
||||
|
||||
**Modify:**
|
||||
- `frontend/app/layout.tsx` — remove `lang="en"` from `<html>`, keep all providers
|
||||
- `frontend/app/page.tsx` — replace with client-side locale redirect (localStorage > navigator.language > 'en')
|
||||
- `frontend/next.config.mjs` — wrap with `createNextIntlPlugin` from `next-intl/plugin`
|
||||
- `frontend/package.json` — add `next-intl`
|
||||
- `frontend/lib/api.ts` — add `Accept-Language` header via `getLocaleFromPath()`
|
||||
- `frontend/components/app-header.tsx` — add LanguageSwitcher
|
||||
|
||||
**String extraction in this PR:** Extract ALL user-facing strings from ALL components (landing, dashboard, job flow, lyrics review, instrumental review, audio editor, audio search, credits, feedback, push, auth, status, common). Write the complete `en.json` upfront so PR 2 is just wiring `useTranslations()` into components.
|
||||
|
||||
**Why extract all strings in PR 1?** The en.json file defines the complete translation surface. Having it complete lets us run translate.py once to generate es.json/de.json, and subsequent PRs just add `useTranslations()` calls without needing to re-translate.
|
||||
|
||||
### PR 2: Component i18n Wiring (~50 components)
|
||||
**Goal:** Wire `useTranslations()` into all user-facing components.
|
||||
|
||||
**Components to convert (by area):**
|
||||
|
||||
*Job creation (~14 files):*
|
||||
- `components/job/GuidedJobFlow.tsx`, `TenantJobFlow.tsx`
|
||||
- `components/job/steps/SongInfoStep.tsx`, `AudioSourceStep.tsx`, `CustomizeStep.tsx`, `VisibilityStep.tsx`
|
||||
- `components/job/JobCard.tsx`, `JobActions.tsx`, `OutputLinks.tsx`, `JobSubmission.tsx`
|
||||
- `components/job/ThemeSelector.tsx`, `TitleCardPreview.tsx`, `EditTrackModal.tsx`, `CommunityVersionBanner.tsx`
|
||||
|
||||
*Lyrics review (~20 files):*
|
||||
- `components/lyrics-review/Header.tsx`, `LyricsAnalyzer.tsx`, `GuidancePanel.tsx`, `TranscriptionView.tsx`
|
||||
- `components/lyrics-review/EditActionBar.tsx`, `EditFeedbackBar.tsx`, `EditWordList.tsx`
|
||||
- `components/lyrics-review/ModeSelector.tsx`, `ReferenceView.tsx`, `ReferenceEmptyState.tsx`
|
||||
- `components/lyrics-review/SessionRestoreDialog.tsx`, `PreviewVideoSection.tsx`, `GapNavigator.tsx`
|
||||
- `components/lyrics-review/modals/*.tsx` (8 files)
|
||||
- `components/lyrics-review/synchronizer/*.tsx` (4 files)
|
||||
|
||||
*Instrumental review (~7 files):*
|
||||
- `components/instrumental-review/InstrumentalSelector.tsx`, `InstrumentalSelectorEmbedded.tsx`
|
||||
- `components/instrumental-review/InstrumentalGuidancePanel.tsx`, `SelectionOptions.tsx`
|
||||
- `components/instrumental-review/StemComparison.tsx`, `CustomUpload.tsx`, `MuteRegionEditor.tsx`
|
||||
|
||||
*Other (~10 files):*
|
||||
- `components/audio-editor/AudioEditor.tsx`, `AudioEditRestoreDialog.tsx`
|
||||
- `components/audio-search/AudioSearchDialog.tsx`
|
||||
- `components/credits/BuyCreditsDialog.tsx`
|
||||
- `components/feedback/FeedbackDialog.tsx`
|
||||
- `components/auth/AuthDialog.tsx`, `AuthStatus.tsx`
|
||||
- `components/push-notification-prompt.tsx`, `push-settings.tsx`
|
||||
- `components/TenantLandingPage.tsx`, `WarmingUpLoader.tsx`, `status-badge.tsx`
|
||||
|
||||
**Pattern:** Each component gets `const t = useTranslations('namespace')` and replaces hardcoded strings with `t('key')`.
|
||||
|
||||
### PR 3: Backend i18n Infrastructure + Route Localization (~150-200 strings)
|
||||
**Goal:** Add `backend/i18n.py`, translation files, convert all route files.
|
||||
|
||||
**Create:**
|
||||
- `backend/i18n.py` — `t(locale, key, **kwargs)`, `get_locale_from_request(request)`, `get_locale_prefix(locale)` (copy from karaoke-decide)
|
||||
- `backend/translations/en.json` — all backend strings
|
||||
- `backend/translations/es.json`, `de.json` — via translate.py
|
||||
|
||||
**Modify:**
|
||||
- `backend/models/user.py` — add `locale: Optional[str] = None` to User model
|
||||
- `backend/services/user_service.py` — persist locale on create/update
|
||||
- All user-facing route files (10 files): `auth.py`, `jobs.py`, `review.py`, `audio_search.py`, `users.py`, `push.py`, `file_upload.py`, `catalog.py`, `themes.py`, `tenant.py`
|
||||
- `backend/main.py` — localize `InsufficientCreditsError` handler
|
||||
|
||||
**Pattern:**
|
||||
```python
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
locale = get_locale_from_request(request)
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
```
|
||||
|
||||
### PR 4: Email + Push Notification Localization (~50-80 strings)
|
||||
**Goal:** Localize all 5 email types and 3 push notification types.
|
||||
|
||||
**Modify:**
|
||||
- `backend/services/email_service.py` — pass locale to all email methods, use `t()` for subjects/headings/buttons
|
||||
- `backend/services/template_service.py` — locale-aware GCS template paths (`templates/{locale}/...`)
|
||||
- `backend/services/job_notification_service.py` — fetch user locale, pass to email service; localize URL prefixes
|
||||
- `backend/services/push_notification_service.py` — locale-aware notification titles/bodies
|
||||
|
||||
**Add to translations:** `emails.*` and `push.*` namespaces in backend translation files.
|
||||
|
||||
## Implementation Order
|
||||
|
||||
```
|
||||
PR 1 (Frontend Infra) ──→ PR 2 (Component Wiring)
|
||||
│
|
||||
└──→ PR 3 (Backend Infra) ──→ PR 4 (Emails + Push)
|
||||
```
|
||||
|
||||
PRs 2 and 3 can be developed in parallel after PR 1 lands.
|
||||
|
||||
## Key Technical Details
|
||||
|
||||
### Accept-Language Header (frontend → backend)
|
||||
```typescript
|
||||
// frontend/lib/api.ts
|
||||
function getLocaleFromPath(): string {
|
||||
if (typeof window === 'undefined') return 'en';
|
||||
const match = window.location.pathname.match(/^\/(en|es|de)\//);
|
||||
return match ? match[1] : 'en';
|
||||
}
|
||||
```
|
||||
Added to `getAuthHeaders()` so every API call includes locale.
|
||||
|
||||
### User Locale Persistence
|
||||
- **Frontend:** `localStorage.setItem('locale', newLocale)` on language switch
|
||||
- **Backend:** `User.locale` field in Firestore (`gen_users` collection), set on magic link verify from `Accept-Language`, updated on explicit language change
|
||||
- **Emails/push:** Read `User.locale` from Firestore, fallback to `'en'`
|
||||
|
||||
### Static Export with Locale Routing
|
||||
`generateStaticParams` on `[locale]/layout.tsx` returns `[{locale:'en'},{locale:'es'},{locale:'de'}]`. Combined with `output: 'export'` and `trailingSlash: true`, Next.js generates `/en/`, `/es/`, `/de/` directories — compatible with Cloudflare Pages.
|
||||
|
||||
### Backend-Generated URLs
|
||||
All backend URLs that point to frontend must include locale prefix:
|
||||
```python
|
||||
f"{frontend_url}/{get_locale_prefix(user_locale)}/app/jobs#{job_id}/review"
|
||||
```
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
- **Backend:** Test `i18n.py` — `t()` function with valid/invalid keys, interpolation, fallback to English, unsupported locale handling
|
||||
- **Backend:** Test locale extraction from `Accept-Language` header
|
||||
- **Frontend:** Jest tests for `getLocaleFromPath()` helper
|
||||
|
||||
### Integration Tests
|
||||
- **Backend:** Verify routes return localized error messages when `Accept-Language: es` is sent
|
||||
- **Backend:** Verify emails are sent with correct locale strings
|
||||
|
||||
### E2E Tests (Playwright)
|
||||
- **Production E2E:** Navigate to `/es/` and `/de/`, verify page renders in correct language
|
||||
- **Production E2E:** Switch language via LanguageSwitcher, verify localStorage persistence and page reload
|
||||
- **Production E2E:** Verify root `/` redirects to correct locale based on browser language
|
||||
|
||||
### Manual Verification
|
||||
Convert to automated E2E tests per TESTING.md guidelines:
|
||||
- Verify static export generates all 3 locale directories
|
||||
- Verify admin pages still work at `/admin/` (no locale prefix)
|
||||
- Verify tenant subdomains work with locale routing
|
||||
|
||||
## Estimated String Counts
|
||||
|
||||
| Area | Strings | PR |
|
||||
|------|---------|-----|
|
||||
| Frontend: landing, dashboard, auth, payment | ~100 | 1 |
|
||||
| Frontend: common (buttons, errors, loading) | ~50 | 1 |
|
||||
| Frontend: job flow | ~80 | 1 (extracted), 2 (wired) |
|
||||
| Frontend: lyrics review | ~120 | 1 (extracted), 2 (wired) |
|
||||
| Frontend: instrumental review | ~40 | 1 (extracted), 2 (wired) |
|
||||
| Frontend: other components | ~60 | 1 (extracted), 2 (wired) |
|
||||
| **Frontend total** | **~450-550** | |
|
||||
| Backend: route messages | ~150-200 | 3 |
|
||||
| Backend: emails + push | ~50-80 | 4 |
|
||||
| **Backend total** | **~200-280** | |
|
||||
| **Grand total** | **~650-830** | |
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should we store locale preference in a cookie too (for pre-auth pages where we don't have a user document)?
|
||||
- [ ] The landing page (`app/page.tsx`) currently has a lot of marketing content — confirm it should be fully translated vs. just the chrome
|
||||
- [ ] Any karaoke-gen-specific glossary terms beyond what's in karaoke-decide's glossary? (e.g., "stem separation", "instrumental track", "lyrics review")
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Each PR is independently revertable:
|
||||
- PR 1: Revert moves pages back to non-locale paths. Admin pages unaffected.
|
||||
- PR 3: Revert removes `i18n.py` and translation files. Routes return English strings.
|
||||
- Cloudflare Pages: Previous deployment is one click to restore.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,213 @@
|
||||
# Service Health Status Modal — Design Spec
|
||||
|
||||
## Overview
|
||||
|
||||
Replace the static footer version/status line with a clickable element that opens a modal showing detailed system status. Non-admin users see service health, versions, and deploy info. Admin users additionally see blue-green encoder deployment details. Each service links to the PR that produced its current version.
|
||||
|
||||
## Footer Changes
|
||||
|
||||
The existing footer line (`Frontend: v0.155.3 | Backend: v0.155.3 | ● Encoder: v0.155.3 | ...`) becomes a single clickable element. On hover: `cursor: pointer`, slight opacity change. No other visual changes to the footer layout.
|
||||
|
||||
Clicking anywhere on the version/status line opens the modal.
|
||||
|
||||
## Modal — Public View (everyone)
|
||||
|
||||
### Layout
|
||||
|
||||
- Standard modal: dark backdrop (click to dismiss), X close button, title "System Status"
|
||||
- Responsive card grid: 2 columns on desktop, 1 column on mobile
|
||||
- 5 service cards: **Frontend**, **Backend**, **Encoder**, **Flacfetch**, **Separator**
|
||||
|
||||
### Card Contents
|
||||
|
||||
Each card shows:
|
||||
|
||||
| Element | Example |
|
||||
|---------|---------|
|
||||
| Status indicator | Green dot (●) + "Healthy" or red dot (○) + "Offline" |
|
||||
| Version | `v0.155.3` |
|
||||
| Deploy time | "Deployed 2 hours ago" (relative) |
|
||||
| Latest change | `#644 — fix blue-green deploy` (clickable link to GitHub PR) |
|
||||
|
||||
The "Latest change" line links to the GitHub PR that produced the currently deployed version. If unavailable, this line is omitted.
|
||||
|
||||
## Modal — Admin View (additional detail)
|
||||
|
||||
When the user has an admin token (stored in localStorage from login), the modal request includes it and the response includes extra data.
|
||||
|
||||
### Encoder Blue-Green Section
|
||||
|
||||
Inside the Encoder card, below the standard info, an expandable section labeled "Blue-Green Deployment" shows:
|
||||
|
||||
- **Two side-by-side mini-cards**: Primary (green-tinted border) and Secondary (muted/grey)
|
||||
- Each mini-card shows:
|
||||
- VM name (e.g., `encoding-worker-b`)
|
||||
- Version (e.g., `v0.155.3`)
|
||||
- Role label: "PRIMARY" (green) or "SECONDARY (stopped)" (muted)
|
||||
- **Deploy status line**: "Last swap: 2 hours ago" or "⚠ Deploy in progress..." (amber)
|
||||
- **Active jobs**: count on primary, if > 0
|
||||
|
||||
### Admin Detail on Other Cards
|
||||
|
||||
For Backend, Flacfetch, and Separator cards, admin view additionally shows:
|
||||
- Error message if status is offline (from the health check error field)
|
||||
|
||||
No extra admin detail needed for Frontend (it's a static site).
|
||||
|
||||
## New Backend Endpoint
|
||||
|
||||
### `GET /api/health/system-status`
|
||||
|
||||
Single endpoint that aggregates all service health data. Avoids the current pattern of 4 separate fetches.
|
||||
|
||||
**Authentication**: Optional `X-Admin-Token` header. If valid admin token, response includes `admin_details`. If omitted or invalid, those fields are absent.
|
||||
|
||||
**Response (public fields)**:
|
||||
|
||||
```json
|
||||
{
|
||||
"services": {
|
||||
"frontend": {
|
||||
"status": "ok",
|
||||
"version": "0.155.3",
|
||||
"deployed_at": "2026-03-31T18:10:00Z",
|
||||
"commit_sha": "8e2a949a",
|
||||
"pr_number": 644,
|
||||
"pr_title": "fix: complete blue-green deploy test payload and status check"
|
||||
},
|
||||
"backend": {
|
||||
"status": "ok",
|
||||
"version": "0.155.3",
|
||||
"deployed_at": "2026-03-31T18:10:00Z",
|
||||
"commit_sha": "8e2a949a",
|
||||
"pr_number": 644,
|
||||
"pr_title": "fix: complete blue-green deploy test payload and status check"
|
||||
},
|
||||
"encoder": {
|
||||
"status": "ok",
|
||||
"version": "0.155.3",
|
||||
"deployed_at": "2026-03-31T18:10:00Z",
|
||||
"active_jobs": 0
|
||||
},
|
||||
"flacfetch": {
|
||||
"status": "ok",
|
||||
"version": "0.19.1"
|
||||
},
|
||||
"separator": {
|
||||
"status": "ok",
|
||||
"version": "0.4.3"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Additional fields when admin token is valid**:
|
||||
|
||||
```json
|
||||
{
|
||||
"services": {
|
||||
"encoder": {
|
||||
"admin_details": {
|
||||
"primary_vm": "encoding-worker-b",
|
||||
"primary_ip": "34.10.189.118",
|
||||
"primary_version": "0.155.3",
|
||||
"primary_deployed_at": "2026-03-31T18:10:00Z",
|
||||
"secondary_vm": "encoding-worker-a",
|
||||
"secondary_ip": "34.57.78.246",
|
||||
"secondary_version": "0.155.2",
|
||||
"secondary_deployed_at": "2026-03-29T14:00:00Z",
|
||||
"last_swap_at": "2026-03-31T18:10:00Z",
|
||||
"deploy_in_progress": false,
|
||||
"active_jobs": 0,
|
||||
"queue_length": 0
|
||||
}
|
||||
},
|
||||
"flacfetch": {
|
||||
"admin_details": {
|
||||
"error": null
|
||||
}
|
||||
},
|
||||
"separator": {
|
||||
"admin_details": {
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Build Metadata — Git SHA and PR Info
|
||||
|
||||
Currently no git metadata is baked into builds. We need to add this.
|
||||
|
||||
### CI Changes (`.github/workflows/ci.yml`)
|
||||
|
||||
Add a step early in the deploy job that captures git info:
|
||||
|
||||
```yaml
|
||||
- name: Capture build metadata
|
||||
id: build-meta
|
||||
run: |
|
||||
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
|
||||
# For merge commits, extract PR number from commit message
|
||||
PR_NUM=$(git log -1 --format=%s | grep -oP '#\K[0-9]+' | head -1)
|
||||
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
```
|
||||
|
||||
### Where metadata is stored
|
||||
|
||||
| Service | Storage mechanism |
|
||||
|---------|------------------|
|
||||
| **Frontend** | New env vars `NEXT_PUBLIC_COMMIT_SHA`, `NEXT_PUBLIC_PR_NUMBER`, `NEXT_PUBLIC_PR_TITLE`, `NEXT_PUBLIC_BUILD_TIME` set in CI before `npm run build`. Baked into the static bundle at build time via `next.config.mjs`. The `deployed_at` for frontend is the build timestamp (close enough to deploy time for Cloudflare Pages). |
|
||||
| **Backend** | New env vars `COMMIT_SHA`, `PR_NUMBER`, `PR_TITLE` set on the Cloud Run service. Read at runtime in `backend/version.py`. |
|
||||
| **Encoder** | Written to GCS version manifest alongside the existing `version.txt`. The GCE worker reads it on startup and includes in `/health` response. |
|
||||
| **Flacfetch / Separator** | These are separate repos with their own CI. PR info can be added later — for now, omit the "Latest change" line for these services. |
|
||||
|
||||
### GitHub PR Link Format
|
||||
|
||||
The frontend constructs the PR link as:
|
||||
```
|
||||
https://github.com/nomadkaraoke/karaoke-gen/pull/{pr_number}
|
||||
```
|
||||
|
||||
Displayed as: `#{pr_number} — {pr_title}` (truncated to ~60 chars if needed).
|
||||
|
||||
## Frontend Components
|
||||
|
||||
### New files
|
||||
- `frontend/components/system-status-modal.tsx` — the modal component
|
||||
|
||||
### Modified files
|
||||
- `frontend/components/version-footer.tsx` — make status line clickable, add modal toggle state
|
||||
- `frontend/lib/api.ts` — add `SystemStatus` types and `getSystemStatus()` method
|
||||
- `frontend/next.config.mjs` — pass through new `NEXT_PUBLIC_COMMIT_SHA`, `NEXT_PUBLIC_PR_NUMBER`, `NEXT_PUBLIC_PR_TITLE` env vars
|
||||
|
||||
### Modified backend files
|
||||
- `backend/api/routes/health.py` — new `/api/health/system-status` endpoint
|
||||
- `backend/version.py` — read `COMMIT_SHA`, `PR_NUMBER`, `PR_TITLE` env vars
|
||||
- `.github/workflows/ci.yml` — capture build metadata, pass to builds/deploys
|
||||
|
||||
### Data Flow
|
||||
|
||||
1. User clicks footer → modal opens, state set to loading
|
||||
2. Modal calls `GET /api/health/system-status` (with admin token header if available in localStorage)
|
||||
3. Endpoint aggregates: existing health checks + Firestore blue-green config + build metadata env vars
|
||||
4. Frontend renders cards from response
|
||||
5. No auto-refresh — data is fresh on each open
|
||||
|
||||
## Styling
|
||||
|
||||
- Follow existing project design patterns (Tailwind, CSS variables for theming)
|
||||
- Modal uses the same dark theme as the rest of the app
|
||||
- Cards use `var(--card-border)`, `var(--card-bg)` etc. for consistency
|
||||
- Green: `text-green-500` for healthy, red: `text-red-500` for offline
|
||||
- Blue-green section uses amber accent (`text-amber-500`, `border-amber-500/30`) to distinguish it as an operational detail
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Auto-refresh / polling in the modal (can be added later)
|
||||
- Flacfetch and Separator PR info (separate repos, separate CI)
|
||||
- Historical deploy data or deploy log
|
||||
- Notifications or alerts for status changes
|
||||
@@ -24,7 +24,7 @@ describe('getJobStep', () => {
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(1);
|
||||
expect(result.total).toBe(10);
|
||||
expect(result.label).toBe('Setting up');
|
||||
expect(result.label).toBe('settingUp');
|
||||
expect(result.isBlocking).toBe(false);
|
||||
expect(result.color).toBe('text-muted-foreground');
|
||||
});
|
||||
@@ -35,7 +35,7 @@ describe('getJobStep', () => {
|
||||
const job = createJob('searching_audio');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(2);
|
||||
expect(result.label).toBe('Searching for audio');
|
||||
expect(result.label).toBe('searchingForAudio');
|
||||
expect(result.isBlocking).toBe(false);
|
||||
});
|
||||
|
||||
@@ -43,7 +43,7 @@ describe('getJobStep', () => {
|
||||
const job = createJob('awaiting_audio_selection');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(2);
|
||||
expect(result.label).toBe('Select audio source');
|
||||
expect(result.label).toBe('selectAudioSource');
|
||||
expect(result.isBlocking).toBe(true);
|
||||
expect(result.color).toBe('text-amber-400');
|
||||
});
|
||||
@@ -54,21 +54,21 @@ describe('getJobStep', () => {
|
||||
const job = createJob('downloading_audio');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(3);
|
||||
expect(result.label).toBe('Downloading audio');
|
||||
expect(result.label).toBe('downloadingAudio');
|
||||
});
|
||||
|
||||
it('returns step 3 for downloading status without worker progress', () => {
|
||||
const job = createJob('downloading');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(3);
|
||||
expect(result.label).toBe('Downloading');
|
||||
expect(result.label).toBe('downloading');
|
||||
});
|
||||
|
||||
it('returns step 3 for downloading with empty state_data', () => {
|
||||
const job = createJob('downloading', {});
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(3);
|
||||
expect(result.label).toBe('Downloading');
|
||||
expect(result.label).toBe('downloading');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -101,7 +101,7 @@ describe('getJobStep', () => {
|
||||
});
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(4);
|
||||
expect(result.label).toMatch(/Audio.*\+.*Transcribing|Transcribing.*\+.*Audio/);
|
||||
expect(result.label).toMatch(/audio.*\+.*transcribing|transcribing.*\+.*audio/);
|
||||
});
|
||||
|
||||
it('shows only active worker when one is complete', () => {
|
||||
@@ -112,7 +112,7 @@ describe('getJobStep', () => {
|
||||
});
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(4);
|
||||
expect(result.label).toBe('Transcribing');
|
||||
expect(result.label).toBe('transcribing');
|
||||
});
|
||||
|
||||
it('shows processing complete when both workers done', () => {
|
||||
@@ -124,7 +124,7 @@ describe('getJobStep', () => {
|
||||
});
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(4);
|
||||
expect(result.label).toBe('Processing complete');
|
||||
expect(result.label).toBe('processingComplete');
|
||||
});
|
||||
|
||||
it('returns step 3 when state_data has no stage info', () => {
|
||||
@@ -135,7 +135,7 @@ describe('getJobStep', () => {
|
||||
});
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(3);
|
||||
expect(result.label).toBe('Downloading');
|
||||
expect(result.label).toBe('downloading');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -144,28 +144,28 @@ describe('getJobStep', () => {
|
||||
const job = createJob('separating_stage1');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(4);
|
||||
expect(result.label).toBe('Separating audio (1/2)');
|
||||
expect(result.label).toBe('separatingAudio1');
|
||||
});
|
||||
|
||||
it('returns step 4 for separating_stage2', () => {
|
||||
const job = createJob('separating_stage2');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(4);
|
||||
expect(result.label).toBe('Separating audio (2/2)');
|
||||
expect(result.label).toBe('separatingAudio2');
|
||||
});
|
||||
|
||||
it('returns step 4 for transcribing', () => {
|
||||
const job = createJob('transcribing');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(4);
|
||||
expect(result.label).toBe('Transcribing lyrics');
|
||||
expect(result.label).toBe('transcribingLyrics');
|
||||
});
|
||||
|
||||
it('returns step 4 for correcting', () => {
|
||||
const job = createJob('correcting');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(4);
|
||||
expect(result.label).toBe('Correcting lyrics');
|
||||
expect(result.label).toBe('correctingLyrics');
|
||||
});
|
||||
|
||||
it('shows combined progress when both audio and lyrics are in progress', () => {
|
||||
@@ -176,7 +176,7 @@ describe('getJobStep', () => {
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(4);
|
||||
// Should show combined label
|
||||
expect(result.label).toMatch(/Audio|Transcribing/);
|
||||
expect(result.label).toMatch(/audio|transcribing/);
|
||||
});
|
||||
|
||||
it('shows combined status when audio done but lyrics in progress', () => {
|
||||
@@ -195,14 +195,14 @@ describe('getJobStep', () => {
|
||||
const job = createJob('generating_screens');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(5);
|
||||
expect(result.label).toBe('Generating screens');
|
||||
expect(result.label).toBe('generatingScreens');
|
||||
});
|
||||
|
||||
it('returns step 5 for applying_padding', () => {
|
||||
const job = createJob('applying_padding');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(5);
|
||||
expect(result.label).toBe('Syncing countdown');
|
||||
expect(result.label).toBe('syncingCountdown');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -211,7 +211,7 @@ describe('getJobStep', () => {
|
||||
const job = createJob('awaiting_review');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(6);
|
||||
expect(result.label).toBe('Review lyrics');
|
||||
expect(result.label).toBe('reviewLyrics');
|
||||
expect(result.isBlocking).toBe(true);
|
||||
expect(result.color).toBe('text-amber-400');
|
||||
});
|
||||
@@ -220,7 +220,7 @@ describe('getJobStep', () => {
|
||||
const job = createJob('in_review');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(6);
|
||||
expect(result.label).toBe('In review');
|
||||
expect(result.label).toBe('inReview');
|
||||
expect(result.isBlocking).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -230,14 +230,14 @@ describe('getJobStep', () => {
|
||||
const job = createJob('review_complete');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(7);
|
||||
expect(result.label).toBe('Starting render');
|
||||
expect(result.label).toBe('startingRender');
|
||||
});
|
||||
|
||||
it('returns step 7 for rendering_video', () => {
|
||||
const job = createJob('rendering_video');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(7);
|
||||
expect(result.label).toBe('Rendering video');
|
||||
expect(result.label).toBe('renderingVideo');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -246,7 +246,7 @@ describe('getJobStep', () => {
|
||||
const job = createJob('awaiting_instrumental_selection');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(8);
|
||||
expect(result.label).toBe('Select instrumental');
|
||||
expect(result.label).toBe('selectInstrumental');
|
||||
expect(result.isBlocking).toBe(true);
|
||||
expect(result.color).toBe('text-amber-400');
|
||||
});
|
||||
@@ -257,28 +257,28 @@ describe('getJobStep', () => {
|
||||
const job = createJob('instrumental_selected');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(9);
|
||||
expect(result.label).toBe('Starting final encode');
|
||||
expect(result.label).toBe('startingFinalEncode');
|
||||
});
|
||||
|
||||
it('returns step 9 for generating_video', () => {
|
||||
const job = createJob('generating_video');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(9);
|
||||
expect(result.label).toBe('Generating final video');
|
||||
expect(result.label).toBe('generatingFinalVideo');
|
||||
});
|
||||
|
||||
it('returns step 9 for encoding', () => {
|
||||
const job = createJob('encoding');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(9);
|
||||
expect(result.label).toBe('Encoding video');
|
||||
expect(result.label).toBe('encodingVideo');
|
||||
});
|
||||
|
||||
it('returns step 9 for packaging', () => {
|
||||
const job = createJob('packaging');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(9);
|
||||
expect(result.label).toBe('Packaging files');
|
||||
expect(result.label).toBe('packagingFiles');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -287,7 +287,7 @@ describe('getJobStep', () => {
|
||||
const job = createJob('uploading');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(10);
|
||||
expect(result.label).toBe('Uploading');
|
||||
expect(result.label).toBe('uploading');
|
||||
expect(result.color).toBe('text-green-400');
|
||||
});
|
||||
|
||||
@@ -295,14 +295,14 @@ describe('getJobStep', () => {
|
||||
const job = createJob('notifying');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(10);
|
||||
expect(result.label).toBe('Sending notifications');
|
||||
expect(result.label).toBe('sendingNotifications');
|
||||
});
|
||||
|
||||
it('returns step 10 for complete', () => {
|
||||
const job = createJob('complete');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(10);
|
||||
expect(result.label).toBe('Complete');
|
||||
expect(result.label).toBe('complete');
|
||||
expect(result.color).toBe('text-green-400');
|
||||
});
|
||||
|
||||
@@ -310,7 +310,7 @@ describe('getJobStep', () => {
|
||||
const job = createJob('prep_complete');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(10);
|
||||
expect(result.label).toBe('Prep complete');
|
||||
expect(result.label).toBe('prepComplete');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -319,7 +319,7 @@ describe('getJobStep', () => {
|
||||
const job = createJob('failed');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(0);
|
||||
expect(result.label).toBe('Failed');
|
||||
expect(result.label).toBe('failed');
|
||||
expect(result.color).toBe('text-red-400');
|
||||
});
|
||||
|
||||
@@ -327,7 +327,7 @@ describe('getJobStep', () => {
|
||||
const job = createJob('cancelled');
|
||||
const result = getJobStep(job);
|
||||
expect(result.step).toBe(0);
|
||||
expect(result.label).toBe('Cancelled');
|
||||
expect(result.label).toBe('cancelled');
|
||||
expect(result.color).toBe('text-muted-foreground');
|
||||
});
|
||||
});
|
||||
@@ -372,19 +372,19 @@ describe('getJobStep', () => {
|
||||
|
||||
describe('formatStepIndicator', () => {
|
||||
it('formats active step correctly', () => {
|
||||
expect(formatStepIndicator(4, 10, 'Processing')).toBe('[4/10] Processing');
|
||||
expect(formatStepIndicator(4, 10, 'processing')).toBe('[4/10] processing');
|
||||
});
|
||||
|
||||
it('omits step number for terminal states (step 0)', () => {
|
||||
expect(formatStepIndicator(0, 10, 'Failed')).toBe('Failed');
|
||||
expect(formatStepIndicator(0, 10, 'failed')).toBe('failed');
|
||||
});
|
||||
|
||||
it('formats first step correctly', () => {
|
||||
expect(formatStepIndicator(1, 10, 'Setting up')).toBe('[1/10] Setting up');
|
||||
expect(formatStepIndicator(1, 10, 'settingUp')).toBe('[1/10] settingUp');
|
||||
});
|
||||
|
||||
it('formats last step correctly', () => {
|
||||
expect(formatStepIndicator(10, 10, 'Complete')).toBe('[10/10] Complete');
|
||||
expect(formatStepIndicator(10, 10, 'complete')).toBe('[10/10] complete');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import { api, Job, createLyricsReviewApiClient, lyricsReviewApi } from "@/lib/ap
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ArrowLeft, AlertCircle } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Link } from "@/i18n/routing"
|
||||
import { LyricsAnalyzer } from "@/components/lyrics-review"
|
||||
import { InstrumentalSelector } from "@/components/instrumental-review"
|
||||
import { AudioEditor } from "@/components/audio-editor/AudioEditor"
|
||||
@@ -0,0 +1,16 @@
|
||||
import { JobRouterClient } from "./client"
|
||||
|
||||
// Required for static export with catch-all routes
|
||||
// Returns params array for paths to pre-render at build time
|
||||
export async function generateStaticParams(): Promise<{ slug?: string[] }[]> {
|
||||
return [
|
||||
{ slug: undefined }, // /app/jobs/
|
||||
// Local mode paths - pre-rendered for karaoke-gen CLI local review
|
||||
{ slug: ['local', 'review'] }, // /app/jobs/local/review
|
||||
{ slug: ['local', 'instrumental'] }, // /app/jobs/local/instrumental
|
||||
]
|
||||
}
|
||||
|
||||
export default function JobsPage() {
|
||||
return <JobRouterClient />
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo, Suspense, useRef } from "react"
|
||||
import { useRouter } from "@/i18n/routing"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { api, Job, getAccessToken } from "@/lib/api"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { useJobNotifications, useVisibilityRefresh } from "@/hooks/use-notifications"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Music2, RefreshCw, Loader2, Moon, Sun, Search, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone } from "lucide-react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { sortJobsByDate } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
import { TenantJobFlow } from "@/components/job/TenantJobFlow"
|
||||
import { TenantLogo } from "@/components/tenant-logo"
|
||||
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 LanguageSwitcher from "@/components/LanguageSwitcher"
|
||||
import { useTheme } from "@/lib/theme"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
|
||||
function AppPageContent() {
|
||||
const t = useTranslations('dashboard')
|
||||
const tHeader = useTranslations('header')
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [allJobs, setAllJobs] = useState<Job[]>([])
|
||||
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
|
||||
const [isInitialLoad, setIsInitialLoad] = useState(true)
|
||||
const [hasFetchedSuccessfully, setHasFetchedSuccessfully] = useState(false)
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
|
||||
const [isVerifyingToken, setIsVerifyingToken] = useState(false)
|
||||
const adminTokenHandled = useRef(false) // Track if admin_token was already processed
|
||||
const { isDarkMode, toggleTheme, mounted } = useTheme()
|
||||
const { user, fetchUser, verifyMagicLink } = useAuth()
|
||||
const { isDefault: isDefaultTenant, branding } = useTenant()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [jobLimit, setJobLimit] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 10
|
||||
const saved = localStorage.getItem("nomad-karaoke-job-limit")
|
||||
return saved ? Number(saved) : 10
|
||||
})
|
||||
const [statusFilter, setStatusFilter] = useState<string>(() => {
|
||||
if (typeof window === "undefined") return "all"
|
||||
return localStorage.getItem("nomad-karaoke-status-filter") || "all"
|
||||
})
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [showAdminControls, setShowAdminControls] = useState<boolean>(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-karaoke-admin-controls") === "true"
|
||||
})
|
||||
const [feedbackBannerDismissed, setFeedbackBannerDismissed] = useState(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-feedback-banner-dismissed") === "true"
|
||||
})
|
||||
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 jobs = useMemo(
|
||||
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
|
||||
[allJobs]
|
||||
)
|
||||
|
||||
// Debounce search input — only update the query (which triggers API calls) after 300ms
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setSearchQuery(searchInput), 300)
|
||||
return () => clearTimeout(timer)
|
||||
}, [searchInput])
|
||||
|
||||
// Memoize loadJobs for use with visibility refresh
|
||||
const loadJobs = useCallback(async () => {
|
||||
if (!getAccessToken()) {
|
||||
setIsLoadingJobs(false)
|
||||
setIsInitialLoad(false)
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = await api.listJobs({
|
||||
limit: jobLimit,
|
||||
exclude_test: isAdmin ? !showTestData : undefined,
|
||||
fields: 'summary',
|
||||
status: statusFilter !== 'all' && statusFilter !== 'active' ? statusFilter : undefined,
|
||||
hide_completed: statusFilter === 'active' ? true : undefined,
|
||||
search: searchQuery || undefined,
|
||||
})
|
||||
setAllJobs(sortJobsByDate(data))
|
||||
} catch (err: any) {
|
||||
if (err?.status !== 401) {
|
||||
console.error("Failed to load jobs:", err)
|
||||
}
|
||||
} finally {
|
||||
setIsLoadingJobs(false)
|
||||
setIsInitialLoad(false)
|
||||
setHasFetchedSuccessfully(true)
|
||||
}
|
||||
}, [isAdmin, showTestData, jobLimit, statusFilter, searchQuery])
|
||||
|
||||
// Enable notifications for job status changes (sound + title animation)
|
||||
useJobNotifications(allJobs)
|
||||
|
||||
// Refresh jobs immediately when tab becomes visible (after returning from review UIs)
|
||||
useVisibilityRefresh(loadJobs, isAuthenticated === true)
|
||||
|
||||
// Handle admin_token URL parameter for one-click login from email
|
||||
useEffect(() => {
|
||||
const adminToken = searchParams.get("admin_token")
|
||||
|
||||
// Only process admin_token once (use ref to prevent repeated calls)
|
||||
if (adminToken && !adminTokenHandled.current) {
|
||||
adminTokenHandled.current = true
|
||||
setIsVerifyingToken(true)
|
||||
|
||||
verifyMagicLink(adminToken).then((success) => {
|
||||
// Clean URL by removing the token
|
||||
window.history.replaceState({}, '', '/app')
|
||||
setIsVerifyingToken(false)
|
||||
if (success) {
|
||||
setIsAuthenticated(true)
|
||||
} else {
|
||||
router.replace('/')
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Normal auth check (skip if admin_token is being processed)
|
||||
if (adminToken || isVerifyingToken) return
|
||||
|
||||
const token = getAccessToken()
|
||||
if (!token) {
|
||||
// Redirect to landing page if not authenticated
|
||||
router.replace('/')
|
||||
return
|
||||
}
|
||||
setIsAuthenticated(true)
|
||||
}, [router, searchParams, verifyMagicLink, isVerifyingToken])
|
||||
|
||||
// Ensure user data is loaded after authentication
|
||||
// This handles the case where user navigates via client-side navigation
|
||||
// (e.g., after beta enrollment) and the module-level fetchUser() didn't run
|
||||
useEffect(() => {
|
||||
const token = getAccessToken()
|
||||
if (token && !user) {
|
||||
fetchUser()
|
||||
}
|
||||
}, [user, fetchUser])
|
||||
|
||||
// Load jobs on mount (only if authenticated)
|
||||
useEffect(() => {
|
||||
if (isAuthenticated !== true) {
|
||||
setIsLoadingJobs(false)
|
||||
return
|
||||
}
|
||||
loadJobs()
|
||||
// Poll for updates every 10 seconds
|
||||
const interval = setInterval(loadJobs, 10000)
|
||||
return () => clearInterval(interval)
|
||||
}, [isAuthenticated, loadJobs])
|
||||
|
||||
// Show nothing while checking auth or verifying admin token (prevents flash)
|
||||
if (isAuthenticated === null || isVerifyingToken) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center animated-gradient">
|
||||
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--text-muted)' }} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Show warming up loader during initial job load (cold start scenario)
|
||||
if (isInitialLoad && isLoadingJobs) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center animated-gradient">
|
||||
<WarmingUpLoader spinnerClassName="w-10 h-10" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen animated-gradient">
|
||||
{/* AutoProcessor - handles non-interactive mode for jobs with that flag */}
|
||||
<AutoProcessor jobs={allJobs} onJobsChanged={loadJobs} />
|
||||
|
||||
{/* Header */}
|
||||
<header className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
|
||||
<div className="px-3 sm:px-4 py-2 sm:py-3 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 sm:gap-3 min-w-0">
|
||||
{isDefaultTenant ? (
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 sm:h-10 shrink-0" />
|
||||
) : (
|
||||
<TenantLogo size="sm" />
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-base sm:text-xl font-bold truncate" style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? t('title') : branding.site_title}
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={loadJobs}
|
||||
disabled={isLoadingJobs || !isAuthenticated}
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 sm:mr-2 ${isLoadingJobs ? 'animate-spin' : ''}`} />
|
||||
<span className="hidden sm:inline">{t('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 ? t('hideAdminControls') : t('showAdminControls')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<HelpCircle className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64">
|
||||
<DropdownMenuLabel className="text-sm font-normal">
|
||||
{tHeader('helpPrompt')}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="mailto:andrew@nomadkaraoke.com">
|
||||
<Mail className="w-4 h-4 mr-2" />
|
||||
andrew@nomadkaraoke.com
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="tel:+18036363267">
|
||||
<Phone className="w-4 h-4 mr-2" />
|
||||
+1 (803) 636-3267
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<LanguageSwitcher />
|
||||
<AuthStatus />
|
||||
{mounted && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={toggleTheme}
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
{isDarkMode ? (
|
||||
<Sun className="w-4 h-4" />
|
||||
) : (
|
||||
<Moon className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
<p>{isDarkMode ? t('switchToLightMode') : t('switchToDarkMode')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</div>
|
||||
</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 (consumer portal only) */}
|
||||
{isDefaultTenant && 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>{t('earnFreeCredit')}</strong>{' '}
|
||||
<span style={{ color: 'var(--text-muted)' }}>
|
||||
{t('feedbackPrompt')}
|
||||
</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"
|
||||
>
|
||||
{t('giveFeedback')}
|
||||
</Button>
|
||||
<button
|
||||
onClick={() => {
|
||||
localStorage.setItem("nomad-feedback-banner-dismissed", "true")
|
||||
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)' }}>
|
||||
{isDefaultTenant ? t('createKaraokeVideo') : t('submitTrack')}
|
||||
</CardTitle>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
{isDefaultTenant
|
||||
? t('createDescription')
|
||||
: t('submitDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isDefaultTenant ? (
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
) : (
|
||||
<TenantJobFlow onJobCreated={loadJobs} />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Jobs List Card */}
|
||||
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
|
||||
<CardHeader className="px-3 sm:px-6">
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<div className="flex items-center gap-2">
|
||||
<CardTitle style={{ color: 'var(--text)' }}>{t('recentJobs')}</CardTitle>
|
||||
{isLoadingJobs && <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--text-muted)' }} />}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5" style={{ color: 'var(--text-muted)' }} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder={t('searchPlaceholder')}
|
||||
aria-label={t('searchPlaceholder')}
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="h-7 w-[160px] sm:w-[200px] text-xs rounded-md border pl-7 pr-2"
|
||||
style={{
|
||||
backgroundColor: 'var(--input)',
|
||||
borderColor: 'var(--border)',
|
||||
color: 'var(--text)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Select value={statusFilter} onValueChange={(v) => {
|
||||
setStatusFilter(v)
|
||||
localStorage.setItem("nomad-karaoke-status-filter", v)
|
||||
}}>
|
||||
<SelectTrigger className="h-7 w-[130px] text-xs" aria-label={t('filterByStatus')}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t('allStatuses')}</SelectItem>
|
||||
<SelectItem value="active">{t('active')}</SelectItem>
|
||||
<SelectItem value="failed">{t('failed')}</SelectItem>
|
||||
<SelectItem value="complete">{t('completed')}</SelectItem>
|
||||
<SelectItem value="cancelled">{t('cancelled')}</SelectItem>
|
||||
<SelectItem value="awaiting_review">{t('awaitingReview')}</SelectItem>
|
||||
<SelectItem value="processing">{t('processing')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={String(jobLimit)} onValueChange={(v) => {
|
||||
const val = Number(v)
|
||||
setJobLimit(val)
|
||||
localStorage.setItem("nomad-karaoke-job-limit", String(val))
|
||||
}}>
|
||||
<SelectTrigger className="h-7 w-[70px] text-xs" aria-label={t('resultsPerPage')}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">5</SelectItem>
|
||||
<SelectItem value="10">10</SelectItem>
|
||||
<SelectItem value="20">20</SelectItem>
|
||||
<SelectItem value="50">50</SelectItem>
|
||||
<SelectItem value="100">100</SelectItem>
|
||||
<SelectItem value="1000">1000</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
{!hasFetchedSuccessfully
|
||||
? t('loadingJobs')
|
||||
: searchQuery || (statusFilter !== 'all' && statusFilter !== 'active')
|
||||
? t('jobsMatchingFilters', { count: jobs.length })
|
||||
: t('jobsCount', { count: jobs.length })}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="px-3 sm:px-6">
|
||||
{jobs.length === 0 ? (
|
||||
<div className="text-center py-8" style={{ color: 'var(--text-muted)' }}>
|
||||
{!hasFetchedSuccessfully ? (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 mx-auto mb-3 opacity-50 animate-spin" />
|
||||
<p>{t('loadingJobs')}</p>
|
||||
</>
|
||||
) : searchQuery || (statusFilter !== 'all' && statusFilter !== 'active') ? (
|
||||
<>
|
||||
<Search className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>{t('noJobsMatchFilters')}</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>{t('noJobsYet')}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{jobs.map((job) => (
|
||||
<JobCard key={job.job_id} job={job} onRefresh={loadJobs} showAdminControls={isAdmin && showAdminControls} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<VersionFooter />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Wrap with Suspense for useSearchParams
|
||||
export default function AppPage() {
|
||||
return (
|
||||
<Suspense fallback={
|
||||
<div className="min-h-screen flex items-center justify-center animated-gradient">
|
||||
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--text-muted)' }} />
|
||||
</div>
|
||||
}>
|
||||
<AppPageContent />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
"use client"
|
||||
|
||||
import { Suspense, useEffect, useState, useRef } from "react"
|
||||
import { useRouter } from "@/i18n/routing"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { Loader2, CheckCircle, XCircle, Gift, ShoppingCart } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useTranslations } from "next-intl"
|
||||
|
||||
type VerifyState = "verifying" | "preparing" | "credits_granted" | "credits_denied" | "credits_pending" | "success" | "error"
|
||||
|
||||
function VerifyMagicLinkContent() {
|
||||
const t = useTranslations('auth')
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [state, setState] = useState<VerifyState>("verifying")
|
||||
const [errorMessage, setErrorMessage] = useState("")
|
||||
const [creditsGranted, setCreditsGranted] = useState(0)
|
||||
const [creditStatus, setCreditStatus] = useState<string>("not_applicable")
|
||||
const hasVerified = useRef(false)
|
||||
|
||||
const { verifyMagicLink, user, error } = useAuth()
|
||||
|
||||
useEffect(() => {
|
||||
if (hasVerified.current) return
|
||||
hasVerified.current = true
|
||||
|
||||
const token = searchParams.get("token")
|
||||
|
||||
if (!token) {
|
||||
setState("error")
|
||||
setErrorMessage(t('noVerificationToken'))
|
||||
return
|
||||
}
|
||||
|
||||
const verify = async () => {
|
||||
// Show "preparing your account" while the backend runs AI evaluation
|
||||
setState("preparing")
|
||||
|
||||
const success = await verifyMagicLink(token)
|
||||
if (success) {
|
||||
const lastVerifyResponse = (window as any).__LAST_VERIFY_RESPONSE__
|
||||
const credits = lastVerifyResponse?.credits_granted || 0
|
||||
const status = lastVerifyResponse?.credit_status || "not_applicable"
|
||||
setCreditsGranted(credits)
|
||||
setCreditStatus(status)
|
||||
|
||||
// Check for tenant subdomain redirect
|
||||
if (lastVerifyResponse?.tenant_subdomain) {
|
||||
const currentHost = window.location.hostname.toLowerCase()
|
||||
const tenantSubdomain = lastVerifyResponse.tenant_subdomain.toLowerCase()
|
||||
if (currentHost !== tenantSubdomain) {
|
||||
setState("success")
|
||||
setTimeout(() => {
|
||||
window.location.href = `https://${tenantSubdomain}/app`
|
||||
}, 1500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Show appropriate interstitial based on credit status
|
||||
if (status === "granted" && credits > 0) {
|
||||
setState("credits_granted")
|
||||
} else if (status === "denied") {
|
||||
setState("credits_denied")
|
||||
} else if (status === "pending_review") {
|
||||
setState("credits_pending")
|
||||
} else {
|
||||
// Returning user or not applicable — go straight to app
|
||||
setState("success")
|
||||
setTimeout(() => {
|
||||
router.push("/app")
|
||||
}, 1500)
|
||||
}
|
||||
} else {
|
||||
setState("error")
|
||||
const authStore = useAuth.getState()
|
||||
setErrorMessage(authStore.error || t('linkExpiredOrUsed'))
|
||||
}
|
||||
}
|
||||
|
||||
verify()
|
||||
}, [searchParams, verifyMagicLink, router, t])
|
||||
|
||||
const goToApp = () => router.push("/app")
|
||||
const goToBuy = () => router.push("/app?buy=true")
|
||||
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
{/* Verifying token */}
|
||||
{state === "verifying" && (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
{t('verifying')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('verifyingWait')}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Preparing account (AI evaluation running) */}
|
||||
{state === "preparing" && (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
{t('preparingAccount')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('preparingWait')}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Credits granted - celebratory interstitial */}
|
||||
{state === "credits_granted" && (
|
||||
<>
|
||||
<div className="relative mx-auto mb-4 w-16 h-16">
|
||||
<Gift className="w-16 h-16 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-foreground mb-2">
|
||||
{t('welcomeTitle')}
|
||||
</h1>
|
||||
<div className="bg-primary/10 border border-primary/20 rounded-lg p-4 mb-4">
|
||||
<p className="text-3xl font-bold text-primary">{creditsGranted}</p>
|
||||
<p className="text-sm font-medium text-primary/80">{t('freeCreditsGranted', { count: creditsGranted })}</p>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
{t('freeCreditsExplanation')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mb-6">
|
||||
{t('freeCreditsRequest')}
|
||||
</p>
|
||||
<Button
|
||||
onClick={goToApp}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
{t('startCreating')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Credits denied - friendly rejection interstitial */}
|
||||
{state === "credits_denied" && (
|
||||
<>
|
||||
<XCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
{t('welcomeBack')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
{t('creditsDeniedExplanation')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
{t('creditsDeniedHelp')}
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={goToBuy}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
<ShoppingCart className="w-4 h-4 mr-2" />
|
||||
{t('buyCredits')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={goToApp}
|
||||
variant="ghost"
|
||||
className="w-full"
|
||||
>
|
||||
{t('goToDashboard')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Credits pending review - friendly holding message */}
|
||||
{state === "credits_pending" && (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
{t('creditsPendingTitle')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
{t('creditsPendingExplanation')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
{t('creditsPendingHint')}
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={goToBuy}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
<ShoppingCart className="w-4 h-4 mr-2" />
|
||||
{t('buyCredits')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={goToApp}
|
||||
variant="ghost"
|
||||
className="w-full"
|
||||
>
|
||||
{t('exploreApp')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Simple success (returning user) */}
|
||||
{state === "success" && (
|
||||
<>
|
||||
<CheckCircle className="w-12 h-12 text-success mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
{t('successSignedIn')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
{t('welcomeBackUser', { email: user?.email ? `, ${user.email}` : "" })}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('redirectingToApp')}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{state === "error" && (
|
||||
<>
|
||||
<XCircle className="w-12 h-12 text-destructive mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
{t('signInFailed')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-6">
|
||||
{errorMessage || t('linkExpiredOrUsed')}
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={() => router.push("/app")}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
{t('goToApp')}
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('requestNewLink')}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function VerifyLoadingFallback() {
|
||||
const t = useTranslations('auth')
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
{t('pleaseWait')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('pleaseWait')}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function VerifyMagicLinkPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<Suspense fallback={<VerifyLoadingFallback />}>
|
||||
<VerifyMagicLinkContent />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import { getMessages, setRequestLocale } from 'next-intl/server';
|
||||
import { hasLocale } from 'next-intl';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { routing } from '@/i18n/routing';
|
||||
|
||||
export function generateStaticParams() {
|
||||
return routing.locales.map((locale) => ({ locale }));
|
||||
}
|
||||
|
||||
export default async function LocaleLayout({
|
||||
children,
|
||||
params,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
params: Promise<{ locale: string }>;
|
||||
}) {
|
||||
const { locale } = await params;
|
||||
|
||||
if (!hasLocale(routing.locales, locale)) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
setRequestLocale(locale);
|
||||
|
||||
const messages = await getMessages();
|
||||
|
||||
return (
|
||||
<NextIntlClientProvider locale={locale} messages={messages}>
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `document.documentElement.lang="${locale}";`,
|
||||
}}
|
||||
/>
|
||||
{children}
|
||||
</NextIntlClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
"use client"
|
||||
|
||||
import { Suspense } from "react"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { CheckCircle, Loader2, Mail, Clock } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useTranslations, useLocale } from "next-intl"
|
||||
|
||||
function OrderSuccessContent() {
|
||||
const t = useTranslations('order')
|
||||
const locale = useLocale()
|
||||
const searchParams = useSearchParams()
|
||||
const sessionId = searchParams.get("session_id")
|
||||
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<CheckCircle className="w-16 h-16 text-success mx-auto mb-4" />
|
||||
|
||||
<h1 className="text-2xl font-bold text-foreground mb-2">
|
||||
{t('title')}
|
||||
</h1>
|
||||
|
||||
<p className="text-muted-foreground mb-6">
|
||||
{t('description')}
|
||||
</p>
|
||||
|
||||
<div className="space-y-4 mb-6">
|
||||
<div className="flex items-center gap-3 text-left p-3 bg-secondary rounded-lg">
|
||||
<Clock className="w-5 h-5 text-primary flex-shrink-0" />
|
||||
<div>
|
||||
<p className="font-medium text-foreground">{t('deliveryTime')}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('deliveryNote')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 text-left p-3 bg-secondary rounded-lg">
|
||||
<Mail className="w-5 h-5 text-primary flex-shrink-0" />
|
||||
<div>
|
||||
<p className="font-medium text-foreground">{t('checkEmail')}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('checkEmailNote')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
asChild
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
<a href={`https://nomadkaraoke.com/${locale}/`}>
|
||||
{t('backToNomadKaraoke')}
|
||||
</a>
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('questionsEmail')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function OrderLoadingFallback() {
|
||||
const tCommon = useTranslations('common')
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<Loader2 className="w-16 h-16 text-primary mx-auto mb-4 animate-spin" />
|
||||
<p className="text-muted-foreground">{tCommon('loading')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function OrderSuccessPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<Suspense fallback={<OrderLoadingFallback />}>
|
||||
<OrderSuccessContent />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,866 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from '@/i18n/routing';
|
||||
import { useTranslations, useLocale } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
import {
|
||||
Music,
|
||||
Sparkles,
|
||||
Video,
|
||||
Youtube,
|
||||
Check,
|
||||
Gift,
|
||||
Mail,
|
||||
Loader2,
|
||||
Search,
|
||||
Link as LinkIcon,
|
||||
Upload,
|
||||
Clock,
|
||||
FileVideo,
|
||||
CreditCard,
|
||||
} from 'lucide-react';
|
||||
import { api, setAccessToken, getAccessToken, CreditPackage } from '@/lib/api';
|
||||
import { AuthDialog } from '@/components/auth/AuthDialog';
|
||||
import { WarmingUpLoader } from '@/components/WarmingUpLoader';
|
||||
import { ThemeToggle } from '@/components/ThemeToggle';
|
||||
import LanguageSwitcher from '@/components/LanguageSwitcher';
|
||||
import { useTenant } from '@/lib/tenant';
|
||||
import { TenantLandingPage } from '@/components/TenantLandingPage';
|
||||
|
||||
// Build-time constant: when true, this build is for tenant portals only
|
||||
const IS_TENANT_PORTAL = process.env.NEXT_PUBLIC_TENANT_PORTAL === 'true';
|
||||
|
||||
export default function LandingPage() {
|
||||
// Tenant portal builds always render the tenant landing page
|
||||
// This is a build-time constant so the consumer code gets tree-shaken
|
||||
if (IS_TENANT_PORTAL) {
|
||||
return <TenantLandingPage />;
|
||||
}
|
||||
|
||||
return <ConsumerLandingPage />;
|
||||
}
|
||||
|
||||
function ConsumerLandingPage() {
|
||||
const router = useRouter();
|
||||
const t = useTranslations('landing');
|
||||
const locale = useLocale();
|
||||
const { isDefault: isDefaultTenant, isLoading: tenantLoading, isInitialized: tenantInitialized } = useTenant();
|
||||
const [isCheckingAuth, setIsCheckingAuth] = useState(true);
|
||||
const [isMounted, setIsMounted] = useState(false);
|
||||
const [packages, setPackages] = useState<CreditPackage[]>([]);
|
||||
const [packagesLoading, setPackagesLoading] = useState(true);
|
||||
const [packagesError, setPackagesError] = useState<string | null>(null);
|
||||
const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null);
|
||||
const [email, setEmail] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Made For You form state
|
||||
const [mfyArtist, setMfyArtist] = useState('');
|
||||
const [mfyTitle, setMfyTitle] = useState('');
|
||||
const [mfySourceType, setMfySourceType] = useState<'search' | 'youtube' | 'upload'>('search');
|
||||
const [mfyYoutubeUrl, setMfyYoutubeUrl] = useState('');
|
||||
const [mfyEmail, setMfyEmail] = useState('');
|
||||
const [mfyNotes, setMfyNotes] = useState('');
|
||||
const [mfyLoading, setMfyLoading] = useState(false);
|
||||
const [mfyError, setMfyError] = useState<string | null>(null);
|
||||
|
||||
// Auth dialog state
|
||||
const [showAuthDialog, setShowAuthDialog] = useState(false);
|
||||
|
||||
// FAQ data (uses translation keys)
|
||||
const faqs = [
|
||||
{ question: t('faq.faq1Question'), answer: t('faq.faq1Answer') },
|
||||
{ question: t('faq.faq2Question'), answer: t('faq.faq2Answer') },
|
||||
{ question: t('faq.faq3Question'), answer: t('faq.faq3Answer') },
|
||||
{ question: t('faq.faq4Question'), answer: t('faq.faq4Answer') },
|
||||
{ question: t('faq.faq5Question'), answer: t('faq.faq5Answer') },
|
||||
];
|
||||
|
||||
// Track client-side mount to avoid hydration mismatch
|
||||
useEffect(() => {
|
||||
setIsMounted(true);
|
||||
}, []);
|
||||
|
||||
// Check if already logged in and redirect to app
|
||||
useEffect(() => {
|
||||
const token = getAccessToken();
|
||||
if (token) {
|
||||
router.replace('/app');
|
||||
return;
|
||||
}
|
||||
setIsCheckingAuth(false);
|
||||
}, [router]);
|
||||
|
||||
// Handle successful auth from dialog
|
||||
const handleAuthSuccess = () => {
|
||||
setShowAuthDialog(false);
|
||||
router.push('/app');
|
||||
};
|
||||
|
||||
// Load credit packages on mount
|
||||
useEffect(() => {
|
||||
if (isCheckingAuth) return;
|
||||
|
||||
async function loadPackages() {
|
||||
try {
|
||||
const pkgs = await api.getCreditPackages();
|
||||
setPackages(pkgs);
|
||||
// Default to 5 credits (best value)
|
||||
const bestValue = pkgs.find((p) => p.credits === 5);
|
||||
setSelectedPackage(bestValue || pkgs[0]);
|
||||
} catch (err) {
|
||||
console.error('Failed to load packages:', err);
|
||||
setPackagesError('Failed to load pricing. Please refresh the page.');
|
||||
} finally {
|
||||
setPackagesLoading(false);
|
||||
}
|
||||
}
|
||||
loadPackages();
|
||||
}, [isCheckingAuth]);
|
||||
|
||||
// Tenant portals get a minimal landing page (just logo + sign in)
|
||||
// Only check after mount to avoid hydration mismatch with static export
|
||||
// Must be AFTER all hooks to comply with React Rules of Hooks
|
||||
if (isMounted && tenantInitialized && !isDefaultTenant) {
|
||||
return <TenantLandingPage />;
|
||||
}
|
||||
|
||||
// Handle checkout
|
||||
const handleCheckout = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!selectedPackage || !email) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const checkoutUrl = await api.createCheckout(selectedPackage.id, email);
|
||||
// Validate that the URL is a Stripe checkout URL
|
||||
if (!checkoutUrl.startsWith('https://checkout.stripe.com/')) {
|
||||
throw new Error('Invalid checkout URL received');
|
||||
}
|
||||
window.location.href = checkoutUrl;
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create checkout session');
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle Made For You checkout
|
||||
const handleMadeForYouSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setMfyError(null);
|
||||
|
||||
// Validation
|
||||
if (!mfyArtist.trim()) {
|
||||
setMfyError(t('madeForYou.artistRequired'));
|
||||
return;
|
||||
}
|
||||
if (!mfyTitle.trim()) {
|
||||
setMfyError(t('madeForYou.titleRequired'));
|
||||
return;
|
||||
}
|
||||
if (!mfyEmail.trim()) {
|
||||
setMfyError(t('madeForYou.emailRequired'));
|
||||
return;
|
||||
}
|
||||
if (mfySourceType === 'youtube' && !mfyYoutubeUrl.trim()) {
|
||||
setMfyError(t('madeForYou.youtubeUrlRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
setMfyLoading(true);
|
||||
|
||||
try {
|
||||
const checkoutUrl = await api.createMadeForYouCheckout({
|
||||
email: mfyEmail,
|
||||
artist: mfyArtist,
|
||||
title: mfyTitle,
|
||||
source_type: mfySourceType,
|
||||
youtube_url: mfySourceType === 'youtube' ? mfyYoutubeUrl : undefined,
|
||||
notes: mfyNotes || undefined,
|
||||
});
|
||||
|
||||
// Redirect to Stripe Checkout
|
||||
window.location.href = checkoutUrl;
|
||||
} catch (err) {
|
||||
setMfyError(err instanceof Error ? err.message : t('madeForYou.submitError'));
|
||||
setMfyLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatPrice = (cents: number) => `$${(cents / 100).toFixed(0)}`;
|
||||
const pricePerVideo = (pkg: CreditPackage) =>
|
||||
`$${(pkg.price_cents / 100 / pkg.credits).toFixed(2)}`;
|
||||
|
||||
// Show loading while checking auth
|
||||
if (isCheckingAuth) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center animated-gradient">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-white" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen animated-gradient">
|
||||
{/* Navigation */}
|
||||
<nav className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
|
||||
<div className="max-w-6xl mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-10" />
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<LanguageSwitcher />
|
||||
<ThemeToggle />
|
||||
<button
|
||||
onClick={() => setShowAuthDialog(true)}
|
||||
className="px-4 py-2 text-sm font-semibold rounded-lg bg-[var(--brand-pink)] text-white hover:bg-[var(--brand-pink-hover)] hover:scale-105 hover:shadow-[0_0_20px_rgba(255,122,204,0.5)] active:scale-95 transition-all duration-200"
|
||||
>
|
||||
{t('navigation.signIn')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Hero Section */}
|
||||
<section className="pt-32 pb-6 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">
|
||||
{t('hero.title')}
|
||||
</h1>
|
||||
<p className="text-xl text-dark-300 mb-8 max-w-2xl mx-auto">
|
||||
{t('hero.subtitle')}
|
||||
</p>
|
||||
|
||||
{/* 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)}
|
||||
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" />
|
||||
{t('heroCTA.createYourself')}
|
||||
<span className="ml-1 px-2 py-0.5 bg-white/20 rounded-full text-sm">{t('heroCTA.createYourselfPrice')}</span>
|
||||
</button>
|
||||
<span className="text-green-400 text-sm">{t('heroCTA.createYourselfNote')}</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<a
|
||||
href="#made-for-you"
|
||||
className="inline-flex items-center gap-2 bg-yellow-500/20 hover:bg-yellow-500/30 text-yellow-400 border border-yellow-500/40 font-semibold px-8 py-4 rounded-xl transition-all"
|
||||
>
|
||||
<Gift className="w-5 h-5" />
|
||||
{t('heroCTA.makeForYou')}
|
||||
<span className="ml-1 px-2 py-0.5 bg-yellow-500/20 rounded-full text-sm">{t('heroCTA.makeForYouPrice')}</span>
|
||||
</a>
|
||||
<span className="text-yellow-400/70 text-sm">{t('heroCTA.makeForYouNote')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Demo Video Section */}
|
||||
<section className="py-8 px-4">
|
||||
<div className="max-w-4xl 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/RLkIEHGwFcU"
|
||||
title={t('demoVideo.title')}
|
||||
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>
|
||||
</section>
|
||||
|
||||
{/* How It Works */}
|
||||
<section className="py-16 px-4">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-center mb-12">{t('howItWorks.title')}</h2>
|
||||
<div className="grid md:grid-cols-4 gap-8">
|
||||
{[
|
||||
{ icon: Music, title: t('howItWorks.step1Title'), desc: t('howItWorks.step1Desc') },
|
||||
{ icon: Sparkles, title: t('howItWorks.step2Title'), desc: t('howItWorks.step2Desc') },
|
||||
{ icon: Video, title: t('howItWorks.step3Title'), desc: t('howItWorks.step3Desc') },
|
||||
{ icon: Youtube, title: t('howItWorks.step4Title'), desc: t('howItWorks.step4Desc') },
|
||||
].map((step, i) => (
|
||||
<div key={i} className="text-center">
|
||||
<div className="w-16 h-16 bg-primary-500/20 rounded-2xl flex items-center justify-center mx-auto mb-4">
|
||||
<step.icon className="w-8 h-8 text-primary-400" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg mb-2">{step.title}</h3>
|
||||
<p className="text-dark-400 text-sm">{step.desc}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Full Tutorial Video */}
|
||||
<div className="mt-12 text-center">
|
||||
<h3 className="text-xl font-semibold mb-2">{t('howItWorks.tutorialTitle')}</h3>
|
||||
<p className="text-dark-400 text-sm mb-6 max-w-xl mx-auto">
|
||||
{t('howItWorks.tutorialDesc')}
|
||||
</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={t('howItWorks.tutorialVideoTitle')}
|
||||
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>
|
||||
|
||||
{/* Features */}
|
||||
<section className="py-16 px-4 bg-dark-800/50">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-center mb-12">{t('features.title')}</h2>
|
||||
<div className="grid md:grid-cols-3 gap-6">
|
||||
{[
|
||||
{ title: t('features.feature1Title'), desc: t('features.feature1Desc') },
|
||||
{ title: t('features.feature2Title'), desc: t('features.feature2Desc') },
|
||||
{ title: t('features.feature3Title'), desc: t('features.feature3Desc') },
|
||||
{ title: t('features.feature4Title'), desc: t('features.feature4Desc') },
|
||||
{ title: t('features.feature5Title'), desc: t('features.feature5Desc') },
|
||||
{ title: t('features.feature6Title'), desc: t('features.feature6Desc') },
|
||||
].map((feature, i) => (
|
||||
<div key={i} className="bg-dark-800 border border-dark-700 rounded-xl p-6 card-hover">
|
||||
<h3 className="font-semibold text-lg mb-2">{feature.title}</h3>
|
||||
<p className="text-dark-400 text-sm">{feature.desc}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Screenshots Section */}
|
||||
<section className="py-16 px-4">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-center mb-4">{t('screenshots.title')}</h2>
|
||||
<p className="text-dark-400 text-center mb-12 max-w-xl mx-auto">
|
||||
{t('screenshots.subtitle')}
|
||||
</p>
|
||||
<div className="grid md:grid-cols-2 gap-8">
|
||||
{/* Job Creation 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={t('screenshots.jobCreationAlt')}
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold mb-1">{t('screenshots.jobCreationTitle')}</h3>
|
||||
<p className="text-dark-400 text-sm">{t('screenshots.jobCreationDesc')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Lyrics Review 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/lyrics-review.avif"
|
||||
alt={t('screenshots.lyricsReviewAlt')}
|
||||
fill
|
||||
className="object-cover object-top"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold mb-1">{t('screenshots.lyricsReviewTitle')}</h3>
|
||||
<p className="text-dark-400 text-sm">{t('screenshots.lyricsReviewDesc')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Instrumental Selection 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/instrumental-review.avif"
|
||||
alt={t('screenshots.instrumentalReviewAlt')}
|
||||
fill
|
||||
className="object-cover object-top"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold mb-1">{t('screenshots.instrumentalReviewTitle')}</h3>
|
||||
<p className="text-dark-400 text-sm">{t('screenshots.instrumentalReviewDesc')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Example Output 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/example-output.avif"
|
||||
alt={t('screenshots.exampleOutputAlt')}
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold mb-1">{t('screenshots.exampleOutputTitle')}</h3>
|
||||
<p className="text-dark-400 text-sm">{t('screenshots.exampleOutputDesc')}</p>
|
||||
</div>
|
||||
</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">{t('pricing.title')}</h2>
|
||||
<p className="text-dark-400 text-center mb-4 max-w-xl mx-auto">
|
||||
{t('pricing.subtitle')}
|
||||
</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">{t('pricing.freeCreditLabel')}</div>
|
||||
<div className="text-4xl font-bold text-green-400 mb-1">{t('pricing.freeCredit')}</div>
|
||||
<div className="text-sm text-dark-400 mb-4">{t('pricing.freeCreditNote')}</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"
|
||||
>
|
||||
{t('pricing.signUpFree')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Package Selection */}
|
||||
{packagesLoading && (
|
||||
<WarmingUpLoader className="py-8" />
|
||||
)}
|
||||
{packagesError && (
|
||||
<div className="text-center py-8 text-red-400">
|
||||
{packagesError}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
|
||||
{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 ${
|
||||
isSelected
|
||||
? 'border-primary-500 bg-primary-500/10'
|
||||
: 'border-dark-700 hover:border-dark-500 bg-dark-800/50'
|
||||
}`}
|
||||
>
|
||||
{isBestValue && (
|
||||
<span className="absolute -top-3 left-1/2 -translate-x-1/2 bg-primary-500 text-white text-xs font-semibold px-3 py-1 rounded-full">
|
||||
{t('pricing.bestValue')}
|
||||
</span>
|
||||
)}
|
||||
<div className="text-2xl font-bold mb-1">{pkg.credits}</div>
|
||||
<div className="text-sm text-dark-400 mb-2">
|
||||
{pkg.credits === 1 ? t('pricing.creditUnit') : t('pricing.creditsUnit')}
|
||||
</div>
|
||||
<div className="text-xl font-semibold text-primary-400">
|
||||
{formatPrice(pkg.price_cents)}
|
||||
</div>
|
||||
<div className="text-xs text-dark-500">{pricePerVideo(pkg)}{t('pricing.perVideo')}</div>
|
||||
{savings > 0 && (
|
||||
<div className="text-xs text-green-400 mt-1">{t('pricing.saveFmt', { savings })}</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Checkout Form */}
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-2xl p-8 max-w-md mx-auto">
|
||||
<div className="text-center mb-6">
|
||||
<div className="text-sm text-dark-400 mb-1">{t('pricing.selectedPackage')}</div>
|
||||
<div className="text-2xl font-bold">
|
||||
{selectedPackage?.credits} {selectedPackage && selectedPackage.credits === 1 ? t('pricing.creditUnit') : t('pricing.creditsUnit')}
|
||||
</div>
|
||||
<div className="text-3xl font-bold text-primary-400">
|
||||
{selectedPackage && formatPrice(selectedPackage.price_cents)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleCheckout} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
{t('pricing.emailLabel')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder={t('pricing.emailPlaceholder')}
|
||||
className="w-full pl-10 pr-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-dark-500 mt-2">
|
||||
{t('pricing.emailHint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-red-400 text-sm">{error}</p>}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading || !selectedPackage}
|
||||
className="w-full bg-primary-500 hover:bg-primary-600 disabled:bg-primary-500/50 text-white font-semibold py-4 rounded-xl transition-all btn-glow flex items-center justify-center gap-2"
|
||||
>
|
||||
{isLoading ? t('pricing.redirecting') : t('pricing.continuePayment')}
|
||||
{!isLoading && <Check className="w-5 h-5" />}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="mt-4 flex items-center justify-center gap-4 text-xs text-dark-500">
|
||||
<span>{t('pricing.secureCheckout')}</span>
|
||||
<span>{t('pricing.poweredByStripe')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Made For You Section */}
|
||||
<section id="made-for-you" className="py-20 px-4">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
{/* Section Header */}
|
||||
<div className="text-center mb-12">
|
||||
<div className="inline-flex items-center gap-2 bg-yellow-500/20 text-yellow-400 px-4 py-2 rounded-full text-sm font-medium mb-4">
|
||||
<Gift className="w-4 h-4" />
|
||||
{t('madeForYou.badgeLabel')}
|
||||
</div>
|
||||
<h2 className="text-3xl font-bold mb-4">{t('madeForYou.title')}</h2>
|
||||
<p className="text-dark-400 max-w-2xl mx-auto mb-4">
|
||||
{t('madeForYou.subtitle')}
|
||||
</p>
|
||||
<p className="text-dark-500 text-sm max-w-xl mx-auto">
|
||||
{t('madeForYou.secondarySubtitle')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-2 gap-12 items-start">
|
||||
{/* Benefits */}
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold mb-6">{t('madeForYou.benefitsTitle')}</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-xl p-4 flex items-start gap-4">
|
||||
<div className="w-10 h-10 bg-primary-500/20 rounded-lg flex items-center justify-center shrink-0">
|
||||
<FileVideo className="w-5 h-5 text-primary-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium">{t('madeForYou.benefit1Title')}</h4>
|
||||
<p className="text-dark-400 text-sm mt-1">
|
||||
{t('madeForYou.benefit1Desc')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-xl p-4 flex items-start gap-4">
|
||||
<div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center shrink-0">
|
||||
<Clock className="w-5 h-5 text-purple-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium">{t('madeForYou.benefit2Title')}</h4>
|
||||
<p className="text-dark-400 text-sm mt-1">
|
||||
{t('madeForYou.benefit2Desc')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-xl p-4 flex items-start gap-4">
|
||||
<div className="w-10 h-10 bg-yellow-500/20 rounded-lg flex items-center justify-center shrink-0">
|
||||
<Gift className="w-5 h-5 text-yellow-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium">{t('madeForYou.benefit3Title')}</h4>
|
||||
<p className="text-dark-400 text-sm mt-1">
|
||||
{t('madeForYou.benefit3Desc')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<a
|
||||
href="https://www.youtube.com/@nomadkaraoke"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="bg-dark-800 border border-dark-700 rounded-xl p-4 flex items-start gap-4 hover:border-red-500/40 transition-colors group"
|
||||
>
|
||||
<div className="w-10 h-10 bg-red-500/20 rounded-lg flex items-center justify-center shrink-0">
|
||||
<Youtube className="w-5 h-5 text-red-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium group-hover:text-red-400 transition-colors">{t('madeForYou.benefit4Title')}</h4>
|
||||
<p className="text-dark-400 text-sm mt-1">
|
||||
{t('madeForYou.benefit4Desc')}
|
||||
</p>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Delivery includes */}
|
||||
<div className="mt-8 p-4 bg-dark-800 border border-dark-700 rounded-xl">
|
||||
<h4 className="font-medium mb-3">{t('madeForYou.deliveryIncludesTitle')}</h4>
|
||||
<ul className="space-y-2 text-sm text-dark-400">
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
{t('madeForYou.delivery1')}
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
{t('madeForYou.delivery2')}
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
{t('madeForYou.delivery3')}
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
{t('madeForYou.delivery4')}
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
{t('madeForYou.delivery5')}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Order Form */}
|
||||
<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">{t('madeForYou.orderFormTitle')}</h3>
|
||||
<div className="text-2xl font-bold text-primary-400">{t('madeForYou.orderPrice')}</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleMadeForYouSubmit} className="space-y-5">
|
||||
{/* Artist */}
|
||||
<div>
|
||||
<label htmlFor="mfy-artist" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
{t('madeForYou.artistLabel')} <span className="text-red-400">{t('madeForYou.requiredField')}</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="mfy-artist"
|
||||
value={mfyArtist}
|
||||
onChange={(e) => setMfyArtist(e.target.value)}
|
||||
placeholder={t('madeForYou.artistPlaceholder')}
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<div>
|
||||
<label htmlFor="mfy-title" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
{t('madeForYou.titleLabel')} <span className="text-red-400">{t('madeForYou.requiredField')}</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="mfy-title"
|
||||
value={mfyTitle}
|
||||
onChange={(e) => setMfyTitle(e.target.value)}
|
||||
placeholder={t('madeForYou.titlePlaceholder')}
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Source Type */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-dark-300 mb-2">
|
||||
{t('madeForYou.audioSourceLabel')}
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMfySourceType('search')}
|
||||
className={`flex flex-col items-center gap-1 p-3 rounded-lg border transition-all ${
|
||||
mfySourceType === 'search'
|
||||
? 'border-primary-500 bg-primary-500/10 text-primary-400'
|
||||
: 'border-dark-700 text-dark-400 hover:border-dark-500'
|
||||
}`}
|
||||
>
|
||||
<Search className="w-5 h-5" />
|
||||
<span className="text-xs">{t('madeForYou.autoSearchLabel')}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMfySourceType('youtube')}
|
||||
className={`flex flex-col items-center gap-1 p-3 rounded-lg border transition-all ${
|
||||
mfySourceType === 'youtube'
|
||||
? 'border-primary-500 bg-primary-500/10 text-primary-400'
|
||||
: 'border-dark-700 text-dark-400 hover:border-dark-500'
|
||||
}`}
|
||||
>
|
||||
<LinkIcon className="w-5 h-5" />
|
||||
<span className="text-xs">{t('madeForYou.youtubeUrlLabel')}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMfySourceType('upload')}
|
||||
className={`flex flex-col items-center gap-1 p-3 rounded-lg border transition-all ${
|
||||
mfySourceType === 'upload'
|
||||
? 'border-primary-500 bg-primary-500/10 text-primary-400'
|
||||
: 'border-dark-700 text-dark-400 hover:border-dark-500'
|
||||
}`}
|
||||
>
|
||||
<Upload className="w-5 h-5" />
|
||||
<span className="text-xs">{t('madeForYou.fileUploadLabel')}</span>
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-dark-500">
|
||||
{mfySourceType === 'search' && t('madeForYou.autoSearchHint')}
|
||||
{mfySourceType === 'youtube' && t('madeForYou.youtubeUrlHint')}
|
||||
{mfySourceType === 'upload' && t('madeForYou.fileUploadHint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* YouTube URL (conditional) */}
|
||||
{mfySourceType === 'youtube' && (
|
||||
<div>
|
||||
<label htmlFor="mfy-youtube" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
{t('madeForYou.youtubeUrlFieldLabel')}
|
||||
</label>
|
||||
<input
|
||||
type="url"
|
||||
id="mfy-youtube"
|
||||
value={mfyYoutubeUrl}
|
||||
onChange={(e) => setMfyYoutubeUrl(e.target.value)}
|
||||
placeholder={t('madeForYou.youtubeUrlPlaceholder')}
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="mfy-email" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
{t('madeForYou.emailLabel2')} <span className="text-red-400">{t('madeForYou.requiredField')}</span>
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
id="mfy-email"
|
||||
value={mfyEmail}
|
||||
onChange={(e) => setMfyEmail(e.target.value)}
|
||||
placeholder={t('madeForYou.emailPlaceholder2')}
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-dark-500">
|
||||
{t('madeForYou.emailHint2')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Notes (optional) */}
|
||||
<div>
|
||||
<label htmlFor="mfy-notes" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
{t('madeForYou.notesLabel')} <span className="text-dark-500">{t('madeForYou.notesOptional')}</span>
|
||||
</label>
|
||||
<textarea
|
||||
id="mfy-notes"
|
||||
value={mfyNotes}
|
||||
onChange={(e) => setMfyNotes(e.target.value)}
|
||||
rows={3}
|
||||
placeholder={t('madeForYou.notesPlaceholder')}
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{mfyError && <p className="text-red-400 text-sm">{mfyError}</p>}
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={mfyLoading}
|
||||
className="w-full bg-primary-500 hover:bg-primary-600 disabled:bg-primary-500/50 text-white font-semibold py-4 rounded-xl transition-all btn-glow flex items-center justify-center gap-2"
|
||||
>
|
||||
{mfyLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
{t('madeForYou.processing')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CreditCard className="w-5 h-5" />
|
||||
{t('madeForYou.submitButton')}
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<p className="text-xs text-center text-dark-500">
|
||||
{t('madeForYou.paymentDisclaimer')}
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* FAQ */}
|
||||
<section className="py-16 px-4 bg-dark-800/50">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-center mb-12">{t('faq.title')}</h2>
|
||||
<div className="space-y-4">
|
||||
{faqs.map((faq, i) => (
|
||||
<div key={i} className="bg-dark-800 border border-dark-700 rounded-xl p-6">
|
||||
<h3 className="font-medium mb-2">{faq.question}</h3>
|
||||
<p className="text-dark-400 text-sm">{faq.answer}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="py-12 px-4 border-t border-primary-500/30">
|
||||
<div className="max-w-6xl mx-auto flex flex-col md:flex-row items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8" />
|
||||
</div>
|
||||
<div className="text-sm text-dark-500">
|
||||
{t('footer.copyright', { year: new Date().getFullYear() })}
|
||||
</div>
|
||||
<div className="flex gap-6 text-sm text-dark-400">
|
||||
<a href="mailto:support@nomadkaraoke.com" className="hover:text-primary-400 transition-colors">
|
||||
{t('footer.supportLink')}
|
||||
</a>
|
||||
<a href={`https://nomadkaraoke.com/${locale}/`} className="hover:text-primary-400 transition-colors">
|
||||
{t('footer.aboutLink')}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
{/* Auth Dialog for sign-in */}
|
||||
<AuthDialog
|
||||
open={showAuthDialog}
|
||||
onClose={() => setShowAuthDialog(false)}
|
||||
onSuccess={handleAuthSuccess}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
"use client"
|
||||
|
||||
import { Suspense, useEffect, useState } from "react"
|
||||
import { useRouter } from "@/i18n/routing"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { CheckCircle, Loader2, Coins } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useTranslations } from "next-intl"
|
||||
|
||||
function PaymentSuccessContent() {
|
||||
const t = useTranslations('payment')
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
const { user, fetchUser } = useAuth()
|
||||
|
||||
useEffect(() => {
|
||||
// Refresh user data to get updated credits
|
||||
const refreshUser = async () => {
|
||||
await fetchUser()
|
||||
setIsLoading(false)
|
||||
}
|
||||
refreshUser()
|
||||
}, [fetchUser])
|
||||
|
||||
const sessionId = searchParams.get("session_id")
|
||||
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<CheckCircle className="w-16 h-16 text-success mx-auto mb-4" />
|
||||
|
||||
<h1 className="text-2xl font-bold text-foreground mb-2">
|
||||
{t('title')}
|
||||
</h1>
|
||||
|
||||
<p className="text-muted-foreground mb-6">
|
||||
{t('description')}
|
||||
</p>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center gap-2 text-muted-foreground mb-6">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
{t('loadingBalance')}
|
||||
</div>
|
||||
) : user ? (
|
||||
<div className="bg-secondary rounded-lg p-4 mb-6">
|
||||
<div className="flex items-center justify-center gap-2 text-warning">
|
||||
<Coins className="w-5 h-5" />
|
||||
<span className="text-2xl font-bold">{user.credits}</span>
|
||||
<span className="text-muted-foreground">{t('creditsAvailable')}</span>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
onClick={() => router.push("/app")}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
{t('startCreating')}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('confirmationEmail')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PaymentLoadingFallback() {
|
||||
const tCommon = useTranslations('common')
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<Loader2 className="w-16 h-16 text-primary mx-auto mb-4 animate-spin" />
|
||||
<p className="text-muted-foreground">{tCommon('loading')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function PaymentSuccessPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<Suspense fallback={<PaymentLoadingFallback />}>
|
||||
<PaymentSuccessContent />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,16 +1,14 @@
|
||||
import { JobRouterClient } from "./client"
|
||||
import { LocaleRedirect } from "@/components/LocaleRedirect"
|
||||
|
||||
// Required for static export with catch-all routes
|
||||
// Returns params array for paths to pre-render at build time
|
||||
// Preserve static params for local mode CLI paths
|
||||
export async function generateStaticParams(): Promise<{ slug?: string[] }[]> {
|
||||
return [
|
||||
{ slug: undefined }, // /app/jobs/
|
||||
// Local mode paths - pre-rendered for karaoke-gen CLI local review
|
||||
{ slug: ['local', 'review'] }, // /app/jobs/local/review
|
||||
{ slug: ['local', 'instrumental'] }, // /app/jobs/local/instrumental
|
||||
{ slug: undefined },
|
||||
{ slug: ['local', 'review'] },
|
||||
{ slug: ['local', 'instrumental'] },
|
||||
]
|
||||
}
|
||||
|
||||
export default function JobsPage() {
|
||||
return <JobRouterClient />
|
||||
export default function JobsRedirect() {
|
||||
return <LocaleRedirect />
|
||||
}
|
||||
+3
-507
@@ -1,509 +1,5 @@
|
||||
"use client"
|
||||
import { LocaleRedirect } from "@/components/LocaleRedirect"
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo, Suspense, useRef } from "react"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import { api, Job, getAccessToken } from "@/lib/api"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { useJobNotifications, useVisibilityRefresh } from "@/hooks/use-notifications"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Music2, RefreshCw, Loader2, Moon, Sun, Search, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone } from "lucide-react"
|
||||
import { sortJobsByDate } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
import { TenantJobFlow } from "@/components/job/TenantJobFlow"
|
||||
import { TenantLogo } from "@/components/tenant-logo"
|
||||
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 { useTenant } from "@/lib/tenant"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
|
||||
function AppPageContent() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [allJobs, setAllJobs] = useState<Job[]>([])
|
||||
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
|
||||
const [isInitialLoad, setIsInitialLoad] = useState(true)
|
||||
const [hasFetchedSuccessfully, setHasFetchedSuccessfully] = useState(false)
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
|
||||
const [isVerifyingToken, setIsVerifyingToken] = useState(false)
|
||||
const adminTokenHandled = useRef(false) // Track if admin_token was already processed
|
||||
const { isDarkMode, toggleTheme, mounted } = useTheme()
|
||||
const { user, fetchUser, verifyMagicLink } = useAuth()
|
||||
const { isDefault: isDefaultTenant, branding } = useTenant()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [jobLimit, setJobLimit] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 10
|
||||
const saved = localStorage.getItem("nomad-karaoke-job-limit")
|
||||
return saved ? Number(saved) : 10
|
||||
})
|
||||
const [statusFilter, setStatusFilter] = useState<string>(() => {
|
||||
if (typeof window === "undefined") return "active"
|
||||
return localStorage.getItem("nomad-karaoke-status-filter") || "active"
|
||||
})
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [showAdminControls, setShowAdminControls] = useState<boolean>(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-karaoke-admin-controls") === "true"
|
||||
})
|
||||
const [feedbackBannerDismissed, setFeedbackBannerDismissed] = useState(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-feedback-banner-dismissed") === "true"
|
||||
})
|
||||
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 jobs = useMemo(
|
||||
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
|
||||
[allJobs]
|
||||
)
|
||||
|
||||
// Debounce search input — only update the query (which triggers API calls) after 300ms
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setSearchQuery(searchInput), 300)
|
||||
return () => clearTimeout(timer)
|
||||
}, [searchInput])
|
||||
|
||||
// Memoize loadJobs for use with visibility refresh
|
||||
const loadJobs = useCallback(async () => {
|
||||
if (!getAccessToken()) {
|
||||
setIsLoadingJobs(false)
|
||||
setIsInitialLoad(false)
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = await api.listJobs({
|
||||
limit: jobLimit,
|
||||
exclude_test: isAdmin ? !showTestData : undefined,
|
||||
fields: 'summary',
|
||||
status: statusFilter !== 'all' && statusFilter !== 'active' ? statusFilter : undefined,
|
||||
hide_completed: statusFilter === 'active' ? true : undefined,
|
||||
search: searchQuery || undefined,
|
||||
})
|
||||
setAllJobs(sortJobsByDate(data))
|
||||
} catch (err: any) {
|
||||
if (err?.status !== 401) {
|
||||
console.error("Failed to load jobs:", err)
|
||||
}
|
||||
} finally {
|
||||
setIsLoadingJobs(false)
|
||||
setIsInitialLoad(false)
|
||||
setHasFetchedSuccessfully(true)
|
||||
}
|
||||
}, [isAdmin, showTestData, jobLimit, statusFilter, searchQuery])
|
||||
|
||||
// Enable notifications for job status changes (sound + title animation)
|
||||
useJobNotifications(allJobs)
|
||||
|
||||
// Refresh jobs immediately when tab becomes visible (after returning from review UIs)
|
||||
useVisibilityRefresh(loadJobs, isAuthenticated === true)
|
||||
|
||||
// Handle admin_token URL parameter for one-click login from email
|
||||
useEffect(() => {
|
||||
const adminToken = searchParams.get("admin_token")
|
||||
|
||||
// Only process admin_token once (use ref to prevent repeated calls)
|
||||
if (adminToken && !adminTokenHandled.current) {
|
||||
adminTokenHandled.current = true
|
||||
setIsVerifyingToken(true)
|
||||
|
||||
verifyMagicLink(adminToken).then((success) => {
|
||||
// Clean URL by removing the token
|
||||
window.history.replaceState({}, '', '/app')
|
||||
setIsVerifyingToken(false)
|
||||
if (success) {
|
||||
setIsAuthenticated(true)
|
||||
} else {
|
||||
router.replace('/')
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Normal auth check (skip if admin_token is being processed)
|
||||
if (adminToken || isVerifyingToken) return
|
||||
|
||||
const token = getAccessToken()
|
||||
if (!token) {
|
||||
// Redirect to landing page if not authenticated
|
||||
router.replace('/')
|
||||
return
|
||||
}
|
||||
setIsAuthenticated(true)
|
||||
}, [router, searchParams, verifyMagicLink, isVerifyingToken])
|
||||
|
||||
// Ensure user data is loaded after authentication
|
||||
// This handles the case where user navigates via client-side navigation
|
||||
// (e.g., after beta enrollment) and the module-level fetchUser() didn't run
|
||||
useEffect(() => {
|
||||
const token = getAccessToken()
|
||||
if (token && !user) {
|
||||
fetchUser()
|
||||
}
|
||||
}, [user, fetchUser])
|
||||
|
||||
// Load jobs on mount (only if authenticated)
|
||||
useEffect(() => {
|
||||
if (isAuthenticated !== true) {
|
||||
setIsLoadingJobs(false)
|
||||
return
|
||||
}
|
||||
loadJobs()
|
||||
// Poll for updates every 10 seconds
|
||||
const interval = setInterval(loadJobs, 10000)
|
||||
return () => clearInterval(interval)
|
||||
}, [isAuthenticated, loadJobs])
|
||||
|
||||
// Show nothing while checking auth or verifying admin token (prevents flash)
|
||||
if (isAuthenticated === null || isVerifyingToken) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center animated-gradient">
|
||||
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--text-muted)' }} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Show warming up loader during initial job load (cold start scenario)
|
||||
if (isInitialLoad && isLoadingJobs) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center animated-gradient">
|
||||
<WarmingUpLoader spinnerClassName="w-10 h-10" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen animated-gradient">
|
||||
{/* AutoProcessor - handles non-interactive mode for jobs with that flag */}
|
||||
<AutoProcessor jobs={allJobs} onJobsChanged={loadJobs} />
|
||||
|
||||
{/* Header */}
|
||||
<header className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
|
||||
<div className="px-3 sm:px-4 py-2 sm:py-3 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 sm:gap-3 min-w-0">
|
||||
{isDefaultTenant ? (
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 sm:h-10 shrink-0" />
|
||||
) : (
|
||||
<TenantLogo size="sm" />
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-base sm:text-xl font-bold truncate" style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? "Karaoke Generator" : branding.site_title}
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={loadJobs}
|
||||
disabled={isLoadingJobs || !isAuthenticated}
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<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>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<HelpCircle className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64">
|
||||
<DropdownMenuLabel className="text-sm font-normal">
|
||||
Something confusing or not working? Reach out anytime!
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="mailto:andrew@nomadkaraoke.com">
|
||||
<Mail className="w-4 h-4 mr-2" />
|
||||
andrew@nomadkaraoke.com
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="tel:+18036363267">
|
||||
<Phone className="w-4 h-4 mr-2" />
|
||||
+1 (803) 636-3267
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<AuthStatus />
|
||||
{mounted && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={toggleTheme}
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
{isDarkMode ? (
|
||||
<Sun className="w-4 h-4" />
|
||||
) : (
|
||||
<Moon className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
<p>{isDarkMode ? "Switch to light mode" : "Switch to dark mode"}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</div>
|
||||
</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 (consumer portal only) */}
|
||||
{isDefaultTenant && 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 1 free credit!</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={() => {
|
||||
localStorage.setItem("nomad-feedback-banner-dismissed", "true")
|
||||
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)' }}>
|
||||
{isDefaultTenant ? "Create Karaoke Video" : "Submit Track"}
|
||||
</CardTitle>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
{isDefaultTenant
|
||||
? "Turn any song into a karaoke video with synced lyrics"
|
||||
: "Upload your mixed audio and instrumental"}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isDefaultTenant ? (
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
) : (
|
||||
<TenantJobFlow onJobCreated={loadJobs} />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Jobs List Card */}
|
||||
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
|
||||
<CardHeader className="px-3 sm:px-6">
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<div className="flex items-center gap-2">
|
||||
<CardTitle style={{ color: 'var(--text)' }}>Recent Jobs</CardTitle>
|
||||
{isLoadingJobs && <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--text-muted)' }} />}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5" style={{ color: 'var(--text-muted)' }} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search..."
|
||||
aria-label="Search jobs"
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="h-7 w-[160px] sm:w-[200px] text-xs rounded-md border pl-7 pr-2"
|
||||
style={{
|
||||
backgroundColor: 'var(--input)',
|
||||
borderColor: 'var(--border)',
|
||||
color: 'var(--text)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Select value={statusFilter} onValueChange={(v) => {
|
||||
setStatusFilter(v)
|
||||
localStorage.setItem("nomad-karaoke-status-filter", v)
|
||||
}}>
|
||||
<SelectTrigger className="h-7 w-[130px] text-xs" aria-label="Filter by status">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All statuses</SelectItem>
|
||||
<SelectItem value="active">Active</SelectItem>
|
||||
<SelectItem value="failed">Failed</SelectItem>
|
||||
<SelectItem value="complete">Completed</SelectItem>
|
||||
<SelectItem value="cancelled">Cancelled</SelectItem>
|
||||
<SelectItem value="awaiting_review">Awaiting review</SelectItem>
|
||||
<SelectItem value="processing">Processing</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={String(jobLimit)} onValueChange={(v) => {
|
||||
const val = Number(v)
|
||||
setJobLimit(val)
|
||||
localStorage.setItem("nomad-karaoke-job-limit", String(val))
|
||||
}}>
|
||||
<SelectTrigger className="h-7 w-[70px] text-xs" aria-label="Results per page">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="5">5</SelectItem>
|
||||
<SelectItem value="10">10</SelectItem>
|
||||
<SelectItem value="20">20</SelectItem>
|
||||
<SelectItem value="50">50</SelectItem>
|
||||
<SelectItem value="100">100</SelectItem>
|
||||
<SelectItem value="1000">1000</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
{!hasFetchedSuccessfully
|
||||
? 'Loading...'
|
||||
: searchQuery || statusFilter !== 'active'
|
||||
? `${jobs.length} job${jobs.length !== 1 ? 's' : ''} matching filters`
|
||||
: `${jobs.length} job${jobs.length !== 1 ? 's' : ''}`}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="px-3 sm:px-6">
|
||||
{jobs.length === 0 ? (
|
||||
<div className="text-center py-8" style={{ color: 'var(--text-muted)' }}>
|
||||
{!hasFetchedSuccessfully ? (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 mx-auto mb-3 opacity-50 animate-spin" />
|
||||
<p>Loading jobs...</p>
|
||||
</>
|
||||
) : searchQuery || statusFilter !== 'active' ? (
|
||||
<>
|
||||
<Search className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>No jobs match your filters.</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>No jobs yet. Create one to get started!</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{jobs.map((job) => (
|
||||
<JobCard key={job.job_id} job={job} onRefresh={loadJobs} showAdminControls={isAdmin && showAdminControls} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<VersionFooter />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Wrap with Suspense for useSearchParams
|
||||
export default function AppPage() {
|
||||
return (
|
||||
<Suspense fallback={
|
||||
<div className="min-h-screen flex items-center justify-center animated-gradient">
|
||||
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--text-muted)' }} />
|
||||
</div>
|
||||
}>
|
||||
<AppPageContent />
|
||||
</Suspense>
|
||||
)
|
||||
export default function DashboardRedirect() {
|
||||
return <LocaleRedirect />
|
||||
}
|
||||
@@ -1,277 +1,5 @@
|
||||
"use client"
|
||||
import { LocaleRedirect } from "@/components/LocaleRedirect"
|
||||
|
||||
import { Suspense, useEffect, useState, useRef } from "react"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import { Loader2, CheckCircle, XCircle, Gift, ShoppingCart } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
|
||||
type VerifyState = "verifying" | "preparing" | "credits_granted" | "credits_denied" | "credits_pending" | "success" | "error"
|
||||
|
||||
function VerifyMagicLinkContent() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [state, setState] = useState<VerifyState>("verifying")
|
||||
const [errorMessage, setErrorMessage] = useState("")
|
||||
const [creditsGranted, setCreditsGranted] = useState(0)
|
||||
const [creditStatus, setCreditStatus] = useState<string>("not_applicable")
|
||||
const hasVerified = useRef(false)
|
||||
|
||||
const { verifyMagicLink, user, error } = useAuth()
|
||||
|
||||
useEffect(() => {
|
||||
if (hasVerified.current) return
|
||||
hasVerified.current = true
|
||||
|
||||
const token = searchParams.get("token")
|
||||
|
||||
if (!token) {
|
||||
setState("error")
|
||||
setErrorMessage("No verification token provided")
|
||||
return
|
||||
}
|
||||
|
||||
const verify = async () => {
|
||||
// Show "preparing your account" while the backend runs AI evaluation
|
||||
setState("preparing")
|
||||
|
||||
const success = await verifyMagicLink(token)
|
||||
if (success) {
|
||||
const lastVerifyResponse = (window as any).__LAST_VERIFY_RESPONSE__
|
||||
const credits = lastVerifyResponse?.credits_granted || 0
|
||||
const status = lastVerifyResponse?.credit_status || "not_applicable"
|
||||
setCreditsGranted(credits)
|
||||
setCreditStatus(status)
|
||||
|
||||
// Check for tenant subdomain redirect
|
||||
if (lastVerifyResponse?.tenant_subdomain) {
|
||||
const currentHost = window.location.hostname.toLowerCase()
|
||||
const tenantSubdomain = lastVerifyResponse.tenant_subdomain.toLowerCase()
|
||||
if (currentHost !== tenantSubdomain) {
|
||||
setState("success")
|
||||
setTimeout(() => {
|
||||
window.location.href = `https://${tenantSubdomain}/app`
|
||||
}, 1500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Show appropriate interstitial based on credit status
|
||||
if (status === "granted" && credits > 0) {
|
||||
setState("credits_granted")
|
||||
} else if (status === "denied") {
|
||||
setState("credits_denied")
|
||||
} else if (status === "pending_review") {
|
||||
setState("credits_pending")
|
||||
} else {
|
||||
// Returning user or not applicable — go straight to app
|
||||
setState("success")
|
||||
setTimeout(() => {
|
||||
router.push("/app")
|
||||
}, 1500)
|
||||
}
|
||||
} else {
|
||||
setState("error")
|
||||
const authStore = useAuth.getState()
|
||||
setErrorMessage(authStore.error || "Invalid or expired link")
|
||||
}
|
||||
}
|
||||
|
||||
verify()
|
||||
}, [searchParams, verifyMagicLink, router])
|
||||
|
||||
const goToApp = () => router.push("/app")
|
||||
const goToBuy = () => router.push("/app?buy=true")
|
||||
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
{/* Verifying token */}
|
||||
{state === "verifying" && (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Verifying your sign-in link...
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Please wait while we sign you in.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Preparing account (AI evaluation running) */}
|
||||
{state === "preparing" && (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Preparing your account...
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Just a moment while we set things up for you.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Credits granted - celebratory interstitial */}
|
||||
{state === "credits_granted" && (
|
||||
<>
|
||||
<div className="relative mx-auto mb-4 w-16 h-16">
|
||||
<Gift className="w-16 h-16 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-foreground mb-2">
|
||||
Welcome to Nomad Karaoke!
|
||||
</h1>
|
||||
<div className="bg-primary/10 border border-primary/20 rounded-lg p-4 mb-4">
|
||||
<p className="text-3xl font-bold text-primary">{creditsGranted}</p>
|
||||
<p className="text-sm font-medium text-primary/80">free credits to get started</p>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-2">
|
||||
Each credit creates one professional karaoke video.
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mb-6">
|
||||
These credits cost us real money to fulfil, so please use them wisely
|
||||
and let us know what you think!
|
||||
</p>
|
||||
<Button
|
||||
onClick={goToApp}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
Start Creating Karaoke
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Credits denied - friendly rejection interstitial */}
|
||||
{state === "credits_denied" && (
|
||||
<>
|
||||
<XCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Welcome to Nomad Karaoke
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
We weren't able to grant free credits this time.
|
||||
Karaoke generation costs us real money for every job,
|
||||
so we need to be careful about free credit distribution.
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
If you think this is a mistake, check your email — we've sent you
|
||||
details on how to reach out to get this resolved.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={goToBuy}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
<ShoppingCart className="w-4 h-4 mr-2" />
|
||||
Buy Credits
|
||||
</Button>
|
||||
<Button
|
||||
onClick={goToApp}
|
||||
variant="ghost"
|
||||
className="w-full"
|
||||
>
|
||||
Go to Dashboard
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Credits pending review - friendly holding message */}
|
||||
{state === "credits_pending" && (
|
||||
<>
|
||||
<Loader2 className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Welcome to Nomad Karaoke!
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
We weren't able to assign your free credits automatically this time.
|
||||
Our team will review your signup shortly and assign credits if we're able to.
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
You can still explore the app while you wait, or purchase credits
|
||||
to get started right away.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={goToBuy}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
<ShoppingCart className="w-4 h-4 mr-2" />
|
||||
Buy Credits
|
||||
</Button>
|
||||
<Button
|
||||
onClick={goToApp}
|
||||
variant="ghost"
|
||||
className="w-full"
|
||||
>
|
||||
Explore the App
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Simple success (returning user) */}
|
||||
{state === "success" && (
|
||||
<>
|
||||
<CheckCircle className="w-12 h-12 text-success mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Successfully signed in!
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
Welcome back{user?.email ? `, ${user.email}` : ""}!
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Redirecting you to the app...
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{state === "error" && (
|
||||
<>
|
||||
<XCircle className="w-12 h-12 text-destructive mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Sign-in failed
|
||||
</h1>
|
||||
<p className="text-muted-foreground mb-6">
|
||||
{errorMessage || "The link may have expired or already been used."}
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={() => router.push("/app")}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
Go to App
|
||||
</Button>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
You can request a new sign-in link from the app.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function VerifyLoadingFallback() {
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
|
||||
<h1 className="text-xl font-semibold text-foreground mb-2">
|
||||
Loading...
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Please wait.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function VerifyMagicLinkPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<Suspense fallback={<VerifyLoadingFallback />}>
|
||||
<VerifyMagicLinkContent />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
export default function VerifyRedirect() {
|
||||
return <LocaleRedirect />
|
||||
}
|
||||
+14
-11
@@ -3,6 +3,7 @@ import type { Metadata } from "next"
|
||||
import localFont from "next/font/local"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { TenantProvider } from "@/components/tenant-provider"
|
||||
import { DefaultIntlProvider } from "@/components/default-intl-provider"
|
||||
import { ImpersonationBannerWrapper } from "@/components/impersonation-banner-wrapper"
|
||||
import { ServiceWorkerRegistration } from "@/components/service-worker-registration"
|
||||
import { GoogleAnalytics } from "@/components/google-analytics"
|
||||
@@ -40,17 +41,19 @@ export default function RootLayout({
|
||||
<body className={`font-sans antialiased ${titleCardFont.variable}`} style={{ background: 'var(--bg)', color: 'var(--text)' }}>
|
||||
<GoogleAnalytics />
|
||||
<ServiceWorkerRegistration />
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="dark"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
>
|
||||
<TenantProvider>
|
||||
<ImpersonationBannerWrapper />
|
||||
{children}
|
||||
</TenantProvider>
|
||||
</ThemeProvider>
|
||||
<DefaultIntlProvider>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="dark"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
>
|
||||
<TenantProvider>
|
||||
<ImpersonationBannerWrapper />
|
||||
{children}
|
||||
</TenantProvider>
|
||||
</ThemeProvider>
|
||||
</DefaultIntlProvider>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
|
||||
@@ -1,79 +1,5 @@
|
||||
"use client"
|
||||
import { LocaleRedirect } from "@/components/LocaleRedirect"
|
||||
|
||||
import { Suspense } from "react"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { CheckCircle, Loader2, Mail, Clock } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
function OrderSuccessContent() {
|
||||
const searchParams = useSearchParams()
|
||||
const sessionId = searchParams.get("session_id")
|
||||
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<CheckCircle className="w-16 h-16 text-success mx-auto mb-4" />
|
||||
|
||||
<h1 className="text-2xl font-bold text-foreground mb-2">
|
||||
Order Confirmed!
|
||||
</h1>
|
||||
|
||||
<p className="text-muted-foreground mb-6">
|
||||
Thank you for your order. We're creating your custom karaoke video now.
|
||||
</p>
|
||||
|
||||
<div className="space-y-4 mb-6">
|
||||
<div className="flex items-center gap-3 text-left p-3 bg-secondary rounded-lg">
|
||||
<Clock className="w-5 h-5 text-primary flex-shrink-0" />
|
||||
<div>
|
||||
<p className="font-medium text-foreground">Delivery within 24 hours</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Most orders are completed in just a few hours
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 text-left p-3 bg-secondary rounded-lg">
|
||||
<Mail className="w-5 h-5 text-primary flex-shrink-0" />
|
||||
<div>
|
||||
<p className="font-medium text-foreground">Check your email</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
We'll send your video when it's ready
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
asChild
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
<a href="https://nomadkaraoke.com">
|
||||
Back to Nomad Karaoke
|
||||
</a>
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Questions? Email us at help@nomadkaraoke.com
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function OrderSuccessPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<Loader2 className="w-16 h-16 text-primary mx-auto mb-4 animate-spin" />
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<OrderSuccessContent />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
export default function OrderRedirect() {
|
||||
return <LocaleRedirect />
|
||||
}
|
||||
+3
-881
@@ -1,883 +1,5 @@
|
||||
'use client';
|
||||
import { LocaleRedirect } from "@/components/LocaleRedirect"
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Image from 'next/image';
|
||||
import {
|
||||
Music,
|
||||
Sparkles,
|
||||
Video,
|
||||
Youtube,
|
||||
Check,
|
||||
Gift,
|
||||
Mail,
|
||||
Loader2,
|
||||
Search,
|
||||
Link as LinkIcon,
|
||||
Upload,
|
||||
Clock,
|
||||
FileVideo,
|
||||
CreditCard,
|
||||
} from 'lucide-react';
|
||||
import { api, setAccessToken, getAccessToken, CreditPackage } from '@/lib/api';
|
||||
import { AuthDialog } from '@/components/auth/AuthDialog';
|
||||
import { WarmingUpLoader } from '@/components/WarmingUpLoader';
|
||||
import { ThemeToggle } from '@/components/ThemeToggle';
|
||||
import { useTenant } from '@/lib/tenant';
|
||||
import { TenantLandingPage } from '@/components/TenantLandingPage';
|
||||
|
||||
// Build-time constant: when true, this build is for tenant portals only
|
||||
const IS_TENANT_PORTAL = process.env.NEXT_PUBLIC_TENANT_PORTAL === 'true';
|
||||
|
||||
// FAQ data
|
||||
const faqs = [
|
||||
{
|
||||
question: 'How does it work?',
|
||||
answer:
|
||||
'Enter an artist and song title (or paste a YouTube link, or upload your own audio file). Our system finds the audio, separates the vocals from the instrumental, transcribes the lyrics, and syncs them to the music. You then review and correct any transcription errors before we generate your final karaoke video.',
|
||||
},
|
||||
{
|
||||
question: 'What songs can I use?',
|
||||
answer:
|
||||
'Any song! Search by artist and title, paste a YouTube URL, or upload your own audio file. If you can get the audio, we can make it into karaoke.',
|
||||
},
|
||||
{
|
||||
question: 'What format is the output?',
|
||||
answer:
|
||||
'You get multiple files: a 4K MP4 karaoke video, a "With Vocals" version for sing-along practice, and a CDG+MP3 ZIP for older karaoke systems. All videos are also published to our YouTube channel for easy sharing.',
|
||||
},
|
||||
{
|
||||
question: 'Do I need to do anything, or is it fully automatic?',
|
||||
answer:
|
||||
"The lyrics transcription is very accurate, but you'll need to review it and correct any misheard words before the final video is generated. For songs with clear vocals, there may be few or no corrections needed. For complex songs, expect to spend 5-10 minutes fixing errors. The word timing/sync is handled automatically and is very precise.",
|
||||
},
|
||||
{
|
||||
question: 'Do credits expire?',
|
||||
answer:
|
||||
'No! Your credits never expire. Use them whenever you want.',
|
||||
},
|
||||
];
|
||||
|
||||
export default function LandingPage() {
|
||||
// Tenant portal builds always render the tenant landing page
|
||||
// This is a build-time constant so the consumer code gets tree-shaken
|
||||
if (IS_TENANT_PORTAL) {
|
||||
return <TenantLandingPage />;
|
||||
}
|
||||
|
||||
return <ConsumerLandingPage />;
|
||||
}
|
||||
|
||||
function ConsumerLandingPage() {
|
||||
const router = useRouter();
|
||||
const { isDefault: isDefaultTenant, isLoading: tenantLoading, isInitialized: tenantInitialized } = useTenant();
|
||||
const [isCheckingAuth, setIsCheckingAuth] = useState(true);
|
||||
const [isMounted, setIsMounted] = useState(false);
|
||||
const [packages, setPackages] = useState<CreditPackage[]>([]);
|
||||
const [packagesLoading, setPackagesLoading] = useState(true);
|
||||
const [packagesError, setPackagesError] = useState<string | null>(null);
|
||||
const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null);
|
||||
const [email, setEmail] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Made For You form state
|
||||
const [mfyArtist, setMfyArtist] = useState('');
|
||||
const [mfyTitle, setMfyTitle] = useState('');
|
||||
const [mfySourceType, setMfySourceType] = useState<'search' | 'youtube' | 'upload'>('search');
|
||||
const [mfyYoutubeUrl, setMfyYoutubeUrl] = useState('');
|
||||
const [mfyEmail, setMfyEmail] = useState('');
|
||||
const [mfyNotes, setMfyNotes] = useState('');
|
||||
const [mfyLoading, setMfyLoading] = useState(false);
|
||||
const [mfyError, setMfyError] = useState<string | null>(null);
|
||||
|
||||
// Auth dialog state
|
||||
const [showAuthDialog, setShowAuthDialog] = useState(false);
|
||||
|
||||
// Track client-side mount to avoid hydration mismatch
|
||||
useEffect(() => {
|
||||
setIsMounted(true);
|
||||
}, []);
|
||||
|
||||
// Check if already logged in and redirect to app
|
||||
useEffect(() => {
|
||||
const token = getAccessToken();
|
||||
if (token) {
|
||||
router.replace('/app');
|
||||
return;
|
||||
}
|
||||
setIsCheckingAuth(false);
|
||||
}, [router]);
|
||||
|
||||
// Handle successful auth from dialog
|
||||
const handleAuthSuccess = () => {
|
||||
setShowAuthDialog(false);
|
||||
router.push('/app');
|
||||
};
|
||||
|
||||
// Load credit packages on mount
|
||||
useEffect(() => {
|
||||
if (isCheckingAuth) return;
|
||||
|
||||
async function loadPackages() {
|
||||
try {
|
||||
const pkgs = await api.getCreditPackages();
|
||||
setPackages(pkgs);
|
||||
// Default to 5 credits (best value)
|
||||
const bestValue = pkgs.find((p) => p.credits === 5);
|
||||
setSelectedPackage(bestValue || pkgs[0]);
|
||||
} catch (err) {
|
||||
console.error('Failed to load packages:', err);
|
||||
setPackagesError('Failed to load pricing. Please refresh the page.');
|
||||
} finally {
|
||||
setPackagesLoading(false);
|
||||
}
|
||||
}
|
||||
loadPackages();
|
||||
}, [isCheckingAuth]);
|
||||
|
||||
// Tenant portals get a minimal landing page (just logo + sign in)
|
||||
// Only check after mount to avoid hydration mismatch with static export
|
||||
// Must be AFTER all hooks to comply with React Rules of Hooks
|
||||
if (isMounted && tenantInitialized && !isDefaultTenant) {
|
||||
return <TenantLandingPage />;
|
||||
}
|
||||
|
||||
// Handle checkout
|
||||
const handleCheckout = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!selectedPackage || !email) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const checkoutUrl = await api.createCheckout(selectedPackage.id, email);
|
||||
// Validate that the URL is a Stripe checkout URL
|
||||
if (!checkoutUrl.startsWith('https://checkout.stripe.com/')) {
|
||||
throw new Error('Invalid checkout URL received');
|
||||
}
|
||||
window.location.href = checkoutUrl;
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create checkout session');
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle Made For You checkout
|
||||
const handleMadeForYouSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setMfyError(null);
|
||||
|
||||
// Validation
|
||||
if (!mfyArtist.trim()) {
|
||||
setMfyError('Please enter the artist name');
|
||||
return;
|
||||
}
|
||||
if (!mfyTitle.trim()) {
|
||||
setMfyError('Please enter the song title');
|
||||
return;
|
||||
}
|
||||
if (!mfyEmail.trim()) {
|
||||
setMfyError('Please enter your email address');
|
||||
return;
|
||||
}
|
||||
if (mfySourceType === 'youtube' && !mfyYoutubeUrl.trim()) {
|
||||
setMfyError('Please enter a YouTube URL');
|
||||
return;
|
||||
}
|
||||
|
||||
setMfyLoading(true);
|
||||
|
||||
try {
|
||||
const checkoutUrl = await api.createMadeForYouCheckout({
|
||||
email: mfyEmail,
|
||||
artist: mfyArtist,
|
||||
title: mfyTitle,
|
||||
source_type: mfySourceType,
|
||||
youtube_url: mfySourceType === 'youtube' ? mfyYoutubeUrl : undefined,
|
||||
notes: mfyNotes || undefined,
|
||||
});
|
||||
|
||||
// Redirect to Stripe Checkout
|
||||
window.location.href = checkoutUrl;
|
||||
} catch (err) {
|
||||
setMfyError(err instanceof Error ? err.message : 'Something went wrong. Please try again.');
|
||||
setMfyLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatPrice = (cents: number) => `$${(cents / 100).toFixed(0)}`;
|
||||
const pricePerVideo = (pkg: CreditPackage) =>
|
||||
`$${(pkg.price_cents / 100 / pkg.credits).toFixed(2)}`;
|
||||
|
||||
// Show loading while checking auth
|
||||
if (isCheckingAuth) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center animated-gradient">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-white" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen animated-gradient">
|
||||
{/* Navigation */}
|
||||
<nav className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
|
||||
<div className="max-w-6xl mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-10" />
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<ThemeToggle />
|
||||
<button
|
||||
onClick={() => setShowAuthDialog(true)}
|
||||
className="px-4 py-2 text-sm font-semibold rounded-lg bg-[var(--brand-pink)] text-white hover:bg-[var(--brand-pink-hover)] hover:scale-105 hover:shadow-[0_0_20px_rgba(255,122,204,0.5)] active:scale-95 transition-all duration-200"
|
||||
>
|
||||
Sign In
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Hero Section */}
|
||||
<section className="pt-32 pb-6 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
|
||||
</h1>
|
||||
<p className="text-xl text-dark-300 mb-8 max-w-2xl mx-auto">
|
||||
Create professional karaoke videos in under 30 minutes. Real instrumentals
|
||||
from the original song, precise lyrics sync, and 4K video output.
|
||||
</p>
|
||||
|
||||
{/* 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)}
|
||||
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">1 free credit included - no payment required</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<a
|
||||
href="#made-for-you"
|
||||
className="inline-flex items-center gap-2 bg-yellow-500/20 hover:bg-yellow-500/30 text-yellow-400 border border-yellow-500/40 font-semibold px-8 py-4 rounded-xl transition-all"
|
||||
>
|
||||
<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>
|
||||
</a>
|
||||
<span className="text-yellow-400/70 text-sm">We handle everything, delivered in 24h</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Demo Video Section */}
|
||||
<section className="py-8 px-4">
|
||||
<div className="max-w-4xl 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/RLkIEHGwFcU"
|
||||
title="Nomad Karaoke Demo"
|
||||
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>
|
||||
</section>
|
||||
|
||||
{/* How It Works */}
|
||||
<section className="py-16 px-4">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-center mb-12">How It Works</h2>
|
||||
<div className="grid md:grid-cols-4 gap-8">
|
||||
{[
|
||||
{ icon: Music, title: 'Choose a Song', desc: 'Search, paste a YouTube link, or upload audio' },
|
||||
{ icon: Sparkles, title: 'We Do the Heavy Lifting', desc: 'Vocals removed, lyrics transcribed & synced' },
|
||||
{ icon: Video, title: 'Review & Correct', desc: 'Fix any transcription errors (usually 5-10 min)' },
|
||||
{ icon: Youtube, title: 'Get Your Video', desc: 'Download files or watch on our YouTube' },
|
||||
].map((step, i) => (
|
||||
<div key={i} className="text-center">
|
||||
<div className="w-16 h-16 bg-primary-500/20 rounded-2xl flex items-center justify-center mx-auto mb-4">
|
||||
<step.icon className="w-8 h-8 text-primary-400" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg mb-2">{step.title}</h3>
|
||||
<p className="text-dark-400 text-sm">{step.desc}</p>
|
||||
</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>
|
||||
|
||||
{/* Features */}
|
||||
<section className="py-16 px-4 bg-dark-800/50">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-center mb-12">What You Get</h2>
|
||||
<div className="grid md:grid-cols-3 gap-6">
|
||||
{[
|
||||
{ title: 'Real Instrumentals', desc: "Uses the actual instrumental from your song—not a cover band or MIDI recreation." },
|
||||
{ title: 'Precise Lyrics Sync', desc: 'Word-by-word timing that highlights exactly when to sing. You review the lyrics for accuracy.' },
|
||||
{ title: 'Keep or Remove Backing Vocals', desc: 'Choose a clean instrumental or one that preserves backing vocals for a fuller sound.' },
|
||||
{ title: '4K Video + Multiple Formats', desc: 'Get a 4K karaoke video, a sing-along version with vocals, and CDG+MP3 for older systems.' },
|
||||
{ title: 'Published to YouTube', desc: 'Every video is automatically published to our YouTube channel for easy sharing.' },
|
||||
{ title: 'Full Control Before Export', desc: 'Review and correct any transcription errors before the final video is generated.' },
|
||||
].map((feature, i) => (
|
||||
<div key={i} className="bg-dark-800 border border-dark-700 rounded-xl p-6 card-hover">
|
||||
<h3 className="font-semibold text-lg mb-2">{feature.title}</h3>
|
||||
<p className="text-dark-400 text-sm">{feature.desc}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Screenshots Section */}
|
||||
<section className="py-16 px-4">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-center mb-4">See It In Action</h2>
|
||||
<p className="text-dark-400 text-center mb-12 max-w-xl mx-auto">
|
||||
Here's what the process looks like at each step
|
||||
</p>
|
||||
<div className="grid md:grid-cols-2 gap-8">
|
||||
{/* Job Creation 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"
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Lyrics Review 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/lyrics-review.avif"
|
||||
alt="Lyrics review with synced lyrics alongside reference lyrics for correction"
|
||||
fill
|
||||
className="object-cover object-top"
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Instrumental Selection 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/instrumental-review.avif"
|
||||
alt="Instrumental review with waveform visualization and backing vocal options"
|
||||
fill
|
||||
className="object-cover object-top"
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Example Output 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/example-output.avif"
|
||||
alt="Completed karaoke job with download options for 4K, 720p, CDG, and more"
|
||||
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>
|
||||
</div>
|
||||
</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 1 free credit, then 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">1 Free Credit</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" />
|
||||
)}
|
||||
{packagesError && (
|
||||
<div className="text-center py-8 text-red-400">
|
||||
{packagesError}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
|
||||
{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 ${
|
||||
isSelected
|
||||
? 'border-primary-500 bg-primary-500/10'
|
||||
: 'border-dark-700 hover:border-dark-500 bg-dark-800/50'
|
||||
}`}
|
||||
>
|
||||
{isBestValue && (
|
||||
<span className="absolute -top-3 left-1/2 -translate-x-1/2 bg-primary-500 text-white text-xs font-semibold px-3 py-1 rounded-full">
|
||||
Best Value
|
||||
</span>
|
||||
)}
|
||||
<div className="text-2xl font-bold mb-1">{pkg.credits}</div>
|
||||
<div className="text-sm text-dark-400 mb-2">
|
||||
{pkg.credits === 1 ? 'credit' : 'credits'}
|
||||
</div>
|
||||
<div className="text-xl font-semibold text-primary-400">
|
||||
{formatPrice(pkg.price_cents)}
|
||||
</div>
|
||||
<div className="text-xs text-dark-500">{pricePerVideo(pkg)}/video</div>
|
||||
{savings > 0 && (
|
||||
<div className="text-xs text-green-400 mt-1">Save {savings}%</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Checkout Form */}
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-2xl p-8 max-w-md mx-auto">
|
||||
<div className="text-center mb-6">
|
||||
<div className="text-sm text-dark-400 mb-1">Selected package</div>
|
||||
<div className="text-2xl font-bold">
|
||||
{selectedPackage?.credits} Credits
|
||||
</div>
|
||||
<div className="text-3xl font-bold text-primary-400">
|
||||
{selectedPackage && formatPrice(selectedPackage.price_cents)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleCheckout} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
Email address
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="you@example.com"
|
||||
className="w-full pl-10 pr-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-dark-500 mt-2">
|
||||
We'll send your login link to this email
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-red-400 text-sm">{error}</p>}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading || !selectedPackage}
|
||||
className="w-full bg-primary-500 hover:bg-primary-600 disabled:bg-primary-500/50 text-white font-semibold py-4 rounded-xl transition-all btn-glow flex items-center justify-center gap-2"
|
||||
>
|
||||
{isLoading ? 'Redirecting...' : 'Continue to Payment'}
|
||||
{!isLoading && <Check className="w-5 h-5" />}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="mt-4 flex items-center justify-center gap-4 text-xs text-dark-500">
|
||||
<span>Secure checkout</span>
|
||||
<span>powered by Stripe</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Made For You Section */}
|
||||
<section id="made-for-you" className="py-20 px-4">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
{/* Section Header */}
|
||||
<div className="text-center mb-12">
|
||||
<div className="inline-flex items-center gap-2 bg-yellow-500/20 text-yellow-400 px-4 py-2 rounded-full text-sm font-medium mb-4">
|
||||
<Gift className="w-4 h-4" />
|
||||
Full-Service Option
|
||||
</div>
|
||||
<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.
|
||||
</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.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-2 gap-12 items-start">
|
||||
{/* Benefits */}
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold mb-6">What You Get</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-xl p-4 flex items-start gap-4">
|
||||
<div className="w-10 h-10 bg-primary-500/20 rounded-lg flex items-center justify-center shrink-0">
|
||||
<FileVideo className="w-5 h-5 text-primary-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium">Professional 4K Video</h4>
|
||||
<p className="text-dark-400 text-sm mt-1">
|
||||
High-quality karaoke video with perfectly synced lyrics
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-xl p-4 flex items-start gap-4">
|
||||
<div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center shrink-0">
|
||||
<Clock className="w-5 h-5 text-purple-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium">24-Hour Delivery</h4>
|
||||
<p className="text-dark-400 text-sm mt-1">
|
||||
We handle everything — just wait for your video to arrive
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-dark-800 border border-dark-700 rounded-xl p-4 flex items-start gap-4">
|
||||
<div className="w-10 h-10 bg-yellow-500/20 rounded-lg flex items-center justify-center shrink-0">
|
||||
<Gift className="w-5 h-5 text-yellow-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium">All Formats Included</h4>
|
||||
<p className="text-dark-400 text-sm mt-1">
|
||||
MP4 video, CDG+MP3 for karaoke machines, audio stems
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<a
|
||||
href="https://www.youtube.com/@nomadkaraoke"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="bg-dark-800 border border-dark-700 rounded-xl p-4 flex items-start gap-4 hover:border-red-500/40 transition-colors group"
|
||||
>
|
||||
<div className="w-10 h-10 bg-red-500/20 rounded-lg flex items-center justify-center shrink-0">
|
||||
<Youtube className="w-5 h-5 text-red-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium group-hover:text-red-400 transition-colors">1000+ Real Examples on YouTube</h4>
|
||||
<p className="text-dark-400 text-sm mt-1">
|
||||
Browse our YouTube channel to see exactly what you'll get
|
||||
</p>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Delivery includes */}
|
||||
<div className="mt-8 p-4 bg-dark-800 border border-dark-700 rounded-xl">
|
||||
<h4 className="font-medium mb-3">Your delivery includes:</h4>
|
||||
<ul className="space-y-2 text-sm text-dark-400">
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
4K lossless MP4 video with title screen
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
720p web-optimized version
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
CDG+MP3 for karaoke machines
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
Instrumental audio (with or without backing vocals)
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
"Sing along" version with original vocals
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Order Form */}
|
||||
<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>
|
||||
|
||||
<form onSubmit={handleMadeForYouSubmit} className="space-y-5">
|
||||
{/* Artist */}
|
||||
<div>
|
||||
<label htmlFor="mfy-artist" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
Artist <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="mfy-artist"
|
||||
value={mfyArtist}
|
||||
onChange={(e) => setMfyArtist(e.target.value)}
|
||||
placeholder="e.g. Taylor Swift"
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<div>
|
||||
<label htmlFor="mfy-title" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
Song Title <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="mfy-title"
|
||||
value={mfyTitle}
|
||||
onChange={(e) => setMfyTitle(e.target.value)}
|
||||
placeholder="e.g. Anti-Hero"
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Source Type */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-dark-300 mb-2">
|
||||
Audio Source
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMfySourceType('search')}
|
||||
className={`flex flex-col items-center gap-1 p-3 rounded-lg border transition-all ${
|
||||
mfySourceType === 'search'
|
||||
? 'border-primary-500 bg-primary-500/10 text-primary-400'
|
||||
: 'border-dark-700 text-dark-400 hover:border-dark-500'
|
||||
}`}
|
||||
>
|
||||
<Search className="w-5 h-5" />
|
||||
<span className="text-xs">Auto Search</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMfySourceType('youtube')}
|
||||
className={`flex flex-col items-center gap-1 p-3 rounded-lg border transition-all ${
|
||||
mfySourceType === 'youtube'
|
||||
? 'border-primary-500 bg-primary-500/10 text-primary-400'
|
||||
: 'border-dark-700 text-dark-400 hover:border-dark-500'
|
||||
}`}
|
||||
>
|
||||
<LinkIcon className="w-5 h-5" />
|
||||
<span className="text-xs">YouTube URL</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMfySourceType('upload')}
|
||||
className={`flex flex-col items-center gap-1 p-3 rounded-lg border transition-all ${
|
||||
mfySourceType === 'upload'
|
||||
? 'border-primary-500 bg-primary-500/10 text-primary-400'
|
||||
: 'border-dark-700 text-dark-400 hover:border-dark-500'
|
||||
}`}
|
||||
>
|
||||
<Upload className="w-5 h-5" />
|
||||
<span className="text-xs">File Upload</span>
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-dark-500">
|
||||
{mfySourceType === 'search' && "We'll automatically find the best quality audio for your song."}
|
||||
{mfySourceType === 'youtube' && 'Provide a YouTube link to the song you want.'}
|
||||
{mfySourceType === 'upload' && 'Upload your own audio file (contact us after ordering).'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* YouTube URL (conditional) */}
|
||||
{mfySourceType === 'youtube' && (
|
||||
<div>
|
||||
<label htmlFor="mfy-youtube" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
YouTube URL
|
||||
</label>
|
||||
<input
|
||||
type="url"
|
||||
id="mfy-youtube"
|
||||
value={mfyYoutubeUrl}
|
||||
onChange={(e) => setMfyYoutubeUrl(e.target.value)}
|
||||
placeholder="https://youtube.com/watch?v=..."
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="mfy-email" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
Your Email <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
id="mfy-email"
|
||||
value={mfyEmail}
|
||||
onChange={(e) => setMfyEmail(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 focus:border-transparent text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-dark-500">
|
||||
We'll send your video files to this address
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Notes (optional) */}
|
||||
<div>
|
||||
<label htmlFor="mfy-notes" className="block text-sm font-medium text-dark-300 mb-2">
|
||||
Special Requests <span className="text-dark-500">(optional)</span>
|
||||
</label>
|
||||
<textarea
|
||||
id="mfy-notes"
|
||||
value={mfyNotes}
|
||||
onChange={(e) => setMfyNotes(e.target.value)}
|
||||
rows={3}
|
||||
placeholder="Any special requests or notes about the song..."
|
||||
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-foreground placeholder:text-muted-foreground resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{mfyError && <p className="text-red-400 text-sm">{mfyError}</p>}
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={mfyLoading}
|
||||
className="w-full bg-primary-500 hover:bg-primary-600 disabled:bg-primary-500/50 text-white font-semibold py-4 rounded-xl transition-all btn-glow flex items-center justify-center gap-2"
|
||||
>
|
||||
{mfyLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
Processing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CreditCard className="w-5 h-5" />
|
||||
Pay $50 & Order
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<p className="text-xs text-center text-dark-500">
|
||||
Secure payment via Stripe. 24-hour delivery guaranteed or your money back.
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* FAQ */}
|
||||
<section className="py-16 px-4 bg-dark-800/50">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<h2 className="text-3xl font-bold text-center mb-12">Questions?</h2>
|
||||
<div className="space-y-4">
|
||||
{faqs.map((faq, i) => (
|
||||
<div key={i} className="bg-dark-800 border border-dark-700 rounded-xl p-6">
|
||||
<h3 className="font-medium mb-2">{faq.question}</h3>
|
||||
<p className="text-dark-400 text-sm">{faq.answer}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="py-12 px-4 border-t border-primary-500/30">
|
||||
<div className="max-w-6xl mx-auto flex flex-col md:flex-row items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8" />
|
||||
</div>
|
||||
<div className="text-sm text-dark-500">
|
||||
© {new Date().getFullYear()} Nomad Karaoke. All rights reserved.
|
||||
</div>
|
||||
<div className="flex gap-6 text-sm text-dark-400">
|
||||
<a href="mailto:support@nomadkaraoke.com" className="hover:text-primary-400 transition-colors">
|
||||
Support
|
||||
</a>
|
||||
<a href="https://nomadkaraoke.com" className="hover:text-primary-400 transition-colors">
|
||||
About
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
{/* Auth Dialog for sign-in */}
|
||||
<AuthDialog
|
||||
open={showAuthDialog}
|
||||
onClose={() => setShowAuthDialog(false)}
|
||||
onSuccess={handleAuthSuccess}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
export default function RootPage() {
|
||||
return <LocaleRedirect />
|
||||
}
|
||||
@@ -1,85 +1,5 @@
|
||||
"use client"
|
||||
import { LocaleRedirect } from "@/components/LocaleRedirect"
|
||||
|
||||
import { Suspense, useEffect, useState } from "react"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import { CheckCircle, Loader2, Coins } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
|
||||
function PaymentSuccessContent() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
const { user, fetchUser } = useAuth()
|
||||
|
||||
useEffect(() => {
|
||||
// Refresh user data to get updated credits
|
||||
const refreshUser = async () => {
|
||||
await fetchUser()
|
||||
setIsLoading(false)
|
||||
}
|
||||
refreshUser()
|
||||
}, [fetchUser])
|
||||
|
||||
const sessionId = searchParams.get("session_id")
|
||||
|
||||
return (
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<CheckCircle className="w-16 h-16 text-success mx-auto mb-4" />
|
||||
|
||||
<h1 className="text-2xl font-bold text-foreground mb-2">
|
||||
Payment Successful!
|
||||
</h1>
|
||||
|
||||
<p className="text-muted-foreground mb-6">
|
||||
Thank you for your purchase. Your credits have been added to your account.
|
||||
</p>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center gap-2 text-muted-foreground mb-6">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Loading your balance...
|
||||
</div>
|
||||
) : user ? (
|
||||
<div className="bg-secondary rounded-lg p-4 mb-6">
|
||||
<div className="flex items-center justify-center gap-2 text-warning">
|
||||
<Coins className="w-5 h-5" />
|
||||
<span className="text-2xl font-bold">{user.credits}</span>
|
||||
<span className="text-muted-foreground">credits available</span>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
onClick={() => router.push("/app")}
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
>
|
||||
Start Creating Karaoke
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A confirmation email has been sent to your email address.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function PaymentSuccessPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
|
||||
<Loader2 className="w-16 h-16 text-primary mx-auto mb-4 animate-spin" />
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<PaymentSuccessContent />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
export default function PaymentRedirect() {
|
||||
return <LocaleRedirect />
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
'use client';
|
||||
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import { usePathname, useRouter, routing } from '@/i18n/routing';
|
||||
|
||||
const localeNames: Record<string, string> = {
|
||||
en: 'English',
|
||||
es: 'Español',
|
||||
de: 'Deutsch',
|
||||
};
|
||||
|
||||
export default function LanguageSwitcher() {
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const t = useTranslations('languageSwitcher');
|
||||
|
||||
function handleChange(e: React.ChangeEvent<HTMLSelectElement>) {
|
||||
const newLocale = e.target.value;
|
||||
try { localStorage.setItem('locale', newLocale); } catch {}
|
||||
router.replace(pathname, { locale: newLocale });
|
||||
}
|
||||
|
||||
return (
|
||||
<select
|
||||
value={locale}
|
||||
onChange={handleChange}
|
||||
aria-label={t('label')}
|
||||
className="bg-transparent border border-border/50 rounded-md px-2 py-1 text-sm cursor-pointer text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{routing.locales.map((loc) => (
|
||||
<option key={loc} value={loc}>{localeNames[loc]}</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { routing } from '@/i18n/routing';
|
||||
|
||||
/**
|
||||
* Detects the user's preferred locale and redirects to the locale-prefixed
|
||||
* version of the current URL. Preserves path, query string, and hash.
|
||||
*
|
||||
* Used by legacy non-locale routes (e.g., /app → /en/app) to redirect
|
||||
* to the proper [locale] routes.
|
||||
*/
|
||||
export function LocaleRedirect() {
|
||||
useEffect(() => {
|
||||
const locale = detectLocale();
|
||||
const { pathname, search, hash } = window.location;
|
||||
window.location.replace(`/${locale}${pathname}${search}${hash}`);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function detectLocale(): string {
|
||||
// 1. Check localStorage for saved preference
|
||||
try {
|
||||
const saved = localStorage.getItem('locale');
|
||||
if (saved && routing.locales.includes(saved as typeof routing.locales[number])) {
|
||||
return saved;
|
||||
}
|
||||
} catch {
|
||||
// localStorage not available
|
||||
}
|
||||
|
||||
// 2. Detect from browser language
|
||||
const browserLangs = navigator.languages || [navigator.language];
|
||||
for (const lang of browserLangs) {
|
||||
const prefix = lang.split('-')[0].toLowerCase();
|
||||
if (routing.locales.includes(prefix as typeof routing.locales[number])) {
|
||||
return prefix;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Fallback to default
|
||||
return routing.defaultLocale;
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useRouter } from '@/i18n/routing'
|
||||
import { TenantLogo } from '@/components/tenant-logo'
|
||||
import { AuthDialog } from '@/components/auth/AuthDialog'
|
||||
import { useTenant } from '@/lib/tenant'
|
||||
import { ThemeToggle } from '@/components/ThemeToggle'
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
/**
|
||||
* Minimal landing page for whitelabel tenant portals.
|
||||
@@ -13,6 +14,7 @@ import { ThemeToggle } from '@/components/ThemeToggle'
|
||||
* No pricing, marketing content, or payment options.
|
||||
*/
|
||||
export function TenantLandingPage() {
|
||||
const t = useTranslations('tenant')
|
||||
const router = useRouter()
|
||||
const { tenant, branding } = useTenant()
|
||||
const [showAuthDialog, setShowAuthDialog] = useState(false)
|
||||
@@ -48,8 +50,7 @@ export function TenantLandingPage() {
|
||||
|
||||
{/* Title */}
|
||||
<h1 className="text-2xl md:text-3xl font-semibold text-center mb-3" style={{ color: '#ffffff' }}>
|
||||
Karaoke Generator for{' '}
|
||||
<span style={{ color: primaryColor }}>{tenantName}</span>
|
||||
{t('title', { tenantName })}
|
||||
</h1>
|
||||
|
||||
{/* Tagline */}
|
||||
@@ -61,7 +62,7 @@ export function TenantLandingPage() {
|
||||
|
||||
{!branding.tagline && (
|
||||
<p className="text-muted-foreground text-center text-lg mb-10 max-w-md">
|
||||
Create professional karaoke videos with real instrumentals, precise lyrics sync, and 4K output.
|
||||
{t('description')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -74,7 +75,7 @@ export function TenantLandingPage() {
|
||||
color: 'var(--primary-foreground)',
|
||||
}}
|
||||
>
|
||||
Sign In
|
||||
{t('signIn')}
|
||||
</button>
|
||||
|
||||
{/* Domain hint */}
|
||||
@@ -83,7 +84,7 @@ export function TenantLandingPage() {
|
||||
if (externalDomains.length === 0) return null
|
||||
return (
|
||||
<p className="text-muted-foreground text-sm mt-4">
|
||||
Sign in with your {externalDomains.map(d => `@${d}`).join(' or ')} email
|
||||
{t('signInWithDomain', { domains: externalDomains.map(d => `@${d}`).join(' or ') })}
|
||||
</p>
|
||||
)
|
||||
})()}
|
||||
@@ -92,14 +93,13 @@ export function TenantLandingPage() {
|
||||
{/* Footer */}
|
||||
<footer className="w-full px-6 py-6 text-center">
|
||||
<p className="text-muted-foreground text-xs">
|
||||
Powered by{' '}
|
||||
<a
|
||||
href="https://gen.nomadkaraoke.com"
|
||||
className="underline hover:text-foreground transition-colors"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Nomad Karaoke
|
||||
{t('poweredBy')}
|
||||
</a>
|
||||
</p>
|
||||
</footer>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
interface WarmingUpLoaderProps {
|
||||
/** Custom class name for the container */
|
||||
@@ -24,6 +25,7 @@ export function WarmingUpLoader({
|
||||
warmUpDelay = 5000,
|
||||
almostThereDelay = 15000,
|
||||
}: WarmingUpLoaderProps) {
|
||||
const t = useTranslations('warmingUp');
|
||||
const [phase, setPhase] = useState<'initial' | 'warming' | 'almost'>('initial');
|
||||
|
||||
useEffect(() => {
|
||||
@@ -49,14 +51,14 @@ export function WarmingUpLoader({
|
||||
/>
|
||||
{phase === 'warming' && (
|
||||
<p className="text-sm animate-fade-in" style={{ color: 'var(--text-muted)' }}>
|
||||
Warming up the generator...
|
||||
{t('title')}
|
||||
</p>
|
||||
)}
|
||||
{phase === 'almost' && (
|
||||
<div className="text-center animate-fade-in">
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>Almost there...</p>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('almostThere')}</p>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)', opacity: 0.7 }}>
|
||||
First load can take up to 30 seconds
|
||||
{t('firstLoadNote')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -45,7 +45,7 @@ describe('AuthStatus', () => {
|
||||
|
||||
// Should show user email and credits
|
||||
expect(screen.getByText('test@example.com')).toBeInTheDocument()
|
||||
expect(screen.getByText('5 credits')).toBeInTheDocument()
|
||||
expect(screen.getByText('5 credits available')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens auth dialog when Login is clicked', () => {
|
||||
|
||||
@@ -226,7 +226,7 @@ describe('PushNotificationToggle', () => {
|
||||
|
||||
render(<PushNotificationToggle />)
|
||||
|
||||
expect(screen.getByText('Enable')).toBeInTheDocument()
|
||||
expect(screen.getByText('Enable notifications')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Disable button when subscribed', () => {
|
||||
@@ -237,7 +237,7 @@ describe('PushNotificationToggle', () => {
|
||||
|
||||
render(<PushNotificationToggle />)
|
||||
|
||||
expect(screen.getByText('Disable')).toBeInTheDocument()
|
||||
expect(screen.getByText('Disable on this device')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls subscribe when Enable clicked', async () => {
|
||||
@@ -250,7 +250,7 @@ describe('PushNotificationToggle', () => {
|
||||
|
||||
render(<PushNotificationToggle />)
|
||||
|
||||
fireEvent.click(screen.getByText('Enable'))
|
||||
fireEvent.click(screen.getByText('Enable notifications'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSubscribe).toHaveBeenCalledTimes(1)
|
||||
@@ -267,7 +267,7 @@ describe('PushNotificationToggle', () => {
|
||||
|
||||
render(<PushNotificationToggle />)
|
||||
|
||||
fireEvent.click(screen.getByText('Disable'))
|
||||
fireEvent.click(screen.getByText('Disable on this device'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUnsubscribe).toHaveBeenCalledTimes(1)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useRouter, Link } from "@/i18n/routing"
|
||||
import NextLink from "next/link"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { Logo } from "./logo"
|
||||
import { Button } from "./ui/button"
|
||||
@@ -13,9 +14,11 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "./ui/dropdown-menu"
|
||||
import { User, LogOut, Settings, Shield, Mail, Phone, HelpCircle, Eye } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import LanguageSwitcher from "./LanguageSwitcher"
|
||||
import { useTranslations } from "next-intl"
|
||||
|
||||
export function AppHeader() {
|
||||
const t = useTranslations('header')
|
||||
const { user, logout, isImpersonating, impersonatedUserEmail, endImpersonation } = useAuth()
|
||||
const router = useRouter()
|
||||
|
||||
@@ -26,7 +29,7 @@ export function AppHeader() {
|
||||
|
||||
const handleBackToAdmin = () => {
|
||||
endImpersonation()
|
||||
router.push("/admin")
|
||||
window.location.href = "/admin"
|
||||
}
|
||||
|
||||
if (!user) return null
|
||||
@@ -40,19 +43,21 @@ export function AppHeader() {
|
||||
|
||||
<nav className="hidden md:flex items-center gap-6">
|
||||
<Link href="/app" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
Dashboard
|
||||
{t('dashboard')}
|
||||
</Link>
|
||||
<Link href="/jobs" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
My Jobs
|
||||
{t('myJobs')}
|
||||
</Link>
|
||||
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
|
||||
<Link href="/admin" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
Admin
|
||||
</Link>
|
||||
<NextLink href="/admin" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
{t('admin')}
|
||||
</NextLink>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<LanguageSwitcher />
|
||||
|
||||
{isImpersonating && (
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -61,7 +66,7 @@ export function AppHeader() {
|
||||
className="h-8 gap-1.5 border-purple-500/40 text-purple-300 hover:text-white hover:bg-purple-800/40"
|
||||
>
|
||||
<Shield className="w-3.5 h-3.5" />
|
||||
Back to Admin
|
||||
{t('backToAdmin')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -69,12 +74,12 @@ export function AppHeader() {
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="hidden lg:flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors">
|
||||
<HelpCircle className="w-3.5 h-3.5" />
|
||||
<span>Need help?</span>
|
||||
<span>{t('needHelp')}</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64">
|
||||
<DropdownMenuLabel className="text-sm">
|
||||
Something confusing or not working? Reach out anytime!
|
||||
{t('helpPrompt')}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
@@ -94,7 +99,7 @@ export function AppHeader() {
|
||||
|
||||
<div className="hidden sm:flex items-center gap-2 px-4 py-2 rounded-lg bg-primary/10 border border-primary/20">
|
||||
<div className="w-2 h-2 rounded-full bg-primary animate-pulse" />
|
||||
<span className="text-sm font-medium text-primary">{user.credits} credits</span>
|
||||
<span className="text-sm font-medium text-primary">{t('credits', { count: user.credits })}</span>
|
||||
</div>
|
||||
|
||||
<DropdownMenu>
|
||||
@@ -106,28 +111,28 @@ export function AppHeader() {
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
<DropdownMenuLabel>
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-sm font-medium">Account</p>
|
||||
<p className="text-xs text-muted-foreground">{user.role === "admin" ? "Admin" : "User"}</p>
|
||||
<p className="text-sm font-medium">{t('account')}</p>
|
||||
<p className="text-xs text-muted-foreground">{user.role === "admin" ? t('adminRole') : t('userRole')}</p>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="sm:hidden">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-2 h-2 rounded-full bg-primary" />
|
||||
<span>{user.credits} credits</span>
|
||||
<span>{t('credits', { count: user.credits })}</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/admin">
|
||||
<NextLink href="/admin">
|
||||
<Shield className="w-4 h-4 mr-2" />
|
||||
Admin Dashboard
|
||||
</Link>
|
||||
{t('adminDashboard')}
|
||||
</NextLink>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem>
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
Settings
|
||||
{t('settings')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="mailto:andrew@nomadkaraoke.com">
|
||||
@@ -144,7 +149,7 @@ export function AppHeader() {
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout} className="text-destructive focus:text-destructive">
|
||||
<LogOut className="w-4 h-4 mr-2" />
|
||||
Logout
|
||||
{t('logout')}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { api, AudioEditSessionMeta, AudioEditSessionWithData, AudioEditEntry } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
@@ -35,6 +36,7 @@ export function AudioEditRestoreDialog({
|
||||
onRestore,
|
||||
onStartFresh,
|
||||
}: AudioEditRestoreDialogProps) {
|
||||
const t = useTranslations('audioEditRestore')
|
||||
const [sessions, setSessions] = useState<AudioEditSessionMeta[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null)
|
||||
@@ -91,7 +93,7 @@ export function AudioEditRestoreDialog({
|
||||
style={{ borderColor: "var(--card-border)", backgroundColor: "var(--card)" }}
|
||||
>
|
||||
<Spinner className="w-6 h-6 mx-auto mb-2" />
|
||||
<p className="text-sm text-muted-foreground">Checking for saved sessions...</p>
|
||||
<p className="text-sm text-muted-foreground">{t('checking')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -108,7 +110,7 @@ export function AudioEditRestoreDialog({
|
||||
<div className="flex items-center gap-2">
|
||||
<History className="w-5 h-5 text-blue-400" />
|
||||
<h2 className="text-lg font-semibold" style={{ color: "var(--text)" }}>
|
||||
Saved Audio Edit Sessions
|
||||
{t('title')}
|
||||
</h2>
|
||||
</div>
|
||||
<button onClick={onStartFresh} className="text-muted-foreground hover:text-foreground">
|
||||
@@ -142,7 +144,7 @@ export function AudioEditRestoreDialog({
|
||||
<p className="text-muted-foreground">
|
||||
{session.edit_count} edit{session.edit_count !== 1 ? "s" : ""} · {session.trigger}
|
||||
{i === 0 && (
|
||||
<span className="ml-1 text-blue-400">[Latest]</span>
|
||||
<span className="ml-1 text-blue-400">{t('latest')}</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -160,7 +162,7 @@ export function AudioEditRestoreDialog({
|
||||
) : selectedSession?.edit_data?.entries ? (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>
|
||||
Operations applied:
|
||||
{t('editsApplied')}
|
||||
</p>
|
||||
<div className="space-y-1.5">
|
||||
{selectedSession.edit_data.entries.map((entry: AudioEditEntry, i: number) => (
|
||||
@@ -180,17 +182,16 @@ export function AudioEditRestoreDialog({
|
||||
{selectedSession.summary && (
|
||||
<div className="text-xs text-muted-foreground pt-2 border-t" style={{ borderColor: "var(--card-border)" }}>
|
||||
<p>
|
||||
Duration change: {formatDuration(selectedSession.summary.duration_change_seconds)}
|
||||
{t('durationChange', { change: formatDuration(selectedSession.summary.duration_change_seconds) })}
|
||||
</p>
|
||||
<p>
|
||||
Net duration: {Math.floor(selectedSession.summary.net_duration_seconds / 60)}:
|
||||
{String(Math.floor(selectedSession.summary.net_duration_seconds % 60)).padStart(2, "0")}
|
||||
{t('netDuration', { duration: `${Math.floor(selectedSession.summary.net_duration_seconds / 60)}:${String(Math.floor(selectedSession.summary.net_duration_seconds % 60)).padStart(2, "0")}` })}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">Select a session to preview</p>
|
||||
<p className="text-sm text-muted-foreground">{t('selectToPreview')}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -198,7 +199,7 @@ export function AudioEditRestoreDialog({
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-end gap-2 p-4 border-t" style={{ borderColor: "var(--card-border)" }}>
|
||||
<Button variant="outline" onClick={onStartFresh} disabled={isRestoring}>
|
||||
Start Fresh
|
||||
{t('startFresh')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleRestore}
|
||||
@@ -207,10 +208,10 @@ export function AudioEditRestoreDialog({
|
||||
{isRestoring ? (
|
||||
<>
|
||||
<Spinner className="w-4 h-4 mr-1" />
|
||||
Restoring...
|
||||
{t('restoring')}
|
||||
</>
|
||||
) : (
|
||||
"Restore Selected"
|
||||
t('restoreSelected')
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useRef, useCallback } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { api, Job, AudioEditInfo, AudioEditResponse, AudioEditEntry, AudioEditSessionMeta } from "@/lib/api"
|
||||
import { useAudioEditAutoSave } from "@/hooks/use-audio-edit-autosave"
|
||||
import { AudioEditRestoreDialog } from "./AudioEditRestoreDialog"
|
||||
@@ -25,7 +26,7 @@ import {
|
||||
ChevronRight,
|
||||
X,
|
||||
} from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Link } from "@/i18n/routing"
|
||||
|
||||
// ─── Types ─────────────────────────────────────────────────────────
|
||||
|
||||
@@ -325,6 +326,8 @@ interface AudioEditorProps {
|
||||
}
|
||||
|
||||
export function AudioEditor({ job }: AudioEditorProps) {
|
||||
const t = useTranslations('audioEditor')
|
||||
const tc = useTranslations('common')
|
||||
// Loading state
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -551,7 +554,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
const resp = await api.applyAudioEdit(job.job_id, operation, params)
|
||||
updateFromResponse(resp)
|
||||
} catch (err) {
|
||||
setOperationError(err instanceof Error ? err.message : "Edit failed")
|
||||
setOperationError(err instanceof Error ? err.message : t('editFailed'))
|
||||
} finally {
|
||||
setIsOperating(false)
|
||||
}
|
||||
@@ -565,7 +568,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
const resp = await api.undoAudioEdit(job.job_id)
|
||||
updateFromResponse(resp)
|
||||
} catch (err) {
|
||||
setOperationError(err instanceof Error ? err.message : "Undo failed")
|
||||
setOperationError(err instanceof Error ? err.message : t('undoFailed'))
|
||||
} finally {
|
||||
setIsOperating(false)
|
||||
}
|
||||
@@ -579,7 +582,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
const resp = await api.redoAudioEdit(job.job_id)
|
||||
updateFromResponse(resp)
|
||||
} catch (err) {
|
||||
setOperationError(err instanceof Error ? err.message : "Redo failed")
|
||||
setOperationError(err instanceof Error ? err.message : t('redoFailed'))
|
||||
} finally {
|
||||
setIsOperating(false)
|
||||
}
|
||||
@@ -629,7 +632,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
setShowJoinDialog(false)
|
||||
setJoinFile(null)
|
||||
} catch (err) {
|
||||
setOperationError(err instanceof Error ? err.message : "Join failed")
|
||||
setOperationError(err instanceof Error ? err.message : t('editFailed'))
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
}
|
||||
@@ -649,7 +652,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
updateFromResponse(resp)
|
||||
}
|
||||
} catch (err) {
|
||||
setOperationError(err instanceof Error ? err.message : "Restore failed — some edits may not have been applied")
|
||||
setOperationError(err instanceof Error ? err.message : t('restoreFailed'))
|
||||
} finally {
|
||||
setIsRestoringSession(false)
|
||||
}
|
||||
@@ -668,7 +671,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
setSubmitSuccess(true)
|
||||
setShowSubmitConfirm(false)
|
||||
} catch (err) {
|
||||
setOperationError(err instanceof Error ? err.message : "Submit failed")
|
||||
setOperationError(err instanceof Error ? err.message : t('submitFailed'))
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
@@ -705,7 +708,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center">
|
||||
<Spinner className="w-8 h-8 mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">Loading audio editor...</p>
|
||||
<p className="text-muted-foreground">{t('loading')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -716,12 +719,12 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center max-w-md p-6">
|
||||
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
|
||||
<h1 className="text-xl font-semibold mb-2">Failed to load audio</h1>
|
||||
<p className="text-muted-foreground mb-4">{error || "Could not load audio data."}</p>
|
||||
<h1 className="text-xl font-semibold mb-2">{t('failedToLoad')}</h1>
|
||||
<p className="text-muted-foreground mb-4">{error || t('couldNotLoadData')}</p>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/app">
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to dashboard
|
||||
{t('backToDashboard')}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
@@ -739,16 +742,15 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
>
|
||||
<Check className="w-8 h-8 text-green-500" />
|
||||
</div>
|
||||
<h1 className="text-xl font-semibold">Audio edit complete!</h1>
|
||||
<h1 className="text-xl font-semibold">{t('editComplete')}</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Processing will continue with your edited audio.
|
||||
You'll receive an email when lyrics are ready for review.
|
||||
{t('editsWillBeReviewed')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Redirecting in {redirectCountdown}...
|
||||
{t('redirectingIn', { count: redirectCountdown })}
|
||||
</p>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/app">Back to dashboard</Link>
|
||||
<Link href="/app">{t('backToDashboard')}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -807,14 +809,13 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
<div className="flex items-start gap-2">
|
||||
<Scissors className="w-4 h-4 mt-0.5 shrink-0 text-blue-400" />
|
||||
<div className="space-y-1.5">
|
||||
<p className="font-medium" style={{ color: "var(--text)" }}>Audio Editor Tips</p>
|
||||
<p className="font-medium" style={{ color: "var(--text)" }}>{t('keyboardShortcuts')}</p>
|
||||
<ul className="space-y-1 text-xs text-muted-foreground">
|
||||
<li><strong>Select:</strong> Click and drag on the waveform to select a region</li>
|
||||
<li><strong>Trim:</strong> Select a region near the start or end, then click Trim Start/End</li>
|
||||
<li><strong>Cut:</strong> Select a region and press Delete or click Cut</li>
|
||||
<li><strong>Mute:</strong> Select a region and press M or click Mute</li>
|
||||
<li><strong>Undo/Redo:</strong> Ctrl+Z / Ctrl+Shift+Z</li>
|
||||
<li><strong>Play/Pause:</strong> Spacebar or click anywhere to seek</li>
|
||||
<li>{t('shortcutSpace')}</li>
|
||||
<li>{t('shortcutUndo')}</li>
|
||||
<li>{t('shortcutRedo')}</li>
|
||||
<li>{t('shortcutDelete')}</li>
|
||||
<li>{t('shortcutMute')}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@@ -841,7 +842,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
size="sm"
|
||||
disabled={!canUndo || isOperating}
|
||||
onClick={handleUndo}
|
||||
title="Undo (Ctrl+Z)"
|
||||
title={t('undo')}
|
||||
>
|
||||
<Undo2 className="w-4 h-4" />
|
||||
</Button>
|
||||
@@ -850,7 +851,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
size="sm"
|
||||
disabled={!canRedo || isOperating}
|
||||
onClick={handleRedo}
|
||||
title="Redo (Ctrl+Shift+Z)"
|
||||
title={t('redo')}
|
||||
>
|
||||
<Redo2 className="w-4 h-4" />
|
||||
</Button>
|
||||
@@ -873,7 +874,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
onClick={handleTrimStart}
|
||||
className="text-xs h-7"
|
||||
>
|
||||
Trim Start
|
||||
{t('trimStart')}
|
||||
</Button>
|
||||
)}
|
||||
{selection.endSeconds > currentDuration - 1 && (
|
||||
@@ -884,7 +885,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
onClick={handleTrimEnd}
|
||||
className="text-xs h-7"
|
||||
>
|
||||
Trim End
|
||||
{t('trimEnd')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
@@ -893,7 +894,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
disabled={isOperating}
|
||||
onClick={handleCut}
|
||||
className="text-xs h-7"
|
||||
title="Cut selection (Delete)"
|
||||
title={t('cutSelection')}
|
||||
>
|
||||
<Scissors className="w-3 h-3 mr-1" />
|
||||
Cut
|
||||
@@ -904,7 +905,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
disabled={isOperating}
|
||||
onClick={handleMute}
|
||||
className="text-xs h-7"
|
||||
title="Mute selection (M)"
|
||||
title={t('muteSelection')}
|
||||
>
|
||||
<VolumeX className="w-3 h-3 mr-1" />
|
||||
Mute
|
||||
@@ -968,7 +969,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
className="text-xs h-7 bg-green-600 hover:bg-green-700 text-white"
|
||||
>
|
||||
<Check className="w-3 h-3 mr-1" />
|
||||
{hasEdits ? "Submit & Continue" : "Continue Without Editing"}
|
||||
{hasEdits ? t('submitForReview') : t('continueWithoutEditing')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -982,7 +983,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
Original ({formatTime(audioInfo.original_duration_seconds)})
|
||||
{t('original')} ({formatTime(audioInfo.original_duration_seconds)})
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab("edited")}
|
||||
@@ -992,7 +993,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
Edited ({formatTime(audioInfo.current_duration_seconds)})
|
||||
{t('edited')} ({formatTime(audioInfo.current_duration_seconds)})
|
||||
{hasEdits && durationChange !== 0 && (
|
||||
<span className={`ml-1 ${durationChange < 0 ? "text-green-400" : "text-amber-400"}`}>
|
||||
({durationChange > 0 ? "+" : ""}{formatTimePrecise(durationChange)})
|
||||
@@ -1090,7 +1091,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
style={{ borderColor: "var(--card-border)", backgroundColor: "var(--card)" }}
|
||||
>
|
||||
<h2 className="text-lg font-semibold" style={{ color: "var(--text)" }}>
|
||||
Submit Edited Audio?
|
||||
{t('submitConfirmation')}
|
||||
</h2>
|
||||
<div className="space-y-1 text-sm text-muted-foreground">
|
||||
<p>Original duration: {formatTime(audioInfo.original_duration_seconds)}</p>
|
||||
@@ -1174,7 +1175,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
onClick={() => handleJoin("start")}
|
||||
disabled={isUploading}
|
||||
>
|
||||
{isUploading ? <Spinner className="w-4 h-4" /> : "Add to Start"}
|
||||
{isUploading ? <Spinner className="w-4 h-4" /> : t('addToStart')}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
@@ -1182,7 +1183,7 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
onClick={() => handleJoin("end")}
|
||||
disabled={isUploading}
|
||||
>
|
||||
{isUploading ? <Spinner className="w-4 h-4" /> : "Add to End"}
|
||||
{isUploading ? <Spinner className="w-4 h-4" /> : t('addToEnd')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -155,7 +155,7 @@ describe("AudioEditor", () => {
|
||||
mockApi.getInputAudioInfo.mockResolvedValue(mockAudioInfo)
|
||||
render(<AudioEditor job={mockJob} />)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Audio Editor Tips")).toBeInTheDocument()
|
||||
expect(screen.getByText("Keyboard shortcuts:")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -186,7 +186,7 @@ describe("AudioEditor", () => {
|
||||
mockApi.getInputAudioInfo.mockResolvedValue(infoWithEdits)
|
||||
render(<AudioEditor job={mockJob} />)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Submit & Continue")).toBeInTheDocument()
|
||||
expect(screen.getByText("Submit for Review")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -229,12 +229,12 @@ describe("AudioEditor", () => {
|
||||
mockApi.getInputAudioInfo.mockResolvedValue(infoWithEdits)
|
||||
render(<AudioEditor job={mockJob} />)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Submit & Continue")).toBeInTheDocument()
|
||||
expect(screen.getByText("Submit for Review")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText("Submit & Continue"))
|
||||
fireEvent.click(screen.getByText("Submit for Review"))
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Submit Edited Audio?")).toBeInTheDocument()
|
||||
expect(screen.getByText("Submit your audio edits for review?")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useMemo } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { api } from "@/lib/api"
|
||||
import {
|
||||
ExtendedAudioSearchResult,
|
||||
@@ -28,6 +29,7 @@ interface AudioSearchDialogProps {
|
||||
}
|
||||
|
||||
export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle }: AudioSearchDialogProps) {
|
||||
const t = useTranslations('audioSearch')
|
||||
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isSelecting, setIsSelecting] = useState<number | null>(null)
|
||||
@@ -105,10 +107,10 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
<DialogContent className="max-w-7xl w-[95vw] max-h-[90vh] flex flex-col bg-card border-border !p-0 gap-0 overflow-hidden">
|
||||
<div className="px-4 py-2.5 border-b border-border shrink-0 bg-card flex items-center justify-between">
|
||||
<DialogTitle className="text-foreground text-sm font-semibold flex items-center gap-2">
|
||||
Select Audio Source
|
||||
{t('selectAudioSource')}
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded bg-secondary text-muted-foreground font-mono">v{APP_VERSION}</span>
|
||||
<span className="text-muted-foreground font-normal text-xs">
|
||||
({results.length} results across {totalCategories} categories)
|
||||
({t('resultsCount', { count: results.length, categories: totalCategories })})
|
||||
</span>
|
||||
</DialogTitle>
|
||||
</div>
|
||||
@@ -121,16 +123,16 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
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
|
||||
{t('tipsForChoosing')}
|
||||
{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>
|
||||
<li>{t('tipFilename')}</li>
|
||||
<li>{t('tipAvailability')}</li>
|
||||
<li>{t('tipStudioAlbum')}</li>
|
||||
<li>{t('tipVinylRips')}</li>
|
||||
<li>{t('tipYoutube')}</li>
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
@@ -150,7 +152,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
) : results.length === 0 ? (
|
||||
<div className="flex-1 flex flex-col items-center justify-center py-12 text-muted-foreground">
|
||||
<Music2 className="w-8 h-8 mb-2 opacity-50" />
|
||||
<p className="text-sm">No audio sources found</p>
|
||||
<p className="text-sm">{t('noAudioSources')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto min-h-0 p-4">
|
||||
@@ -178,7 +180,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
{isExpanded ? (
|
||||
<>Show less <ChevronUp className="w-3 h-3" /></>
|
||||
) : (
|
||||
<>+{hiddenCount} more <ChevronDown className="w-3 h-3" /></>
|
||||
<>{t('moreVersions', { count: hiddenCount })} <ChevronDown className="w-3 h-3" /></>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
@@ -208,12 +210,12 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
<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
|
||||
{t('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
|
||||
{t('vinyl')}
|
||||
</span>
|
||||
)}
|
||||
{result.provider === "YouTube" && (
|
||||
@@ -226,7 +228,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
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?
|
||||
{t('wrongTrack')}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-green-400 font-medium">{getDisplayName(result)}</span>
|
||||
@@ -248,7 +250,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
'bg-red-600/20 text-red-400'
|
||||
}`}
|
||||
>
|
||||
{text} availability
|
||||
{text} {t('availability')}
|
||||
</span>
|
||||
)
|
||||
})()
|
||||
@@ -258,7 +260,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
result.view_count >= 10000 ? 'bg-yellow-600/20 text-yellow-400' :
|
||||
'bg-muted text-muted-foreground'
|
||||
}`}>
|
||||
{formatCount(result.view_count)} views
|
||||
{t('views', { count: formatCount(result.view_count) })}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -286,7 +288,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
|
||||
{isSelecting === result.index ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : (
|
||||
"Select"
|
||||
t('select')
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useTranslations } from "next-intl"
|
||||
|
||||
interface AuthDialogProps {
|
||||
open: boolean
|
||||
@@ -22,6 +23,8 @@ interface AuthDialogProps {
|
||||
type AuthStep = "email" | "sent" | "token"
|
||||
|
||||
export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
const t = useTranslations('auth.dialog')
|
||||
const tCommon = useTranslations('common')
|
||||
const [step, setStep] = useState<AuthStep>("email")
|
||||
const [email, setEmail] = useState("")
|
||||
const [token, setToken] = useState("")
|
||||
@@ -85,17 +88,17 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<Mail className="w-5 h-5 text-primary" />
|
||||
Sign In
|
||||
{t('title')}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-muted-foreground">
|
||||
Enter your email to receive a sign-in link
|
||||
{t('emailPrompt')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSendMagicLink} className="space-y-4">
|
||||
<div>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
placeholder={t('emailPlaceholder')}
|
||||
value={email}
|
||||
onChange={(e) => {
|
||||
setEmail(e.target.value)
|
||||
@@ -109,14 +112,12 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
{displayError && (
|
||||
displayError === "disposable_email_not_allowed" ? (
|
||||
<div className="mt-2 p-3 rounded-md bg-amber-500/10 border border-amber-500/30 text-sm space-y-2">
|
||||
<p className="font-medium text-amber-400">We don't support disposable email addresses</p>
|
||||
<p className="font-medium text-amber-400">{t('disposableEmailWarning')}</p>
|
||||
<p className="text-muted-foreground">
|
||||
We'd love to help you create karaoke videos! Please use your regular email
|
||||
address so we can send you a notification when your video is ready.
|
||||
{t('disposableEmailExplanation')}
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
We promise — no spam, no marketing emails, ever. We only email you about
|
||||
your karaoke videos.
|
||||
{t('noSpamPromise')}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
@@ -133,10 +134,10 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Sending...
|
||||
{t('sending')}
|
||||
</>
|
||||
) : (
|
||||
"Send Sign-In Link"
|
||||
t('sendSignInLink')
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
@@ -146,11 +147,11 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<KeyRound className="w-4 h-4 mr-2" />
|
||||
Use Access Token Instead
|
||||
{t('useAccessToken')}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
No account? Just enter your email to get started.
|
||||
{t('noAccount')}
|
||||
</p>
|
||||
</form>
|
||||
</>
|
||||
@@ -161,18 +162,18 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<CheckCircle className="w-5 h-5 text-success" />
|
||||
Check Your Email
|
||||
{t('checkEmailTitle')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<p className="text-foreground">
|
||||
We sent a sign-in link to:
|
||||
{t('checkEmailSent')}
|
||||
</p>
|
||||
<p className="text-foreground font-medium bg-secondary px-4 py-2 rounded-md">
|
||||
{email}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Click the link in the email to sign in. The link expires in 15 minutes.
|
||||
{t('checkEmailExpiry')}
|
||||
</p>
|
||||
<div className="pt-4 border-t border-border space-y-2">
|
||||
<Button
|
||||
@@ -181,14 +182,14 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
className="w-full border-border text-foreground hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Try a Different Email
|
||||
{t('tryDifferentEmail')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={handleClose}
|
||||
className="w-full text-muted-foreground"
|
||||
>
|
||||
Close
|
||||
{tCommon('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -200,17 +201,17 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<KeyRound className="w-5 h-5 text-warning" />
|
||||
Access Token
|
||||
{t('accessTokenTitle')}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-muted-foreground">
|
||||
Enter your access token to authenticate
|
||||
{t('accessTokenPrompt')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleTokenSubmit} className="space-y-4">
|
||||
<div>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Enter access token"
|
||||
placeholder={t('accessTokenPlaceholder')}
|
||||
value={token}
|
||||
onChange={(e) => {
|
||||
setToken(e.target.value)
|
||||
@@ -234,10 +235,10 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Authenticating...
|
||||
{t('authenticating')}
|
||||
</>
|
||||
) : (
|
||||
"Authenticate"
|
||||
t('authenticate')
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
@@ -247,11 +248,11 @@ export function AuthDialog({ open, onClose, onSuccess }: AuthDialogProps) {
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Email Sign-In
|
||||
{t('backToEmail')}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Contact an admin to get an access token
|
||||
{t('contactAdmin')}
|
||||
</p>
|
||||
</form>
|
||||
</>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical, Gift } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Link } from "@/i18n/routing"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -18,12 +18,15 @@ import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { AuthDialog } from "./AuthDialog"
|
||||
import { FeedbackDialog } from "@/components/feedback/FeedbackDialog"
|
||||
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
|
||||
import { useTranslations } from "next-intl"
|
||||
|
||||
interface AuthStatusProps {
|
||||
onAuthChange?: () => void
|
||||
}
|
||||
|
||||
export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
const t = useTranslations('auth.status')
|
||||
const tHeader = useTranslations('header')
|
||||
const { user, logout } = useAuth()
|
||||
const { showTestData, setShowTestData } = useAdminSettings()
|
||||
const [showAuthDialog, setShowAuthDialog] = useState(false)
|
||||
@@ -77,10 +80,10 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
handleBuyCredits()
|
||||
}}
|
||||
className="flex items-center gap-1 text-warning font-medium hover:text-warning/80 transition-colors cursor-pointer"
|
||||
title="Buy more credits"
|
||||
title={t('buyMoreCredits')}
|
||||
>
|
||||
<Coins className="w-3 h-3" />
|
||||
{user.credits} {user.credits === 1 ? 'credit' : 'credits'}
|
||||
{t('creditsAvailable', { count: user.credits })}
|
||||
</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
@@ -88,7 +91,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
<DropdownMenuLabel className="text-muted-foreground font-normal">
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{user.display_name || "Karaoke Fan"}
|
||||
{user.display_name || t('defaultName')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{user.email}</p>
|
||||
</div>
|
||||
@@ -99,14 +102,14 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
disabled
|
||||
>
|
||||
<Coins className="w-4 h-4 mr-2 text-warning" />
|
||||
<span>{user.credits} credits available</span>
|
||||
<span>{t('creditsAvailable', { count: user.credits })}</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={handleBuyCredits}
|
||||
className="text-muted-foreground focus:text-foreground focus:bg-secondary"
|
||||
>
|
||||
<CreditCard className="w-4 h-4 mr-2" />
|
||||
<span>Buy More Credits</span>
|
||||
<span>{t('buyMoreCredits')}</span>
|
||||
</DropdownMenuItem>
|
||||
{user.feedback_eligible && (
|
||||
<DropdownMenuItem
|
||||
@@ -114,7 +117,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
className="text-green-500 focus:text-green-400 focus:bg-secondary"
|
||||
>
|
||||
<Gift className="w-4 h-4 mr-2" />
|
||||
<span>Earn 1 Free Credit</span>
|
||||
<span>{t('earnFreeCredit')}</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
|
||||
@@ -123,7 +126,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
<DropdownMenuItem asChild className="text-muted-foreground focus:text-foreground focus:bg-secondary">
|
||||
<Link href="/admin">
|
||||
<Shield className="w-4 h-4 mr-2" />
|
||||
<span>Admin Dashboard</span>
|
||||
<span>{tHeader('adminDashboard')}</span>
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
@@ -131,7 +134,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
className="text-muted-foreground focus:text-foreground focus:bg-secondary"
|
||||
>
|
||||
<FlaskConical className="w-4 h-4 mr-2" />
|
||||
<span className="flex-1">Show Test Jobs</span>
|
||||
<span className="flex-1">{t('showTestJobs')}</span>
|
||||
<Switch
|
||||
checked={showTestData}
|
||||
onCheckedChange={setShowTestData}
|
||||
@@ -146,7 +149,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
className="text-destructive focus:text-destructive focus:bg-secondary"
|
||||
>
|
||||
<LogOut className="w-4 h-4 mr-2" />
|
||||
<span>Sign Out</span>
|
||||
<span>{t('signOut')}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
@@ -171,7 +174,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
className="text-warning hover:text-warning/80 min-h-[40px] px-2 sm:px-3"
|
||||
>
|
||||
<KeyRound className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Login</span>
|
||||
<span className="hidden sm:inline">{t('login')}</span>
|
||||
</Button>
|
||||
<AuthDialog
|
||||
open={showAuthDialog}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } f
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { api, CreditPackage } from '@/lib/api'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
interface BuyCreditsDialogProps {
|
||||
open: boolean
|
||||
@@ -17,6 +18,8 @@ const pricePerVideo = (pkg: CreditPackage) =>
|
||||
`$${(pkg.price_cents / 100 / pkg.credits).toFixed(2)}`
|
||||
|
||||
export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
const t = useTranslations('credits')
|
||||
const tCommon = useTranslations('common')
|
||||
const { user } = useAuth()
|
||||
const [packages, setPackages] = useState<CreditPackage[]>([])
|
||||
const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null)
|
||||
@@ -60,10 +63,10 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<CreditCard className="w-5 h-5 text-primary" />
|
||||
Buy More Credits
|
||||
{t('title')}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-muted-foreground">
|
||||
Each credit creates one karaoke video. Pick a package below.
|
||||
{t('description')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -100,19 +103,19 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
>
|
||||
{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
|
||||
{t('bestValue')}
|
||||
</span>
|
||||
)}
|
||||
<div className="text-2xl font-bold">{pkg.credits}</div>
|
||||
<div className="text-sm text-muted-foreground mb-1">
|
||||
{pkg.credits === 1 ? 'credit' : 'credits'}
|
||||
{pkg.credits === 1 ? tCommon('credit') : tCommon('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>
|
||||
<div className="text-xs text-muted-foreground">{t('pricePerVideo', { price: pricePerVideo(pkg) })}</div>
|
||||
{savings > 0 && (
|
||||
<div className="text-xs text-green-500 mt-1">Save {savings}%</div>
|
||||
<div className="text-xs text-green-500 mt-1">{t('savePct', { savings })}</div>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
@@ -127,12 +130,12 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
{checkoutLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Redirecting to payment...
|
||||
{t('redirecting')}
|
||||
</>
|
||||
) : selectedPackage ? (
|
||||
`Continue to Payment — ${formatPrice(selectedPackage.price_cents)}`
|
||||
t('continuePayment', { price: formatPrice(selectedPackage.price_cents) })
|
||||
) : (
|
||||
'Select a package'
|
||||
t('selectPackage')
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
"use client"
|
||||
|
||||
import { NextIntlClientProvider } from "next-intl"
|
||||
import enMessages from "@/messages/en.json"
|
||||
|
||||
/**
|
||||
* Provides default English translations for routes outside [locale] (e.g., /admin, /app).
|
||||
* The [locale]/layout.tsx provides locale-specific translations that override this.
|
||||
*/
|
||||
export function DefaultIntlProvider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<NextIntlClientProvider locale="en" messages={enMessages}>
|
||||
{children}
|
||||
</NextIntlClientProvider>
|
||||
)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { Label } from '@/components/ui/label'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { api } from '@/lib/api'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
interface FeedbackDialogProps {
|
||||
open: boolean
|
||||
@@ -46,6 +47,7 @@ function StarRating({ value, onChange, label }: {
|
||||
}
|
||||
|
||||
export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
|
||||
const t = useTranslations('feedback')
|
||||
const { fetchUser } = useAuth()
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [isSuccess, setIsSuccess] = useState(false)
|
||||
@@ -138,17 +140,17 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
|
||||
<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>
|
||||
<DialogTitle className="text-foreground text-xl">{t('thankYou')}</DialogTitle>
|
||||
<DialogDescription className="text-muted-foreground text-base">
|
||||
Your feedback helps us improve Nomad Karaoke for everyone.
|
||||
{t('thankYouDesc')}
|
||||
</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>
|
||||
<p className="text-sm text-muted-foreground">{t('creditsAdded', { count: creditsGranted })}</p>
|
||||
</div>
|
||||
<Button onClick={handleClose} className="mt-4">
|
||||
Done
|
||||
{t('done')}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
@@ -156,10 +158,10 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<Gift className="w-5 h-5 text-green-500" />
|
||||
Share Your Feedback — Earn 1 Free Credit
|
||||
{t('title')}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-muted-foreground">
|
||||
Tell us about your experience creating karaoke videos. Your feedback directly shapes what we build next.
|
||||
{t('description')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -167,22 +169,22 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
|
||||
{/* Star Ratings */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<StarRating
|
||||
label="Overall Experience"
|
||||
label={t('overallExperience')}
|
||||
value={overallRating}
|
||||
onChange={setOverallRating}
|
||||
/>
|
||||
<StarRating
|
||||
label="Ease of Use"
|
||||
label={t('easeOfUse')}
|
||||
value={easeOfUseRating}
|
||||
onChange={setEaseOfUseRating}
|
||||
/>
|
||||
<StarRating
|
||||
label="Lyrics Accuracy"
|
||||
label={t('lyricsAccuracy')}
|
||||
value={lyricsAccuracyRating}
|
||||
onChange={setLyricsAccuracyRating}
|
||||
/>
|
||||
<StarRating
|
||||
label="Correction Experience"
|
||||
label={t('correctionExperience')}
|
||||
value={correctionRating}
|
||||
onChange={setCorrectionRating}
|
||||
/>
|
||||
@@ -191,38 +193,38 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
|
||||
{/* Text Fields */}
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="went-well">What went well?</Label>
|
||||
<Label htmlFor="went-well">{t('whatWentWell')}</Label>
|
||||
<Textarea
|
||||
id="went-well"
|
||||
value={whatWentWell}
|
||||
onChange={(e) => setWhatWentWell(e.target.value)}
|
||||
placeholder="What did you enjoy about creating karaoke videos?"
|
||||
placeholder={t('whatWentWellPlaceholder')}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="could-improve">What could be better?</Label>
|
||||
<Label htmlFor="could-improve">{t('whatCouldBeBetter')}</Label>
|
||||
<Textarea
|
||||
id="could-improve"
|
||||
value={whatCouldImprove}
|
||||
onChange={(e) => setWhatCouldImprove(e.target.value)}
|
||||
placeholder="What would make the experience better?"
|
||||
placeholder={t('whatCouldBeBetterPlaceholder')}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="additional">Additional comments</Label>
|
||||
<Label htmlFor="additional">{t('additionalComments')}</Label>
|
||||
<Textarea
|
||||
id="additional"
|
||||
value={additionalComments}
|
||||
onChange={(e) => setAdditionalComments(e.target.value)}
|
||||
placeholder="Anything else you'd like us to know?"
|
||||
placeholder={t('additionalCommentsPlaceholder')}
|
||||
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)
|
||||
{t('minCharsWarning', { count: longestText })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -236,7 +238,7 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
|
||||
onCheckedChange={(checked) => setWouldRecommend(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="would-recommend" className="text-sm font-normal cursor-pointer">
|
||||
I would recommend Nomad Karaoke to others
|
||||
{t('wouldRecommend')}
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -246,7 +248,7 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
|
||||
onCheckedChange={(checked) => setWouldUseAgain(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="would-use-again" className="text-sm font-normal cursor-pointer">
|
||||
I would use Nomad Karaoke again
|
||||
{t('wouldUseAgain')}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -265,10 +267,10 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Submitting...
|
||||
{t('submitting')}
|
||||
</>
|
||||
) : (
|
||||
'Submit Feedback & Earn 1 Credit'
|
||||
t('submitButton')
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useRouter as useNextRouter } from "next/navigation"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Eye, Shield } from "lucide-react"
|
||||
@@ -11,7 +11,7 @@ import { Eye, Shield } from "lucide-react"
|
||||
*/
|
||||
export function ImpersonationBanner() {
|
||||
const { isImpersonating, impersonatedUserEmail, endImpersonation } = useAuth()
|
||||
const router = useRouter()
|
||||
const router = useNextRouter()
|
||||
|
||||
if (!isImpersonating) {
|
||||
return null
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useRef } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Upload } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
@@ -15,6 +16,7 @@ export function CustomUpload({
|
||||
isUploading,
|
||||
acceptedFormats = [".flac", ".mp3", ".wav", ".m4a", ".ogg"],
|
||||
}: CustomUploadProps) {
|
||||
const t = useTranslations('instrumentalReview.customUpload')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
@@ -41,7 +43,7 @@ export function CustomUpload({
|
||||
>
|
||||
<label className="cursor-pointer">
|
||||
<Upload className="w-3.5 h-3.5 mr-1.5" />
|
||||
{isUploading ? "Uploading..." : "Upload"}
|
||||
{isUploading ? t('uploading') : t('upload')}
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { ExternalLink, Lightbulb, X } from "lucide-react"
|
||||
import type { BackingVocalAnalysis, AudibleSegment } from "@/lib/api"
|
||||
|
||||
@@ -13,6 +14,7 @@ export function InstrumentalGuidancePanel({
|
||||
analysis,
|
||||
audibleSegments,
|
||||
}: InstrumentalGuidancePanelProps) {
|
||||
const t = useTranslations('instrumentalReview.guidance')
|
||||
const [guidanceDismissed, setGuidanceDismissed] = useState(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("instrumentalReviewGuidanceDismissed") === "true"
|
||||
@@ -43,7 +45,7 @@ export function InstrumentalGuidancePanel({
|
||||
className="text-amber-500 hover:text-amber-400 transition-colors"
|
||||
onClick={handleShowTips}
|
||||
>
|
||||
Show tips
|
||||
{t('showTips')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
@@ -56,19 +58,13 @@ export function InstrumentalGuidancePanel({
|
||||
<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.
|
||||
<strong>{t('chooseBackingTrack')}</strong>
|
||||
</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.
|
||||
{t('littleBackingVocals', { percentage: percentage.toFixed(0) })}
|
||||
</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.
|
||||
{t('hearDifference')}
|
||||
</p>
|
||||
<a
|
||||
href="https://www.youtube.com/watch?v=-dI3r7qXo3A"
|
||||
@@ -77,13 +73,13 @@ export function InstrumentalGuidancePanel({
|
||||
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
|
||||
{t('watchFullTutorial')}
|
||||
</a>
|
||||
</div>
|
||||
<button
|
||||
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
onClick={handleDismiss}
|
||||
aria-label="Dismiss tip"
|
||||
aria-label={t('dismissTip')}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
@@ -97,33 +93,20 @@ export function InstrumentalGuidancePanel({
|
||||
<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.
|
||||
<strong>{t('chooseBackingTrack')}</strong>
|
||||
</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.
|
||||
{t('backingVocalsExplanation')}
|
||||
</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)`}.
|
||||
{t('step1', { segments: 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.
|
||||
{t('step2')}
|
||||
</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>.
|
||||
{t('step3')}
|
||||
</p>
|
||||
</div>
|
||||
<a
|
||||
@@ -133,13 +116,13 @@ export function InstrumentalGuidancePanel({
|
||||
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
|
||||
{t('watchFullTutorial')}
|
||||
</a>
|
||||
</div>
|
||||
<button
|
||||
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
onClick={handleDismiss}
|
||||
aria-label="Dismiss tip"
|
||||
aria-label={t('dismissTip')}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useRef, useCallback, useMemo } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useRouter, Link } from "@/i18n/routing"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { ArrowLeft, Play, Pause, Check } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
api,
|
||||
@@ -49,6 +49,7 @@ function formatTime(seconds: number): string {
|
||||
|
||||
export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalSelectorProps) {
|
||||
const router = useRouter()
|
||||
const t = useTranslations('instrumentalReview')
|
||||
const audioRef = useRef<HTMLAudioElement>(null)
|
||||
|
||||
// Data state
|
||||
@@ -518,10 +519,9 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center max-w-md">
|
||||
<Spinner className="w-8 h-8 mx-auto mb-4" />
|
||||
<h2 className="text-lg font-semibold mb-2">Audio Separation In Progress</h2>
|
||||
<h2 className="text-lg font-semibold mb-2">{t('separationInProgress')}</h2>
|
||||
<p className="text-muted-foreground">
|
||||
The audio stems are still being separated. This usually takes a few minutes.
|
||||
This page will automatically update when the separation is complete.
|
||||
{t('separationInProgressDesc')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -534,7 +534,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center">
|
||||
<Spinner className="w-8 h-8 mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">Loading instrumental analysis...</p>
|
||||
<p className="text-muted-foreground">{t('loadingAnalysis')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -550,7 +550,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/app">
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to dashboard
|
||||
{t('backToDashboard')}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
@@ -562,11 +562,11 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
// Success screen
|
||||
if (showSuccess) {
|
||||
const selectionLabels: Record<string, string> = {
|
||||
clean: "Clean Instrumental",
|
||||
with_backing: "With Backing Vocals",
|
||||
custom: "Custom",
|
||||
uploaded: "Uploaded Instrumental",
|
||||
original: "Original Audio",
|
||||
clean: t('options.cleanInstrumental'),
|
||||
with_backing: t('options.withBackingVocals'),
|
||||
custom: t('options.custom'),
|
||||
uploaded: t('options.uploaded'),
|
||||
original: t('options.originalAudio'),
|
||||
}
|
||||
const selectionLabel = selectionLabels[selectedOption] || selectedOption
|
||||
|
||||
@@ -575,19 +575,19 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
<div className="text-center">
|
||||
<h2 className="text-2xl font-semibold text-green-500 mb-4">
|
||||
<Check className="w-8 h-8 inline-block mr-2" />
|
||||
Selection Submitted
|
||||
{t('selectionSubmitted')}
|
||||
</h2>
|
||||
<p className="mb-2">
|
||||
You selected: <strong>{selectionLabel}</strong>
|
||||
{t('youSelected', { label: selectionLabel })}
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
{countdown > 0
|
||||
? isLocalMode
|
||||
? `Closing in ${countdown}s...`
|
||||
: `Redirecting in ${countdown}s...`
|
||||
? t('closingIn', { countdown })
|
||||
: t('redirectingIn', { countdown })
|
||||
: isLocalMode
|
||||
? "You can close this window now."
|
||||
: "Redirecting..."}
|
||||
? t('canCloseWindow')
|
||||
: t('redirecting')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -610,8 +610,8 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
e.currentTarget.style.display = "none"
|
||||
}}
|
||||
/>
|
||||
<span className="sm:hidden">Review</span>
|
||||
<span className="hidden sm:inline">Instrumental Review</span>
|
||||
<span className="sm:hidden">{t('review')}</span>
|
||||
<span className="hidden sm:inline">{t('title')}</span>
|
||||
</span>
|
||||
<span className="text-xs md:text-sm text-muted-foreground truncate">
|
||||
{job.artist} {job.artist && job.title ? "-" : ""} {job.title}
|
||||
@@ -626,8 +626,8 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
}`}
|
||||
>
|
||||
{analysisData?.analysis.recommended_selection === "clean"
|
||||
? "Clean recommended"
|
||||
: "Review backing vocals"}
|
||||
? t('cleanRecommended')
|
||||
: t('reviewBackingVocals')}
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
@@ -693,13 +693,10 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
))}
|
||||
</div>
|
||||
<span className="hidden md:inline 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
|
||||
{t('shiftDrag')}
|
||||
</span>
|
||||
<kbd className="hidden md:inline px-1.5 py-0.5 bg-background border border-border rounded text-[10px] font-mono">
|
||||
Space
|
||||
{t('space')}
|
||||
</kbd>
|
||||
</div>
|
||||
</div>
|
||||
@@ -722,7 +719,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/50 backdrop-blur-sm">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Spinner className="w-4 h-4" />
|
||||
Loading audio...
|
||||
{t('loadingAudio')}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -757,17 +754,15 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
{/* 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>
|
||||
<span className="text-sm font-semibold">{t('alternateInstrumental')}</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.
|
||||
{t('uploadYourOwn', { duration: formatTime(duration) })}
|
||||
</p>
|
||||
{hasUploaded && uploadedFilename && (
|
||||
<p className="text-xs text-green-500 mt-1">
|
||||
✓ Using: {uploadedFilename}
|
||||
✓ {t('usingFile', { filename: uploadedFilename })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -794,7 +789,7 @@ export function InstrumentalSelector({ job, isLocalMode = false }: InstrumentalS
|
||||
className="mt-auto w-full min-h-[44px] text-base font-semibold"
|
||||
>
|
||||
<Check className="w-5 h-5 mr-2" />
|
||||
{isSubmitting ? "Submitting..." : "Confirm & Continue"}
|
||||
{isSubmitting ? t('submitting') : t('confirmContinue')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useCallback, useMemo } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -41,11 +42,6 @@ interface InstrumentalSelectorEmbeddedProps {
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const OPTION_DESCRIPTIONS: Record<string, string> = {
|
||||
clean: "No backing vocals - pure instrumental",
|
||||
with_backing: "Includes backing vocals from original",
|
||||
}
|
||||
|
||||
export function InstrumentalSelectorEmbedded({
|
||||
options,
|
||||
analysis,
|
||||
@@ -54,6 +50,7 @@ export function InstrumentalSelectorEmbedded({
|
||||
compact = false,
|
||||
disabled = false,
|
||||
}: InstrumentalSelectorEmbeddedProps) {
|
||||
const t = useTranslations('instrumentalReview')
|
||||
const [playingId, setPlayingId] = useState<string | null>(null)
|
||||
const [audioElement] = useState<HTMLAudioElement | null>(() =>
|
||||
typeof window !== 'undefined' ? new Audio() : null
|
||||
@@ -95,7 +92,7 @@ export function InstrumentalSelectorEmbedded({
|
||||
return (
|
||||
<Card className="p-4">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
No instrumental options available.
|
||||
{t('noOptionsAvailable')}
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
@@ -106,11 +103,11 @@ export function InstrumentalSelectorEmbedded({
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Music className="h-4 w-4 text-muted-foreground" />
|
||||
<Label className={cn("font-semibold", compact ? "text-sm" : "text-base")}>
|
||||
Select Instrumental Track
|
||||
{t('selectTrack')}
|
||||
</Label>
|
||||
{!value && (
|
||||
<Badge variant="destructive" className="ml-auto text-xs">
|
||||
Required
|
||||
{t('required')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
@@ -119,10 +116,10 @@ export function InstrumentalSelectorEmbedded({
|
||||
{analysis && (analysis.audible_percentage ?? 0) > 0 && (
|
||||
<div className="mb-3 text-xs text-muted-foreground">
|
||||
<span className="font-medium">
|
||||
{(analysis.audible_percentage ?? 0).toFixed(0)}% backing vocals detected
|
||||
{t('backingVocalsDetected', { percentage: (analysis.audible_percentage ?? 0).toFixed(0) })}
|
||||
</span>
|
||||
{(analysis.audible_segments?.length ?? 0) > 0 && (
|
||||
<span> ({analysis.audible_segments?.length ?? 0} segments)</span>
|
||||
<span> {t('segmentsCount', { count: analysis.audible_segments?.length ?? 0 })}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -173,12 +170,12 @@ export function InstrumentalSelectorEmbedded({
|
||||
{option.label}
|
||||
{isRecommended && (
|
||||
<Badge variant="secondary" className="text-xs bg-green-500/20 text-green-600">
|
||||
Recommended
|
||||
{t('options.recommended')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className={cn("text-muted-foreground", compact ? "text-xs" : "text-xs")}>
|
||||
{OPTION_DESCRIPTIONS[option.id] || `Instrumental option: ${option.id}`}
|
||||
{option.id === 'clean' ? t('cleanDescription') : option.id === 'with_backing' ? t('backingVocalsIncluded') : option.label}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { X } from "lucide-react"
|
||||
import type { MuteRegion, AudibleSegment } from "@/lib/api"
|
||||
@@ -38,6 +39,7 @@ export function MuteRegionEditor({
|
||||
onHoverRegion,
|
||||
onHoverSegment,
|
||||
}: MuteRegionEditorProps) {
|
||||
const t = useTranslations('instrumentalReview.muteRegion')
|
||||
const hasRegions = regions.length > 0
|
||||
const hasSegments = audibleSegments.length > 0
|
||||
|
||||
@@ -46,7 +48,7 @@ export function MuteRegionEditor({
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-semibold">
|
||||
Custom Mix {hasRegions && `(${regions.length} muted)`}
|
||||
{hasRegions ? t('titleWithCount', { count: regions.length }) : t('title')}
|
||||
</span>
|
||||
{hasRegions && (
|
||||
<div className="flex gap-1.5">
|
||||
@@ -56,7 +58,7 @@ export function MuteRegionEditor({
|
||||
onClick={onClearAll}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
Clear
|
||||
{t('clear')}
|
||||
</Button>
|
||||
{!hasCustom && (
|
||||
<Button
|
||||
@@ -65,7 +67,7 @@ export function MuteRegionEditor({
|
||||
disabled={isCreatingCustom}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
{isCreatingCustom ? "Creating..." : "Create Custom"}
|
||||
{isCreatingCustom ? t('creating') : t('createCustom')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -104,19 +106,14 @@ export function MuteRegionEditor({
|
||||
{hasSegments ? (
|
||||
<>
|
||||
<p>
|
||||
Want backing vocals but hear lead vocal bleed in some sections?
|
||||
Mute those sections to create a custom mix.
|
||||
{t('explanation')}
|
||||
</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.
|
||||
{t('clickSegment')}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p>No backing vocals detected — clean instrumental recommended.</p>
|
||||
<p>{t('noBackingDetected')}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -131,7 +128,7 @@ export function MuteRegionEditor({
|
||||
onClick={() => onAddSegment(index)}
|
||||
onMouseEnter={() => onHoverSegment?.(index)}
|
||||
onMouseLeave={() => onHoverSegment?.(null)}
|
||||
title="Add to mute regions"
|
||||
title={t('addToMuteRegions')}
|
||||
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"
|
||||
>
|
||||
{formatTime(segment.start_seconds)} - {formatTime(segment.end_seconds)}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { InstrumentalSelectionType, BackingVocalAnalysis, MuteRegion } from "@/lib/api"
|
||||
@@ -34,35 +35,36 @@ export function SelectionOptions({
|
||||
muteRegionsCount,
|
||||
backingVocalAnalysis,
|
||||
}: SelectionOptionsProps) {
|
||||
const t = useTranslations('instrumentalReview.options')
|
||||
const options: SelectionOption[] = [
|
||||
{
|
||||
value: "clean",
|
||||
label: "Clean Instrumental",
|
||||
description: "No backing vocals",
|
||||
label: t('cleanInstrumental'),
|
||||
description: t('noBackingVocals'),
|
||||
available: true,
|
||||
},
|
||||
{
|
||||
value: "with_backing",
|
||||
label: "With Backing Vocals",
|
||||
description: "All backing vocals included",
|
||||
label: t('withBackingVocals'),
|
||||
description: t('allBackingVocalsIncluded'),
|
||||
available: hasWithBacking,
|
||||
},
|
||||
{
|
||||
value: "original",
|
||||
label: "Original Audio",
|
||||
description: "Full original with lead vocals",
|
||||
label: t('originalAudio'),
|
||||
description: t('fullOriginalWithVocals'),
|
||||
available: hasOriginal,
|
||||
},
|
||||
{
|
||||
value: "custom",
|
||||
label: "Custom",
|
||||
description: `${muteRegionsCount} region${muteRegionsCount !== 1 ? "s" : ""} muted`,
|
||||
label: t('custom'),
|
||||
description: t('customRegionsMuted', { count: muteRegionsCount }),
|
||||
available: hasCustom,
|
||||
},
|
||||
{
|
||||
value: "uploaded",
|
||||
label: "Uploaded",
|
||||
description: uploadedFilename || "Custom instrumental file",
|
||||
label: t('uploaded'),
|
||||
description: uploadedFilename || t('customFile'),
|
||||
available: hasUploaded,
|
||||
},
|
||||
]
|
||||
@@ -71,7 +73,7 @@ export function SelectionOptions({
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label className="text-sm font-semibold">Final Selection</Label>
|
||||
<Label className="text-sm font-semibold">{t('finalSelection')}</Label>
|
||||
<div className="flex flex-col gap-2">
|
||||
{availableOptions.map((option) => (
|
||||
<button
|
||||
@@ -103,7 +105,7 @@ export function SelectionOptions({
|
||||
{option.label}
|
||||
{backingVocalAnalysis?.recommended_selection === option.value && (
|
||||
<span className="text-xs px-1.5 py-0.5 bg-green-500/20 text-green-500 rounded">
|
||||
Recommended
|
||||
{t('recommended')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -113,8 +115,8 @@ export function SelectionOptions({
|
||||
{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`}
|
||||
? t('veryFewVocals', { percentage: backingVocalAnalysis.audible_percentage.toFixed(0) })
|
||||
: t('significantVocals', { percentage: backingVocalAnalysis.audible_percentage.toFixed(0) })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Loader2 } from "lucide-react"
|
||||
|
||||
@@ -33,13 +34,14 @@ export function StemComparison({
|
||||
uploadedFilename,
|
||||
isLoading = false,
|
||||
}: StemComparisonProps) {
|
||||
const t = useTranslations('instrumentalReview.stemComparison')
|
||||
const options: AudioOption[] = [
|
||||
{ type: "original", label: "Original", available: hasOriginal },
|
||||
{ type: "backing", label: "Backing Vocals Only", available: true },
|
||||
{ type: "clean", label: "Pure Instrumental", available: true },
|
||||
{ type: "with_backing", label: "Instrumental + Backing", available: hasWithBacking },
|
||||
{ type: "custom", label: "Custom", available: hasCustom },
|
||||
{ type: "uploaded", label: "Uploaded", available: hasUploaded, title: uploadedFilename },
|
||||
{ type: "original", label: t('original'), available: hasOriginal },
|
||||
{ type: "backing", label: t('backingVocalsOnly'), available: true },
|
||||
{ type: "clean", label: t('pureInstrumental'), available: true },
|
||||
{ type: "with_backing", label: t('instrumentalPlusBacking'), available: hasWithBacking },
|
||||
{ type: "custom", label: t('custom'), available: hasCustom },
|
||||
{ type: "uploaded", label: t('uploaded'), available: hasUploaded, title: uploadedFilename },
|
||||
]
|
||||
|
||||
const availableOptions = options.filter((opt) => opt.available)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import type { ColorOverrides } from "@/lib/video-themes"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Input } from "@/components/ui/input"
|
||||
@@ -28,6 +29,7 @@ interface ColorFieldProps {
|
||||
}
|
||||
|
||||
function ColorField({ id, label, description, value, onChange, disabled }: ColorFieldProps) {
|
||||
const t = useTranslations('colorOverrides')
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -42,7 +44,7 @@ function ColorField({ id, label, description, value, onChange, disabled }: Color
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
disabled={disabled}
|
||||
>
|
||||
Reset
|
||||
{t('reset')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
@@ -82,6 +84,7 @@ function ColorField({ id, label, description, value, onChange, disabled }: Color
|
||||
}
|
||||
|
||||
export function ColorOverridesPanel({ value, onChange, disabled }: ColorOverridesProps) {
|
||||
const t = useTranslations('colorOverrides')
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
|
||||
const hasAnyOverrides = !!(
|
||||
@@ -113,10 +116,10 @@ export function ColorOverridesPanel({ value, onChange, disabled }: ColorOverride
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<Paintbrush className="w-4 h-4" />
|
||||
Customize Colors
|
||||
{t('title')}
|
||||
{hasAnyOverrides && (
|
||||
<span className="text-xs bg-amber-500/20 text-amber-400 px-1.5 py-0.5 rounded">
|
||||
Modified
|
||||
{t('modified')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
@@ -132,7 +135,7 @@ export function ColorOverridesPanel({ value, onChange, disabled }: ColorOverride
|
||||
<div className="space-y-4 p-4 rounded-lg border" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--secondary)' }}>
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Override theme colors (optional)
|
||||
{t('overrideThemeColors')}
|
||||
</p>
|
||||
{hasAnyOverrides && (
|
||||
<Button
|
||||
@@ -144,7 +147,7 @@ export function ColorOverridesPanel({ value, onChange, disabled }: ColorOverride
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<RotateCcw className="w-3 h-3 mr-1" />
|
||||
Reset All
|
||||
{t('resetAll')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -152,8 +155,8 @@ export function ColorOverridesPanel({ value, onChange, disabled }: ColorOverride
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<ColorField
|
||||
id="artist-color"
|
||||
label="Artist Color"
|
||||
description="Color for artist name on title/end screens"
|
||||
label={t('artistColor')}
|
||||
description={t('artistColorDesc')}
|
||||
value={value.artist_color}
|
||||
onChange={(v) => updateField("artist_color", v)}
|
||||
disabled={disabled}
|
||||
@@ -161,8 +164,8 @@ export function ColorOverridesPanel({ value, onChange, disabled }: ColorOverride
|
||||
|
||||
<ColorField
|
||||
id="title-color"
|
||||
label="Title Color"
|
||||
description="Color for song title on title/end screens"
|
||||
label={t('titleColor')}
|
||||
description={t('titleColorDesc')}
|
||||
value={value.title_color}
|
||||
onChange={(v) => updateField("title_color", v)}
|
||||
disabled={disabled}
|
||||
@@ -170,8 +173,8 @@ export function ColorOverridesPanel({ value, onChange, disabled }: ColorOverride
|
||||
|
||||
<ColorField
|
||||
id="sung-lyrics-color"
|
||||
label="Sung Lyrics Color"
|
||||
description="Color for lyrics being sung (highlighted)"
|
||||
label={t('sungLyricsColor')}
|
||||
description={t('sungLyricsColorDesc')}
|
||||
value={value.sung_lyrics_color}
|
||||
onChange={(v) => updateField("sung_lyrics_color", v)}
|
||||
disabled={disabled}
|
||||
@@ -179,8 +182,8 @@ export function ColorOverridesPanel({ value, onChange, disabled }: ColorOverride
|
||||
|
||||
<ColorField
|
||||
id="unsung-lyrics-color"
|
||||
label="Unsung Lyrics Color"
|
||||
description="Color for lyrics not yet sung"
|
||||
label={t('unsungLyricsColor')}
|
||||
description={t('unsungLyricsColorDesc')}
|
||||
value={value.unsung_lyrics_color}
|
||||
onChange={(v) => updateField("unsung_lyrics_color", v)}
|
||||
disabled={disabled}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { X, ExternalLink, Youtube, AlertTriangle } from "lucide-react"
|
||||
import type { CommunityCheckResponse } from "@/lib/api"
|
||||
|
||||
@@ -9,6 +10,7 @@ interface CommunityVersionBannerProps {
|
||||
}
|
||||
|
||||
export function CommunityVersionBanner({ data, onDismiss }: CommunityVersionBannerProps) {
|
||||
const t = useTranslations('communityVersion')
|
||||
if (!data.has_community || data.songs.length === 0) return null
|
||||
|
||||
// Collect all community tracks across songs, take top 3
|
||||
@@ -42,10 +44,10 @@ export function CommunityVersionBanner({ data, onDismiss }: CommunityVersionBann
|
||||
<div className="pr-6">
|
||||
<p className="text-sm font-medium flex items-center gap-1.5" style={{ color: "rgb(34, 197, 94)" }}>
|
||||
<AlertTriangle className="w-4 h-4 shrink-0" />
|
||||
A karaoke version of this song already exists!
|
||||
{t('exists')}
|
||||
</p>
|
||||
<p className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
|
||||
Check if an existing version works for you before using a credit.
|
||||
{t('checkFirst')}
|
||||
</p>
|
||||
|
||||
<div className="mt-2 space-y-1.5">
|
||||
@@ -69,13 +71,13 @@ export function CommunityVersionBanner({ data, onDismiss }: CommunityVersionBann
|
||||
color: "rgb(34, 197, 94)",
|
||||
}}
|
||||
>
|
||||
Community
|
||||
{t('community')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="ml-auto shrink-0 text-[10px] flex items-center gap-1" style={{ color: "var(--text-muted)" }}>
|
||||
<Youtube className="w-3 h-3 text-red-500" />
|
||||
Watch on YouTube
|
||||
{t('watchOnYoutube')}
|
||||
</span>
|
||||
</a>
|
||||
))}
|
||||
@@ -83,7 +85,7 @@ export function CommunityVersionBanner({ data, onDismiss }: CommunityVersionBann
|
||||
|
||||
{allTracks.length > 3 && (
|
||||
<p className="text-[10px] mt-1.5" style={{ color: "var(--text-muted)" }}>
|
||||
+{allTracks.length - 3} more version{allTracks.length - 3 > 1 ? "s" : ""}
|
||||
{t('moreVersions', { count: allTracks.length - 3 })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { api, Job } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Loader2 } from "lucide-react"
|
||||
@@ -23,6 +24,8 @@ interface EditTrackModalProps {
|
||||
}
|
||||
|
||||
export function EditTrackModal({ job, open, onOpenChange, onEditStarted }: EditTrackModalProps) {
|
||||
const t = useTranslations('editTrack')
|
||||
const tc = useTranslations('common')
|
||||
const [updateMetadata, setUpdateMetadata] = useState(false)
|
||||
const [artist, setArtist] = useState(job.artist || "")
|
||||
const [title, setTitle] = useState(job.title || "")
|
||||
@@ -77,10 +80,9 @@ export function EditTrackModal({ job, open, onOpenChange, onEditStarted }: EditT
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[480px]" onClick={(e) => e.stopPropagation()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Completed Track</DialogTitle>
|
||||
<DialogTitle>{t('title')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
This will remove the current video from YouTube, Dropbox, and Google Drive.
|
||||
After you complete the review again, a new version will be rendered and re-distributed.
|
||||
{t('description')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -94,7 +96,7 @@ export function EditTrackModal({ job, open, onOpenChange, onEditStarted }: EditT
|
||||
className="rounded"
|
||||
/>
|
||||
<Label htmlFor="update-metadata" className="cursor-pointer">
|
||||
I need to update the artist or title
|
||||
{t('updateArtistTitle')}
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
@@ -102,7 +104,7 @@ export function EditTrackModal({ job, open, onOpenChange, onEditStarted }: EditT
|
||||
<div className="grid gap-3 pl-6">
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="edit-artist" className="text-right">
|
||||
Artist
|
||||
{t('artist')}
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-artist"
|
||||
@@ -113,7 +115,7 @@ export function EditTrackModal({ job, open, onOpenChange, onEditStarted }: EditT
|
||||
</div>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="edit-title" className="text-right">
|
||||
Title
|
||||
{t('songTitle')}
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-title"
|
||||
@@ -137,7 +139,7 @@ export function EditTrackModal({ job, open, onOpenChange, onEditStarted }: EditT
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
Cancel
|
||||
{tc('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -147,10 +149,10 @@ export function EditTrackModal({ job, open, onOpenChange, onEditStarted }: EditT
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Cleaning up...
|
||||
{t('cleaningUp')}
|
||||
</>
|
||||
) : (
|
||||
"Confirm & Edit"
|
||||
t('confirmEdit')
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
@@ -19,7 +20,7 @@ interface GuidedJobFlowProps {
|
||||
|
||||
type Step = 1 | 2 | 3 | 4
|
||||
|
||||
const STEP_LABELS = ["Song Info", "Choose Audio", "Visibility", "Customize & Create"]
|
||||
const STEP_LABEL_KEYS = ["songInfo", "chooseAudio", "visibility", "customizeCreate"] as const
|
||||
|
||||
/**
|
||||
* Upload custom style assets to an already-created job.
|
||||
@@ -90,6 +91,7 @@ async function uploadStyleAssets(
|
||||
}
|
||||
|
||||
export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
const t = useTranslations('jobFlow')
|
||||
const { user } = useAuth()
|
||||
const { features } = useTenant()
|
||||
const isAdmin = user?.role === "admin"
|
||||
@@ -191,7 +193,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
})
|
||||
createdJobId = response.job_id
|
||||
} else {
|
||||
setSubmitError("Missing audio source. Please go back and try again.")
|
||||
setSubmitError(t('missingAudioSource'))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -213,12 +215,12 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
setSearchSessionId(null)
|
||||
setSelectedResultIndex(null)
|
||||
setStep(2)
|
||||
setSubmitError("Your search results expired. Please search again — your song info is still saved.")
|
||||
setSubmitError(t('searchExpired'))
|
||||
} else {
|
||||
setSubmitError(err.message)
|
||||
}
|
||||
} else {
|
||||
setSubmitError("Failed to start processing. Please try again.")
|
||||
setSubmitError(t('failedToStartProcessing'))
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
@@ -272,7 +274,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Job Created
|
||||
{t('jobCreated')}
|
||||
</h2>
|
||||
<p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="font-medium" style={{ color: 'var(--text)' }}>{effectiveArtist} - {effectiveTitle}</span>
|
||||
@@ -286,7 +288,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
</div>
|
||||
|
||||
{/* Timeline */}
|
||||
<p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'var(--text-muted)' }}>What happens next</p>
|
||||
<p className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'var(--text-muted)' }}>{t('whatsHappensNext')}</p>
|
||||
<div className="space-y-0 mt-3">
|
||||
{/* Step 1: Automated processing */}
|
||||
<div className="flex gap-3">
|
||||
@@ -300,12 +302,12 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
<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-sm font-medium" style={{ color: 'var(--text)' }}>{t('audioProcessing')}</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>
|
||||
{t('audioProcessingDesc')}
|
||||
</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
|
||||
{t('automatic')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -323,20 +325,20 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
<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 edit the audio</p>
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>{t('youEditTheAudio')}</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
Trim, cut, or mute sections of the downloaded audio before processing begins.
|
||||
{t('youEditDesc')}
|
||||
</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
|
||||
{t('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
|
||||
{t('emailChime')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -354,20 +356,20 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
<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-sm font-medium" style={{ color: 'var(--text)' }}>{t('youReviewLyrics')}</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.
|
||||
{t('youReviewDesc')}
|
||||
</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
|
||||
{t('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
|
||||
{t('emailChime')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -384,20 +386,20 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>Video delivered</p>
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>{t('videoDelivered')}</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>
|
||||
{t('videoDeliveredDesc')}
|
||||
</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
|
||||
{t('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
|
||||
{t('emailWithLink')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -405,7 +407,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
</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.
|
||||
{t('trackProgress')}
|
||||
</p>
|
||||
|
||||
<Button
|
||||
@@ -415,7 +417,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
>
|
||||
<Music className="w-4 h-4 mr-2" />
|
||||
Create Another
|
||||
{t('createAnother')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
@@ -428,13 +430,13 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
<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>
|
||||
<p>{t('noCreditsWarning')}</p>
|
||||
<button
|
||||
onClick={() => setShowBuyCreditsDialog(true)}
|
||||
className="inline-block mt-1 text-sm font-medium underline"
|
||||
style={{ color: 'var(--brand-pink)' }}
|
||||
>
|
||||
Buy Credits
|
||||
{t('buyCredits')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -442,13 +444,14 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
|
||||
{/* Step indicator */}
|
||||
<div className="flex items-center gap-1" role="navigation" aria-label="Progress">
|
||||
{STEP_LABELS.map((label, i) => {
|
||||
{STEP_LABEL_KEYS.map((key, i) => {
|
||||
const stepNum = (i + 1) as Step
|
||||
const isActive = step === stepNum
|
||||
const isCompleted = step > stepNum
|
||||
const label = t(`stepLabels.${key}`)
|
||||
|
||||
return (
|
||||
<div key={label} className="flex items-center gap-1 flex-1">
|
||||
<div key={key} 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 ${
|
||||
@@ -470,7 +473,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
{i < STEP_LABELS.length - 1 && (
|
||||
{i < STEP_LABEL_KEYS.length - 1 && (
|
||||
<div
|
||||
className="h-px flex-1 mx-1 hidden sm:block"
|
||||
style={{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useRef, useState } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Upload, X, ImageIcon } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
@@ -23,19 +24,20 @@ function formatFileSize(bytes: number): string {
|
||||
}
|
||||
|
||||
export function ImageUploadField({ label, description, file, onChange, disabled, hidePreview }: ImageUploadFieldProps) {
|
||||
const t = useTranslations('imageUpload')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const [dragOver, setDragOver] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const validate = useCallback((f: File): string | null => {
|
||||
if (!ALLOWED_TYPES.includes(f.type)) {
|
||||
return "Only PNG and JPG images are allowed."
|
||||
return t('onlyPngJpg')
|
||||
}
|
||||
if (f.size > MAX_SIZE_BYTES) {
|
||||
return `File too large (${formatFileSize(f.size)}). Maximum is 10 MB.`
|
||||
return t('fileTooLarge', { size: formatFileSize(f.size) })
|
||||
}
|
||||
return null
|
||||
}, [])
|
||||
}, [t])
|
||||
|
||||
const handleFile = useCallback((f: File) => {
|
||||
const err = validate(f)
|
||||
@@ -126,10 +128,10 @@ export function ImageUploadField({ label, description, file, onChange, disabled,
|
||||
>
|
||||
<Upload className="w-5 h-5" style={{ color: 'var(--text-muted)' }} />
|
||||
<p className="text-xs text-center" style={{ color: 'var(--text-muted)' }}>
|
||||
Drop an image here or <span style={{ color: 'var(--brand-pink)' }}>browse</span>
|
||||
{t('dropOrBrowse')}
|
||||
</p>
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
PNG or JPG, max 10 MB
|
||||
{t('maxSize')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Job, api } from "@/lib/api"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -15,6 +16,7 @@ interface JobActionsProps {
|
||||
}
|
||||
|
||||
export function JobActions({ job, onRefresh }: JobActionsProps) {
|
||||
const t = useTranslations('jobActions')
|
||||
const [isRetrying, setIsRetrying] = useState(false)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const { toast } = useToast()
|
||||
@@ -28,8 +30,8 @@ export function JobActions({ job, onRefresh }: JobActionsProps) {
|
||||
try {
|
||||
await api.retryJob(job.job_id)
|
||||
toast({
|
||||
title: "Job retry started",
|
||||
description: "The job is being retried. Refreshing status...",
|
||||
title: t('jobRetryStarted'),
|
||||
description: t('jobRetryStartedDesc'),
|
||||
variant: "default",
|
||||
})
|
||||
onRefresh()
|
||||
@@ -42,7 +44,7 @@ export function JobActions({ job, onRefresh }: JobActionsProps) {
|
||||
"Failed to retry job. Please try again."
|
||||
|
||||
toast({
|
||||
title: "Retry failed",
|
||||
title: t('retryFailed'),
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
})
|
||||
@@ -52,7 +54,7 @@ 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
|
||||
if (!confirm(t('permanentlyCancel'))) return
|
||||
|
||||
// Statuses where the backend does NOT refund credits
|
||||
const noRefundStatuses = ["complete", "prep_complete", "failed", "cancelled"]
|
||||
@@ -65,13 +67,13 @@ export function JobActions({ job, onRefresh }: JobActionsProps) {
|
||||
await fetchUser()
|
||||
const remaining = useAuth.getState().user?.credits ?? 0
|
||||
toast({
|
||||
title: "Credit refunded",
|
||||
description: `1 credit returned to your account. ${remaining} remaining.`,
|
||||
title: t('creditRefunded'),
|
||||
description: t('creditRefundedDesc', { remaining }),
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: "Job deleted",
|
||||
description: "The job has been permanently deleted.",
|
||||
title: t('jobDeleted'),
|
||||
description: t('jobDeletedDesc'),
|
||||
})
|
||||
}
|
||||
onRefresh()
|
||||
@@ -83,7 +85,7 @@ export function JobActions({ job, onRefresh }: JobActionsProps) {
|
||||
"Failed to delete job. Please try again."
|
||||
|
||||
toast({
|
||||
title: "Delete failed",
|
||||
title: t('deleteFailed'),
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
})
|
||||
@@ -113,7 +115,7 @@ export function JobActions({ job, onRefresh }: JobActionsProps) {
|
||||
) : (
|
||||
<Trash2 className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Delete
|
||||
{t('delete')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -131,7 +133,7 @@ export function JobActions({ job, onRefresh }: JobActionsProps) {
|
||||
) : (
|
||||
<RotateCcw className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Retry
|
||||
{t('retry')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Job } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Zap } from "lucide-react"
|
||||
@@ -17,15 +18,21 @@ import { useAuth } from "@/lib/auth"
|
||||
* Displays: "[4/10] Processing..." with colored text and optional progress bar
|
||||
*/
|
||||
function StatusIndicator({ job }: { job: Job }) {
|
||||
const t = useTranslations('jobCard')
|
||||
const tStatus = useTranslations('jobStatus')
|
||||
const { step, total, label, isBlocking, color } = getJobStep(job)
|
||||
const formattedStatus = formatStepIndicator(step, total, label)
|
||||
// Translate status label(s) — may contain " + " for combined parallel status
|
||||
const translatedLabel = label.includes(' + ')
|
||||
? label.split(' + ').map(k => tStatus(k as any)).join(' + ')
|
||||
: tStatus(label as any)
|
||||
const formattedStatus = formatStepIndicator(step, total, translatedLabel)
|
||||
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span className={color}>{formattedStatus}</span>
|
||||
{isBlocking && (
|
||||
<span className="text-amber-400 text-[10px] font-medium uppercase tracking-wide">
|
||||
Action needed
|
||||
{t('actionNeeded')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
@@ -76,6 +83,7 @@ interface JobCardProps {
|
||||
}
|
||||
|
||||
export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
const t = useTranslations('jobCard')
|
||||
const [showAudioSearch, setShowAudioSearch] = useState(false)
|
||||
const { user } = useAuth()
|
||||
const isAdmin = user?.role === 'admin'
|
||||
@@ -97,9 +105,9 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-1 text-xs text-amber-400">
|
||||
<Zap className="w-3 h-3" />
|
||||
Will auto-{job.status === "awaiting_review" || job.status === "in_review" ? "accept" :
|
||||
job.status === "awaiting_instrumental_selection" ? "select" :
|
||||
"select first"}
|
||||
{job.status === "awaiting_review" || job.status === "in_review" ? t('autoAccept') :
|
||||
job.status === "awaiting_instrumental_selection" ? t('autoSelect') :
|
||||
t('willAutoSelectFirst')}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -111,7 +119,7 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
href={`/app/jobs#/${job.job_id}/review`}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-primary-500 hover:bg-primary-600 text-white"
|
||||
>
|
||||
Review Lyrics
|
||||
{t('reviewLyrics')}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
@@ -122,7 +130,7 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
href={`/app/jobs#/${job.job_id}/audio-edit`}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-primary-500 hover:bg-primary-600 text-white"
|
||||
>
|
||||
Edit Audio
|
||||
{t('editAudio')}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
@@ -134,7 +142,7 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
onClick={() => setShowAudioSearch(true)}
|
||||
className="text-xs h-7 px-3 bg-primary-500 hover:bg-primary-600"
|
||||
>
|
||||
Select Audio
|
||||
{t('selectAudio')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -146,7 +154,7 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
href={`/app/jobs#/${job.job_id}/instrumental`}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-primary-500 hover:bg-primary-600 text-white"
|
||||
>
|
||||
Select Instrumental
|
||||
{t('selectInstrumental')}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useMemo, useCallback, useRef } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import type { CatalogArtistResult, CatalogTrackResult, CommunityCheckResponse } from "@/lib/api"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
@@ -20,6 +21,8 @@ interface JobSubmissionProps {
|
||||
}
|
||||
|
||||
export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
const t = useTranslations('jobSubmission')
|
||||
const tFlow = useTranslations('jobFlow')
|
||||
const { user, fetchUser } = useAuth()
|
||||
const { features, isDefault, tenant } = useTenant()
|
||||
const { toast } = useToast()
|
||||
@@ -186,11 +189,11 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setIsCreditError(true)
|
||||
setError("You're out of credits. Buy more to continue creating karaoke videos.")
|
||||
setError(t('outOfCredits'))
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError("Failed to create job")
|
||||
setError(t('failedToCreateJob'))
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
@@ -229,11 +232,11 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setIsCreditError(true)
|
||||
setError("You're out of credits. Buy more to continue creating karaoke videos.")
|
||||
setError(t('outOfCredits'))
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError("Failed to create job")
|
||||
setError(t('failedToCreateJob'))
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
@@ -267,11 +270,11 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setIsCreditError(true)
|
||||
setError("You're out of credits. Buy more to continue creating karaoke videos.")
|
||||
setError(t('outOfCredits'))
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError("Failed to search for audio")
|
||||
setError(t('failedToCreateJob'))
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
@@ -294,13 +297,13 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
<div className="flex items-start gap-2 rounded-lg p-3 mb-4 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>
|
||||
<p>{tFlow('noCreditsWarning')}</p>
|
||||
<button
|
||||
onClick={() => setShowBuyCreditsDialog(true)}
|
||||
className="inline-block mt-1 text-sm font-medium underline"
|
||||
style={{ color: 'var(--brand-pink)' }}
|
||||
>
|
||||
Buy Credits
|
||||
{tFlow('buyCredits')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -321,7 +324,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
style={{ color: activeTab === 'search' ? 'white' : 'var(--text-muted)' }}
|
||||
>
|
||||
<Music className="w-4 h-4 shrink-0" />
|
||||
<span className="truncate">Search</span>
|
||||
<span className="truncate">{t('search')}</span>
|
||||
</TabsTrigger>
|
||||
)}
|
||||
{availableTabs.includes("upload") && (
|
||||
@@ -331,7 +334,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
style={{ color: activeTab === 'upload' ? 'white' : 'var(--text-muted)' }}
|
||||
>
|
||||
<Upload className="w-4 h-4 shrink-0" />
|
||||
<span className="truncate">Upload</span>
|
||||
<span className="truncate">{t('upload')}</span>
|
||||
</TabsTrigger>
|
||||
)}
|
||||
{availableTabs.includes("url") && (
|
||||
@@ -341,7 +344,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
style={{ color: activeTab === 'url' ? 'white' : 'var(--text-muted)' }}
|
||||
>
|
||||
<Youtube className="w-4 h-4 shrink-0" />
|
||||
<span className="truncate">URL</span>
|
||||
<span className="truncate">{t('url')}</span>
|
||||
</TabsTrigger>
|
||||
)}
|
||||
</TabsList>
|
||||
@@ -351,7 +354,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
<TabsContent value="upload" className={availableTabs.length === 1 ? "" : "mt-4"}>
|
||||
<form onSubmit={handleUploadSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="audio-file" style={{ color: 'var(--text)' }}>Audio File</Label>
|
||||
<Label htmlFor="audio-file" style={{ color: 'var(--text)' }}>{t('audioFile')}</Label>
|
||||
<div
|
||||
className="relative border-2 border-dashed rounded-lg p-6 text-center transition-colors cursor-pointer"
|
||||
style={{
|
||||
@@ -375,8 +378,8 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<p className="font-medium mb-1" style={{ color: 'var(--text)' }}>Click to upload</p>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>MP3, WAV, FLAC, M4A, or OGG</p>
|
||||
<p className="font-medium mb-1" style={{ color: 'var(--text)' }}>{t('clickToUpload')}</p>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('supportedFormats')}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -384,7 +387,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="upload-artist" style={{ color: 'var(--text)' }}>Artist</Label>
|
||||
<Label htmlFor="upload-artist" style={{ color: 'var(--text)' }}>{tFlow('artist')}</Label>
|
||||
<AutocompleteInput
|
||||
id="upload-artist"
|
||||
placeholder="Artist name"
|
||||
@@ -396,7 +399,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="upload-title" style={{ color: 'var(--text)' }}>Title</Label>
|
||||
<Label htmlFor="upload-title" style={{ color: 'var(--text)' }}>{tFlow('title')}</Label>
|
||||
<AutocompleteInput
|
||||
id="upload-title"
|
||||
placeholder="Song title"
|
||||
@@ -409,7 +412,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="text-amber-500 font-medium">Tip:</span> Start typing and select from suggestions for correct formatting, or type freely.
|
||||
<span className="text-amber-500 font-medium">Tip:</span> {t('artistTip')}
|
||||
</p>
|
||||
|
||||
{/* Private (no YouTube upload) mode */}
|
||||
@@ -425,10 +428,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="private-upload" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (no YouTube upload)
|
||||
{t('privateNoYoutubeUpload')}
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
{t('filesDropboxOnly')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -451,10 +454,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Creating Job...
|
||||
{t('creatingJob')}
|
||||
</>
|
||||
) : (
|
||||
"Create Karaoke Video"
|
||||
tFlow('createKaraokeVideo')
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
@@ -465,13 +468,13 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
<TabsContent value="url" className={availableTabs.length === 1 ? "" : "mt-4"}>
|
||||
<form onSubmit={handleUrlSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="youtube-url" style={{ color: 'var(--text)' }}>YouTube URL</Label>
|
||||
<Label htmlFor="youtube-url" style={{ color: 'var(--text)' }}>{t('youtubeUrlLabel')}</Label>
|
||||
<div className="relative">
|
||||
<Youtube className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" style={{ color: 'var(--text-muted)' }} />
|
||||
<Input
|
||||
id="youtube-url"
|
||||
type="url"
|
||||
placeholder="https://youtube.com/watch?v=..."
|
||||
placeholder={t('youtubeUrlPlaceholder')}
|
||||
value={youtubeUrl}
|
||||
onChange={(e) => setYoutubeUrl(e.target.value)}
|
||||
className="pl-10"
|
||||
@@ -483,7 +486,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="youtube-artist" style={{ color: 'var(--text)' }}>Artist</Label>
|
||||
<Label htmlFor="youtube-artist" style={{ color: 'var(--text)' }}>{tFlow('artist')}</Label>
|
||||
<AutocompleteInput
|
||||
id="youtube-artist"
|
||||
placeholder="Artist name"
|
||||
@@ -495,7 +498,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="youtube-title" style={{ color: 'var(--text)' }}>Title</Label>
|
||||
<Label htmlFor="youtube-title" style={{ color: 'var(--text)' }}>{tFlow('title')}</Label>
|
||||
<AutocompleteInput
|
||||
id="youtube-title"
|
||||
placeholder="Song title"
|
||||
@@ -508,7 +511,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="text-amber-500 font-medium">Tip:</span> Start typing and select from suggestions for correct formatting, or type freely.
|
||||
<span className="text-amber-500 font-medium">Tip:</span> {t('artistTip')}
|
||||
</p>
|
||||
|
||||
{/* Private (no YouTube upload) mode */}
|
||||
@@ -524,10 +527,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="private-url" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (no YouTube upload)
|
||||
{t('privateNoYoutubeUpload')}
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
{t('filesDropboxOnly')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -550,10 +553,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Creating Job...
|
||||
{t('creatingJob')}
|
||||
</>
|
||||
) : (
|
||||
"Create Karaoke Video"
|
||||
tFlow('createKaraokeVideo')
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
@@ -565,10 +568,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
<form onSubmit={handleSearchSubmit} className="space-y-4">
|
||||
{/* Search For section */}
|
||||
<div className="space-y-2">
|
||||
<Label style={{ color: 'var(--text)' }}>Search For Audio Online</Label>
|
||||
<Label style={{ color: 'var(--text)' }}>{t('searchForAudioOnline')}</Label>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="search-artist" className="text-xs" style={{ color: 'var(--text-muted)' }}>Artist</Label>
|
||||
<Label htmlFor="search-artist" className="text-xs" style={{ color: 'var(--text-muted)' }}>{tFlow('artist')}</Label>
|
||||
<AutocompleteInput
|
||||
id="search-artist"
|
||||
data-testid="search-artist-input"
|
||||
@@ -581,7 +584,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="search-title" className="text-xs" style={{ color: 'var(--text-muted)' }}>Title</Label>
|
||||
<Label htmlFor="search-title" className="text-xs" style={{ color: 'var(--text-muted)' }}>{tFlow('title')}</Label>
|
||||
<AutocompleteInput
|
||||
id="search-title"
|
||||
data-testid="search-title-input"
|
||||
@@ -596,7 +599,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
<span className="text-amber-500 font-medium">Tip:</span> Start typing and select from suggestions for correct formatting, or type freely.
|
||||
<span className="text-amber-500 font-medium">Tip:</span> {t('artistTip')}
|
||||
</p>
|
||||
|
||||
{/* Community version check banner */}
|
||||
@@ -621,7 +624,7 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
)}
|
||||
Use different artist/title for title screen
|
||||
{t('useDisplayAs')}
|
||||
</button>
|
||||
{showDisplayAs && (
|
||||
<div className="space-y-2 pl-6">
|
||||
@@ -630,10 +633,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="display-artist" className="text-xs" style={{ color: 'var(--text-muted)' }}>Display Artist</Label>
|
||||
<Label htmlFor="display-artist" className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('displayArtist')}</Label>
|
||||
<Input
|
||||
id="display-artist"
|
||||
placeholder="e.g., Footloose (Broadway Cast)"
|
||||
placeholder={t('displayArtistPlaceholder')}
|
||||
value={displayArtist}
|
||||
onChange={(e) => setDisplayArtist(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
@@ -641,10 +644,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="display-title" className="text-xs" style={{ color: 'var(--text-muted)' }}>Display Title</Label>
|
||||
<Label htmlFor="display-title" className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('displayTitle')}</Label>
|
||||
<Input
|
||||
id="display-title"
|
||||
placeholder="e.g., I Can't Stand Still"
|
||||
placeholder={t('displayTitlePlaceholder')}
|
||||
value={displayTitle}
|
||||
onChange={(e) => setDisplayTitle(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
@@ -669,10 +672,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="private-search" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (no YouTube upload)
|
||||
{t('privateNoYoutubeUpload')}
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
{t('filesDropboxOnly')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -695,10 +698,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Searching...
|
||||
{t('searching')}
|
||||
</>
|
||||
) : (
|
||||
"Search & Create Job"
|
||||
t('searchCreateJob')
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useCallback, useEffect, useState } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { api, adminApi, Job } from "@/lib/api"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -34,6 +35,9 @@ interface OutputLinksProps {
|
||||
}
|
||||
|
||||
export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
const t = useTranslations('outputLinks')
|
||||
const tc = useTranslations('common')
|
||||
const tCard = useTranslations('jobCard')
|
||||
// Use file_urls from job directly - no API call needed
|
||||
const downloadUrls = job.file_urls || null
|
||||
// Use state_data from job directly - no API call needed
|
||||
@@ -207,16 +211,16 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
YouTube
|
||||
{t('youtube')}
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); copyToClipboard(youtubeUrl) }}
|
||||
className="inline-flex items-center text-xs px-2 py-1.5 rounded-r bg-red-700 hover:bg-red-600 text-white transition-colors"
|
||||
title="Copy YouTube URL"
|
||||
aria-label={copiedUrl === youtubeUrl ? "YouTube URL copied" : "Copy YouTube URL"}
|
||||
title={t('copyYoutubeUrl')}
|
||||
aria-label={copiedUrl === youtubeUrl ? t('youtubeUrlCopied') : t('copyYoutubeUrl')}
|
||||
>
|
||||
{copiedUrl === youtubeUrl ? <span className="text-[10px]">Copied!</span> : <Copy className="w-3 h-3" />}
|
||||
{copiedUrl === youtubeUrl ? <span className="text-[10px]">{t('copied')}</span> : <Copy className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -230,16 +234,16 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<FolderOpen className="w-3 h-3" />
|
||||
Dropbox
|
||||
{t('dropbox')}
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); copyToClipboard(dropboxUrl) }}
|
||||
className="inline-flex items-center text-xs px-2 py-1.5 rounded-r bg-[#0052d6] hover:bg-[#0047ba] text-white transition-colors"
|
||||
title="Copy Dropbox URL"
|
||||
aria-label={copiedUrl === dropboxUrl ? "Dropbox URL copied" : "Copy Dropbox URL"}
|
||||
title={t('copyDropboxUrl')}
|
||||
aria-label={copiedUrl === dropboxUrl ? t('dropboxUrlCopied') : t('copyDropboxUrl')}
|
||||
>
|
||||
{copiedUrl === dropboxUrl ? <span className="text-[10px]">Copied!</span> : <Copy className="w-3 h-3" />}
|
||||
{copiedUrl === dropboxUrl ? <span className="text-[10px]">{t('copied')}</span> : <Copy className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -256,7 +260,7 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
4K Video
|
||||
{t('video4k')}
|
||||
</a>
|
||||
)}
|
||||
{downloadUrls?.finals?.lossy_720p_mp4 && (
|
||||
@@ -266,7 +270,7 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
720p Video
|
||||
{t('video720p')}
|
||||
</a>
|
||||
)}
|
||||
{(downloadUrls?.finals?.with_vocals_mp4 || downloadUrls?.videos?.with_vocals) && (
|
||||
@@ -279,7 +283,7 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
With Vocals
|
||||
{t('withVocals')}
|
||||
</a>
|
||||
)}
|
||||
{downloadUrls?.packages?.cdg_zip && (
|
||||
@@ -289,7 +293,7 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
CDG
|
||||
{t('cdg')}
|
||||
</a>
|
||||
)}
|
||||
{downloadUrls?.packages?.txt_zip && (
|
||||
@@ -299,7 +303,7 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
TXT
|
||||
{t('txt')}
|
||||
</a>
|
||||
)}
|
||||
</>
|
||||
@@ -322,8 +326,8 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
<Lock className="w-3 h-3" />
|
||||
)}
|
||||
{isChangingVisibility
|
||||
? (isPrivate ? "Making Public..." : "Making Private...")
|
||||
: (isPrivate ? "Make Public" : "Make Private")
|
||||
? (isPrivate ? t('makingPublic') : t('makingPrivate'))
|
||||
: (isPrivate ? t('makePublic') : t('makePrivate'))
|
||||
}
|
||||
</button>
|
||||
)}
|
||||
@@ -338,19 +342,19 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
title="Send completion email"
|
||||
>
|
||||
<Mail className="w-3 h-3" />
|
||||
Email
|
||||
{t('email')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); copyCompletionMessage() }}
|
||||
disabled={isLoadingMessage}
|
||||
className="inline-flex items-center text-xs px-2 py-1.5 rounded-r bg-[#1a1a1a] hover:bg-[#2a2a2a] text-[var(--text)] border border-[var(--card-border)] disabled:opacity-50 transition-colors"
|
||||
title="Copy completion message to clipboard"
|
||||
title={t('copyCompletionMessage')}
|
||||
>
|
||||
{isLoadingMessage ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : copiedMessage ? (
|
||||
<span className="text-[10px]">Copied!</span>
|
||||
<span className="text-[10px]">{t('copied')}</span>
|
||||
) : (
|
||||
<Copy className="w-3 h-3" />
|
||||
)}
|
||||
@@ -380,36 +384,36 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
title="View job details in admin"
|
||||
>
|
||||
<Settings className="w-3 h-3" />
|
||||
Admin
|
||||
{t('admin')}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hasOutputs && !isAdmin && !canChangeVisibility && (
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>No outputs available yet</p>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{tCard('noOutputsAvailable')}</p>
|
||||
)}
|
||||
|
||||
{/* Send Email Dialog */}
|
||||
<Dialog open={showEmailDialog} onOpenChange={setShowEmailDialog}>
|
||||
<DialogContent className="sm:max-w-[425px]" onClick={(e) => e.stopPropagation()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Send Completion Email</DialogTitle>
|
||||
<DialogTitle>{t('sendCompletionEmail')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Send the job completion message to an email address. The email will be CC'd to gen@nomadkaraoke.com.
|
||||
{t('sendToEmailDesc')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="email" className="text-right">
|
||||
Email
|
||||
{t('emailAddress')}
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={emailInput}
|
||||
onChange={(e) => setEmailInput(e.target.value)}
|
||||
placeholder="customer@example.com"
|
||||
placeholder={t('emailPlaceholder')}
|
||||
className="col-span-3"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
@@ -426,7 +430,7 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
onClick={() => setShowEmailDialog(false)}
|
||||
disabled={isSendingEmail}
|
||||
>
|
||||
Cancel
|
||||
{tc('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -436,12 +440,12 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
{isSendingEmail ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Sending...
|
||||
{t('sending')}
|
||||
</>
|
||||
) : emailSent ? (
|
||||
"Sent!"
|
||||
t('sent')
|
||||
) : (
|
||||
"Send Email"
|
||||
t('sendEmail')
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
@@ -453,36 +457,36 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
<AlertDialogContent onClick={(e) => e.stopPropagation()}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{isPrivate ? "Make This Track Public?" : "Make This Track Private?"}
|
||||
{isPrivate ? t('makePublicTitle') : t('makePrivateTitle')}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-3">
|
||||
{isPrivate ? (
|
||||
<>
|
||||
<p>This will:</p>
|
||||
<p>{t('thisWill')}</p>
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li>Remove any custom styling (backgrounds, colors) and reset to the standard Nomad Karaoke theme</li>
|
||||
<li>Regenerate title and end screens</li>
|
||||
<li>Re-render the karaoke video with default branding</li>
|
||||
<li>Publish to YouTube, Google Drive, and Dropbox</li>
|
||||
<li>{t('removeCustomStyling')}</li>
|
||||
<li>{t('regenerateTitleEndScreens')}</li>
|
||||
<li>{t('reRenderWithDefault')}</li>
|
||||
<li>{t('publishToAll')}</li>
|
||||
</ul>
|
||||
<p>This process takes approximately 15-30 minutes. You'll receive an email when it's complete.</p>
|
||||
<p>{t('takes15To30Minutes')}</p>
|
||||
<p className="font-medium" style={{ color: 'var(--text)' }}>
|
||||
Any custom styling you applied will be permanently removed.
|
||||
{t('customStylingRemoved')}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>This will:</p>
|
||||
<p>{t('thisWill')}</p>
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li>Remove the video from YouTube</li>
|
||||
<li>Remove files from Google Drive</li>
|
||||
<li>Move Dropbox files from the public folder to the private folder</li>
|
||||
<li>Assign a new private brand code</li>
|
||||
<li>{t('removeFromYoutube')}</li>
|
||||
<li>{t('removeFromGoogleDrive')}</li>
|
||||
<li>{t('moveDropboxPrivate')}</li>
|
||||
<li>{t('assignPrivateBrand')}</li>
|
||||
</ul>
|
||||
<p>The video content won't change. This usually takes about 1-2 minutes.</p>
|
||||
<p>{t('videoContentWontChange')}</p>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
You can change it back to public later, but that will require re-rendering the video (~15-30 minutes).
|
||||
{t('canChangeBack')}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
@@ -490,9 +494,9 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogCancel>{tc('cancel')}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleChangeVisibility}>
|
||||
{isPrivate ? "Make Public" : "Make Private"}
|
||||
{isPrivate ? t('makePublic') : t('makePrivate')}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useRef, useCallback } from "react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { CheckCircle2, Upload, Music, Loader2, AlertTriangle } from "lucide-react"
|
||||
@@ -22,6 +23,7 @@ interface TenantJobFlowProps {
|
||||
type SubmitPhase = "idle" | "creating" | "uploading-mixed" | "uploading-instrumental" | "completing" | "done"
|
||||
|
||||
export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
const t = useTranslations('jobFlow')
|
||||
const { branding } = useTenant()
|
||||
|
||||
// Form fields
|
||||
@@ -139,7 +141,7 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: "var(--text)" }}>
|
||||
Track Submitted
|
||||
{t('trackSubmitted')}
|
||||
</h2>
|
||||
<p className="text-sm mt-1" style={{ color: "var(--text-muted)" }}>
|
||||
<span className="font-medium" style={{ color: "var(--text)" }}>
|
||||
@@ -156,7 +158,7 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
|
||||
{/* Timeline — simplified for tenant (no audio processing step) */}
|
||||
<p className="text-xs font-semibold uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>
|
||||
What happens next
|
||||
{t('whatsHappensNext')}
|
||||
</p>
|
||||
<div className="space-y-0 mt-3">
|
||||
{/* Step 1: Lyrics transcription */}
|
||||
@@ -171,12 +173,12 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
<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)" }}>Lyrics transcription</p>
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>{t('lyricsTranscription')}</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
|
||||
We transcribe and sync lyrics from your audio. <span className="font-medium" style={{ color: "var(--text)" }}>~5 minutes</span>
|
||||
{t('lyricsTranscriptionDesc')}
|
||||
</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
|
||||
{t('automatic')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -192,20 +194,20 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
<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)" }}>Review lyrics</p>
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>{t('reviewLyrics')}</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
|
||||
Check the synced lyrics and fix any errors.
|
||||
{t('reviewLyricsDesc')}
|
||||
</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
|
||||
{t('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 when ready
|
||||
{t('emailWhenReady')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -222,19 +224,19 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Video delivered</p>
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>{t('videoDelivered')}</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
|
||||
After approval, your karaoke video is rendered and delivered. <span className="font-medium" style={{ color: "var(--text)" }}>~10 minutes</span>
|
||||
{t('afterApproval')}
|
||||
</p>
|
||||
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-green-500/15 text-green-400">
|
||||
Automatic
|
||||
{t('automatic')}
|
||||
</span>
|
||||
</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.
|
||||
{t('trackProgressTenant')}
|
||||
</p>
|
||||
|
||||
<Button
|
||||
@@ -244,7 +246,7 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
style={{ borderColor: "var(--card-border)", color: "var(--text)" }}
|
||||
>
|
||||
<Music className="w-4 h-4 mr-2" />
|
||||
Submit Another Track
|
||||
{t('submitAnother')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
@@ -256,7 +258,7 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
<div className="space-y-4">
|
||||
{/* Artist */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="tenant-artist" style={{ color: "var(--text)" }}>Artist</Label>
|
||||
<Label htmlFor="tenant-artist" style={{ color: "var(--text)" }}>{t('artist')}</Label>
|
||||
<Input
|
||||
id="tenant-artist"
|
||||
placeholder="e.g. Adele"
|
||||
@@ -269,7 +271,7 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
|
||||
{/* Title */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="tenant-title" style={{ color: "var(--text)" }}>Title</Label>
|
||||
<Label htmlFor="tenant-title" style={{ color: "var(--text)" }}>{t('title')}</Label>
|
||||
<Input
|
||||
id="tenant-title"
|
||||
placeholder="e.g. Someone Like You"
|
||||
@@ -318,10 +320,10 @@ export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
<div className="flex items-center gap-2 text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<span>
|
||||
{phase === "creating" && "Creating job..."}
|
||||
{phase === "uploading-mixed" && "Uploading mixed audio..."}
|
||||
{phase === "uploading-instrumental" && "Uploading instrumental..."}
|
||||
{phase === "completing" && "Finalizing..."}
|
||||
{phase === "creating" && t('creating')}
|
||||
{phase === "uploading-mixed" && t('creating')}
|
||||
{phase === "uploading-instrumental" && t('creating')}
|
||||
{phase === "completing" && t('creating')}
|
||||
</span>
|
||||
</div>
|
||||
{(phase === "uploading-mixed" || phase === "uploading-instrumental") && (
|
||||
|
||||
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user