mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-06 09:57:39 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d76a136ee6 | ||
|
|
9014754bda | ||
|
|
eab20db79c | ||
|
|
286e604b75 | ||
|
|
c4c4f9265c | ||
|
|
76069573eb |
No files matched your search
@@ -2176,7 +2176,7 @@ jobs:
|
||||
--min-instances 0 \
|
||||
--clear-vpc-connector \
|
||||
--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,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,STORAGE_RETENTION_DRY_RUN=false,STORAGE_RETENTION_MAX_JOBS_PER_RUN=50,CONVERSION_EMAILS_ENABLED=true,REVIEW_LAST_CHANCE_ENABLED=true,CONVERSION_OFFER_PERCENT=25,YOUTUBE_COMMENT_AUTOREPLY_ENABLED=true,YOUTUBE_COMMENT_AUTOREPLY_START=2026-04-22T00:00:00Z,EDGE_AUTH_MODE=enforce,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 "ANTHROPIC_API_KEY=anthropic-api-key:latest,GEMINI_API_KEY=gemini-api-key:latest,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,LRCLIB_APP_ID=lrclib-app-id:latest,LRCLIB_SECRET_KEY=lrclib-api-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,POSTMARK_SERVER_TOKEN=postmark-server-token: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,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms: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,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest,DECIDE_GEN_PARTNER_SECRET=decide-gen-partner-secret:latest"
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,GEMINI_API_KEY=gemini-api-key:latest,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,LRCLIB_APP_ID=lrclib-app-id:latest,LRCLIB_SECRET_KEY=lrclib-api-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,POSTMARK_SERVER_TOKEN=postmark-server-token: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,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms: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,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest,DECIDE_GEN_PARTNER_SECRET=decide-gen-partner-secret:latest,REVENUECAT_WEBHOOK_AUTH=revenuecat-webhook-auth:latest,REVENUECAT_SECRET_API_KEY=revenuecat-secret-api-key:latest,APP_REVIEW_DEMO_CODE=app-review-demo-code:latest"
|
||||
|
||||
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
|
||||
- name: Smoke candidate revision
|
||||
@@ -2280,6 +2280,20 @@ jobs:
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
# Voice-pool separate-only job (GPU, us-east4) — same GPU image. Created by
|
||||
# Pulumi; tolerate it not existing yet (pre `pulumi up`).
|
||||
if gcloud run jobs describe voice-pool-separate-job \
|
||||
--region us-east4 \
|
||||
--project ${{ env.PROJECT_ID }} >/dev/null 2>&1; then
|
||||
gcloud run jobs update voice-pool-separate-job \
|
||||
--image "$GPU_IMAGE" \
|
||||
--region us-east4 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
else
|
||||
echo "::warning::voice-pool-separate-job not found in us-east4 (run pulumi up); skipping image update"
|
||||
fi
|
||||
|
||||
echo "✅ Cloud Run Jobs updated"
|
||||
|
||||
- name: Verify deployment and version
|
||||
|
||||
@@ -40,6 +40,8 @@ class BulkArtist(BaseModel):
|
||||
disambiguation: str = ""
|
||||
type: Optional[str] = None
|
||||
country: Optional[str] = None
|
||||
# Set when only a MusicBrainz alias matched the query (e.g. "Hikaru Utada").
|
||||
alias: Optional[str] = None
|
||||
|
||||
|
||||
class BulkAlbum(BaseModel):
|
||||
@@ -258,6 +260,17 @@ class BulkSong(BaseModel):
|
||||
title: str = Field(..., min_length=1)
|
||||
display_artist: Optional[str] = None
|
||||
display_title: Optional[str] = None
|
||||
# Album mode: the track's number on its disc (album-search tie-break).
|
||||
position: Optional[int] = None
|
||||
|
||||
|
||||
class BulkAlbumRef(BaseModel):
|
||||
"""The album an album-mode batch was picked from. Lets the search worker find
|
||||
the album's torrent once instead of searching every track separately."""
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
release_group_mbid: Optional[str] = None
|
||||
release_mbid: Optional[str] = None
|
||||
|
||||
|
||||
class BulkSettings(BaseModel):
|
||||
@@ -274,6 +287,7 @@ class BulkSettings(BaseModel):
|
||||
class BulkSubmitRequest(BaseModel):
|
||||
songs: list[BulkSong]
|
||||
settings: BulkSettings = Field(default_factory=BulkSettings)
|
||||
album: Optional[BulkAlbumRef] = None
|
||||
|
||||
|
||||
class BulkSubmitResponse(BaseModel):
|
||||
@@ -337,6 +351,7 @@ async def bulk_submit(
|
||||
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
bulk_settings = body.settings.model_dump()
|
||||
bulk_album = body.album.model_dump() if body.album else None
|
||||
job_manager = JobManager()
|
||||
job_ids: list[str] = []
|
||||
|
||||
@@ -379,14 +394,15 @@ async def bulk_submit(
|
||||
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
|
||||
break
|
||||
|
||||
job_manager.update_job(
|
||||
job.job_id,
|
||||
{
|
||||
"state_data.batch_id": batch_id,
|
||||
"state_data.bulk_settings": bulk_settings,
|
||||
"state_data.bulk_pending_search": True,
|
||||
},
|
||||
)
|
||||
bulk_state = {
|
||||
"state_data.batch_id": batch_id,
|
||||
"state_data.bulk_settings": bulk_settings,
|
||||
"state_data.bulk_pending_search": True,
|
||||
}
|
||||
if bulk_album is not None:
|
||||
bulk_state["state_data.bulk_album"] = bulk_album
|
||||
bulk_state["state_data.bulk_track_position"] = song.position
|
||||
job_manager.update_job(job.job_id, bulk_state)
|
||||
job_ids.append(job.job_id)
|
||||
return batch_id, job_ids
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.routes.users import (
|
||||
@@ -39,6 +39,10 @@ from backend.api.routes.users import (
|
||||
)
|
||||
from backend.config import get_settings, is_production
|
||||
from backend.i18n import SUPPORTED_LOCALES, t
|
||||
from backend.services.account_deletion_service import (
|
||||
AccountDeletionService,
|
||||
get_account_deletion_service,
|
||||
)
|
||||
from backend.services.email_service import EmailService, get_email_service
|
||||
from backend.services.email_validation_service import get_email_validation_service
|
||||
from backend.services.kjbox_partner_service import (
|
||||
@@ -384,6 +388,34 @@ class ReviewLinkResponse(BaseModel):
|
||||
_REVIEW_LINK_STATUSES = ("awaiting_review", "in_review")
|
||||
|
||||
|
||||
# ------------------------------------------------- account deletion queue
|
||||
|
||||
@router.get("/account-deletions")
|
||||
def list_account_deletions(
|
||||
since: Optional[datetime] = Query(default=None),
|
||||
_secret: str = Depends(require_kjbox_partner),
|
||||
deletion: AccountDeletionService = Depends(get_account_deletion_service),
|
||||
):
|
||||
"""Deleted gen accounts the box still has to erase (it pulls: it may be offline).
|
||||
|
||||
Only the sha256 of the email is sent; the box hashes the ``gen_email`` values
|
||||
it stores to match. Lists entries still pending for kjbox, created after ``since``.
|
||||
"""
|
||||
return {"deletions": deletion.list_kjbox_pending(since)}
|
||||
|
||||
|
||||
@router.post("/account-deletions/{entry_id}/ack", status_code=204)
|
||||
def ack_account_deletion(
|
||||
entry_id: str,
|
||||
_secret: str = Depends(require_kjbox_partner),
|
||||
deletion: AccountDeletionService = Depends(get_account_deletion_service),
|
||||
):
|
||||
"""The box erased this account's data; stop listing it. ``entry_id`` = sha256(email)."""
|
||||
if not deletion.ack_kjbox(entry_id):
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/review-link", response_model=ReviewLinkResponse)
|
||||
async def review_link(
|
||||
job_id: str,
|
||||
|
||||
@@ -269,7 +269,17 @@ def verify_login_code(
|
||||
"""Exchange an emailed code for a session (same response as GET /auth/verify)."""
|
||||
email = _normalize_email(body.email)
|
||||
|
||||
outcome, record = store.verify_code(email, body.code)
|
||||
settings = get_settings()
|
||||
demo_email = (settings.app_review_demo_email or "").strip().lower()
|
||||
demo_code = settings.app_review_demo_code or ""
|
||||
if demo_email and demo_code and email == demo_email:
|
||||
# App Review demo account: reviewers can't receive email, so this one
|
||||
# address signs in with the fixed code. Attempt limits still apply.
|
||||
outcome, record = store.verify_fixed_code(email, body.code, demo_code)
|
||||
if outcome == VerifyOutcome.OK:
|
||||
logger.info("app review demo login")
|
||||
else:
|
||||
outcome, record = store.verify_code(email, body.code)
|
||||
if outcome == VerifyOutcome.TOO_MANY_ATTEMPTS:
|
||||
raise HTTPException(status_code=429, detail="too_many_attempts")
|
||||
if outcome == VerifyOutcome.INVALID:
|
||||
|
||||
@@ -5,19 +5,22 @@ Provides endpoints for managing Web Push notification subscriptions:
|
||||
- GET /api/push/vapid-public-key: Get VAPID public key for client-side subscription
|
||||
- POST /api/push/subscribe: Register a push subscription
|
||||
- POST /api/push/unsubscribe: Remove a push subscription
|
||||
- POST/DELETE /api/push/expo-token: Register/remove an Expo push token (mobile app)
|
||||
- GET /api/push/subscriptions: List user's subscriptions
|
||||
- POST /api/push/test: Send a test notification (admin only)
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional, Dict, List
|
||||
import asyncio
|
||||
from typing import Literal, Optional, Dict, List
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
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.services.expo_push_service import get_expo_push_service
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
|
||||
@@ -85,6 +88,17 @@ class TestNotificationResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
class ExpoTokenRequest(BaseModel):
|
||||
"""Register an Expo push token for one device of the mobile app."""
|
||||
token: str = Field(pattern=r"^Expo(nent)?PushToken\[[^\]\s]+\]$")
|
||||
platform: Literal["ios", "android"]
|
||||
device_id: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class ExpoTokenDeleteRequest(BaseModel):
|
||||
token: str
|
||||
|
||||
|
||||
# Routes
|
||||
|
||||
@router.get("/vapid-public-key", response_model=VapidPublicKeyResponse)
|
||||
@@ -201,6 +215,33 @@ async def unsubscribe_push(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/expo-token", status_code=204)
|
||||
async def register_expo_token(
|
||||
body: ExpoTokenRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Register this device's Expo token. Moves it off any other account that held it."""
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
await asyncio.to_thread(
|
||||
get_expo_push_service().register_token,
|
||||
auth_result.user_email, body.token, body.platform, body.device_id,
|
||||
)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.delete("/expo-token", status_code=204)
|
||||
async def delete_expo_token(
|
||||
body: ExpoTokenDeleteRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Remove one of the caller's Expo tokens (the app calls this before sign-out)."""
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
await asyncio.to_thread(get_expo_push_service().remove_tokens, auth_result.user_email, [body.token])
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get("/subscriptions", response_model=SubscriptionsListResponse)
|
||||
async def list_subscriptions(
|
||||
request: Request,
|
||||
|
||||
@@ -22,7 +22,7 @@ from backend.config import get_settings
|
||||
from backend.services import fake_workers
|
||||
from backend.services.fake_workers import checkout as fake_checkout
|
||||
from backend.services.fake_workers.config import clear_fake_config, get_fake_config, set_fake_config
|
||||
from backend.services.fake_workers.outbox import list_emails
|
||||
from backend.services.fake_workers.outbox import clear_pushes, list_emails, list_pushes
|
||||
from backend.services.fake_workers.scenarios import SCENARIOS, ScenarioError, run_scenario
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -73,6 +73,7 @@ def reset() -> Dict[str, Any]:
|
||||
blob.delete()
|
||||
deleted += 1
|
||||
clear_fake_config()
|
||||
clear_pushes()
|
||||
return {"status": "reset", "blobs_deleted": deleted}
|
||||
|
||||
|
||||
@@ -139,6 +140,18 @@ def emails(to: Optional[str] = None, limit: int = 20) -> Dict[str, Any]:
|
||||
return {"emails": list_emails(to, limit=limit)}
|
||||
|
||||
|
||||
@router.get("/push-outbox")
|
||||
def push_outbox(to: Optional[str] = None, limit: int = 50) -> Dict[str, Any]:
|
||||
"""Expo pushes captured instead of sent (newest first)."""
|
||||
return {"pushes": list_pushes(to, limit=limit)}
|
||||
|
||||
|
||||
@router.delete("/push-outbox")
|
||||
def clear_push_outbox() -> Dict[str, Any]:
|
||||
clear_pushes()
|
||||
return {"status": "cleared"}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ fake Stripe
|
||||
|
||||
_CHECKOUT_PAGE = """<!doctype html>
|
||||
@@ -203,3 +216,100 @@ def checkout_cancel(session_id: str):
|
||||
record = _checkout_or_404(session_id)
|
||||
fake_checkout.mark_checkout(session_id, "cancelled")
|
||||
return RedirectResponse(fake_checkout.resolve_url(record.get("cancel_url"), session_id), status_code=303)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ fake in-app purchases
|
||||
|
||||
|
||||
class FakeIapPurchaseRequest(BaseModel):
|
||||
"""A store purchase, as RevenueCat would report it. Give ``email`` or ``app_user_id``."""
|
||||
product_id: str
|
||||
email: Optional[str] = None
|
||||
app_user_id: Optional[str] = None
|
||||
transaction_id: Optional[str] = None
|
||||
store: str = "APP_STORE"
|
||||
price: Optional[float] = None
|
||||
takehome_percentage: Optional[float] = None
|
||||
country_code: str = "US"
|
||||
|
||||
|
||||
class FakeIapRefundRequest(BaseModel):
|
||||
"""Refunds debit the account the purchase granted, so no user is needed."""
|
||||
transaction_id: str
|
||||
product_id: str
|
||||
store: str = "APP_STORE"
|
||||
|
||||
|
||||
def _fake_app_user_id(email: Optional[str], app_user_id: Optional[str]) -> str:
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
if app_user_id:
|
||||
return app_user_id
|
||||
if not email:
|
||||
raise HTTPException(status_code=422, detail="email or app_user_id is required")
|
||||
user_service = get_user_service()
|
||||
user_service.get_or_create_user(email)
|
||||
return user_service.ensure_app_user_id(email)
|
||||
|
||||
|
||||
def _fake_iap_result(event: Dict[str, Any]) -> Dict[str, Any]:
|
||||
from backend.services.iap_service import get_iap_service
|
||||
|
||||
result = get_iap_service().handle_event(event)
|
||||
return {
|
||||
"action": result.action,
|
||||
"credits": result.credits,
|
||||
"store": event["store"],
|
||||
"transaction_id": event["transaction_id"],
|
||||
}
|
||||
|
||||
|
||||
# US store prices of the credit packs (spec: $9.99 / $23.99 / $34.99 / $59.99).
|
||||
_FAKE_IAP_PRICES = {
|
||||
"nomad_credits_1": 9.99,
|
||||
"nomad_credits_3": 23.99,
|
||||
"nomad_credits_5": 34.99,
|
||||
"nomad_credits_10": 59.99,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/fake-iap/purchase")
|
||||
def fake_iap_purchase(body: FakeIapPurchaseRequest) -> Dict[str, Any]:
|
||||
"""Grant a store credit pack through the same IapService as the RevenueCat webhook."""
|
||||
import uuid
|
||||
|
||||
price = body.price if body.price is not None else _FAKE_IAP_PRICES.get(body.product_id, 0.0)
|
||||
event: Dict[str, Any] = {
|
||||
"type": "NON_RENEWING_PURCHASE",
|
||||
"app_user_id": _fake_app_user_id(body.email, body.app_user_id),
|
||||
"product_id": body.product_id,
|
||||
"transaction_id": body.transaction_id or f"fake-{uuid.uuid4().hex}",
|
||||
"store": body.store,
|
||||
"price": price,
|
||||
"price_in_purchased_currency": price,
|
||||
"currency": "USD",
|
||||
"country_code": body.country_code,
|
||||
"environment": "SANDBOX",
|
||||
}
|
||||
if body.takehome_percentage is not None:
|
||||
event["takehome_percentage"] = body.takehome_percentage
|
||||
return _fake_iap_result(event)
|
||||
|
||||
|
||||
@router.post("/fake-iap/refund")
|
||||
def fake_iap_refund(body: FakeIapRefundRequest) -> Dict[str, Any]:
|
||||
"""Refund a fake store purchase (RevenueCat CANCELLATION / CUSTOMER_SUPPORT)."""
|
||||
price = -_FAKE_IAP_PRICES.get(body.product_id, 0.0)
|
||||
event: Dict[str, Any] = {
|
||||
"type": "CANCELLATION",
|
||||
"cancel_reason": "CUSTOMER_SUPPORT",
|
||||
"app_user_id": "",
|
||||
"product_id": body.product_id,
|
||||
"transaction_id": body.transaction_id,
|
||||
"store": body.store,
|
||||
"price": price,
|
||||
"price_in_purchased_currency": price,
|
||||
"currency": "USD",
|
||||
"environment": "SANDBOX",
|
||||
}
|
||||
return _fake_iap_result(event)
|
||||
+180
-5
@@ -10,6 +10,7 @@ Handles:
|
||||
"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import hmac
|
||||
import html
|
||||
import logging
|
||||
import re
|
||||
@@ -38,7 +39,7 @@ def _mask_email(email: str) -> str:
|
||||
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query, Request, Header
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
from backend.config import get_settings, is_production
|
||||
@@ -62,10 +63,20 @@ from backend.models.user import (
|
||||
UserFeedbackRequest,
|
||||
UserFeedbackResponse,
|
||||
FeedbackEligibilityResponse,
|
||||
effective_push_prefs,
|
||||
)
|
||||
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
|
||||
from backend.services.email_service import get_email_service, EmailService
|
||||
from backend.services.stripe_service import get_stripe_service, StripeService, CREDIT_PACKAGES
|
||||
from backend.services.iap_service import IapService, get_iap_service
|
||||
from backend.services.account_deletion_service import (
|
||||
AccountDeletionRefused,
|
||||
AccountDeletionService,
|
||||
AccountDeletionStepFailed,
|
||||
AccountNotFound,
|
||||
get_account_deletion_service,
|
||||
)
|
||||
from backend.services.login_code_store import TransactionContention
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.services.job_defaults_service import (
|
||||
get_effective_distribution_settings,
|
||||
@@ -179,17 +190,56 @@ class CreditPackage(BaseModel):
|
||||
price_cents: int
|
||||
name: str
|
||||
description: str
|
||||
store_product_id: Optional[str] = None # App Store / Play Store product id
|
||||
|
||||
|
||||
class WebLinkShowFor(BaseModel):
|
||||
"""Store countries (App Store / Play storefront codes) where the app may link to web checkout."""
|
||||
ios: list[str]
|
||||
android: list[str]
|
||||
|
||||
|
||||
class WebLink(BaseModel):
|
||||
"""Where the mobile app shows the "buy on the web" link, and its copy (app i18n key)."""
|
||||
show_for: WebLinkShowFor
|
||||
copy_key: str
|
||||
|
||||
|
||||
DEFAULT_WEB_LINK = {"show_for": {"ios": ["USA"], "android": []}, "copy_key": "credits.webLink.default"}
|
||||
|
||||
|
||||
class CreditPackagesResponse(BaseModel):
|
||||
"""Response listing available credit packages."""
|
||||
packages: list[CreditPackage]
|
||||
web_link: WebLink = WebLink(**DEFAULT_WEB_LINK)
|
||||
|
||||
|
||||
class UserCapabilities(BaseModel):
|
||||
"""Server-side feature switches the mobile app reads from /me."""
|
||||
account_deletion: bool = False
|
||||
|
||||
|
||||
class PushPrefs(BaseModel):
|
||||
"""Mobile push categories; all default on."""
|
||||
ready: bool = True
|
||||
review: bool = True
|
||||
problems: bool = True
|
||||
|
||||
|
||||
class PushPrefsUpdate(BaseModel):
|
||||
"""Partial update of mobile push categories; omitted keys are unchanged."""
|
||||
ready: Optional[bool] = None
|
||||
review: Optional[bool] = None
|
||||
problems: Optional[bool] = None
|
||||
|
||||
|
||||
class UserProfileResponse(BaseModel):
|
||||
"""Response with user profile."""
|
||||
user: UserPublic
|
||||
has_session: bool
|
||||
app_user_id: Optional[str] = None
|
||||
capabilities: UserCapabilities = UserCapabilities()
|
||||
push_prefs: PushPrefs = PushPrefs()
|
||||
|
||||
|
||||
class LogoutResponse(BaseModel):
|
||||
@@ -901,6 +951,93 @@ def logout(
|
||||
# User Profile
|
||||
# =============================================================================
|
||||
|
||||
def _app_user_id(user, user_service) -> Optional[str]:
|
||||
"""The stored mobile-app id, else mint one. A minting failure never fails /me."""
|
||||
existing = getattr(user, "app_user_id", None)
|
||||
if existing:
|
||||
return existing
|
||||
try:
|
||||
return user_service.ensure_app_user_id(user.email)
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not mint app_user_id for {_mask_email(user.email)}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def _profile_response(user, user_public, user_service) -> UserProfileResponse:
|
||||
"""Wrap UserPublic with the mobile-app fields (app_user_id, capabilities, push_prefs)."""
|
||||
stored = getattr(user, "push_prefs", None) or {}
|
||||
return UserProfileResponse(
|
||||
user=user_public,
|
||||
has_session=True,
|
||||
app_user_id=_app_user_id(user, user_service),
|
||||
capabilities=UserCapabilities(account_deletion=get_settings().account_deletion_enabled),
|
||||
push_prefs=PushPrefs(**effective_push_prefs(stored)),
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/me/push-prefs", response_model=PushPrefs)
|
||||
def update_push_prefs(
|
||||
update: PushPrefsUpdate,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""Set per-type push preferences (gen Expo and Web Push both honour them)."""
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
user = user_service.get_or_create_user(auth_result.user_email)
|
||||
merged = effective_push_prefs(getattr(user, "push_prefs", None))
|
||||
merged.update(update.model_dump(exclude_none=True))
|
||||
if user_service.update_user(auth_result.user_email, push_prefs=merged) is None:
|
||||
raise HTTPException(status_code=500, detail="Could not save push preferences")
|
||||
return PushPrefs(**merged)
|
||||
|
||||
|
||||
class DeleteAccountRequest(BaseModel):
|
||||
# iOS: a fresh Sign in with Apple authorization code, so gen can revoke the token
|
||||
apple_authorization_code: Optional[str] = None
|
||||
|
||||
|
||||
def _require_account_deletion(auth_result: AuthResult) -> str:
|
||||
if not get_settings().account_deletion_enabled:
|
||||
raise HTTPException(status_code=404, detail="Not Found")
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
return auth_result.user_email
|
||||
|
||||
|
||||
@router.get("/me/deletion-preview")
|
||||
def account_deletion_preview(
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
deletion: AccountDeletionService = Depends(get_account_deletion_service),
|
||||
):
|
||||
"""What deleting the account would cost: credits lost, videos cancelled, or a 409 reason."""
|
||||
email = _require_account_deletion(auth_result)
|
||||
try:
|
||||
return deletion.preview(email, is_admin=auth_result.is_admin)
|
||||
except AccountNotFound:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
|
||||
@router.delete("/me")
|
||||
def delete_my_account(
|
||||
body: Optional[DeleteAccountRequest] = None,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
deletion: AccountDeletionService = Depends(get_account_deletion_service),
|
||||
):
|
||||
"""Self-serve account deletion (App Store 5.1.1(v), Google Play). 503 = retry."""
|
||||
email = _require_account_deletion(auth_result)
|
||||
apple_code = body.apple_authorization_code if body else None
|
||||
try:
|
||||
summary = deletion.delete(email, apple_code=apple_code, is_admin=auth_result.is_admin)
|
||||
except AccountNotFound:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
except AccountDeletionRefused as e:
|
||||
return JSONResponse(status_code=409, content={"code": e.code})
|
||||
except AccountDeletionStepFailed as e:
|
||||
return JSONResponse(status_code=503, content={"step": e.step})
|
||||
return {"deleted": True, "summary": summary}
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserProfileResponse)
|
||||
def get_current_user(
|
||||
request: Request,
|
||||
@@ -937,7 +1074,7 @@ def get_current_user(
|
||||
role_override=UserRole.ADMIN if auth_result.is_admin else None,
|
||||
feedback_eligible=feedback_eligible,
|
||||
)
|
||||
return UserProfileResponse(user=user_public, has_session=True)
|
||||
return _profile_response(user, user_public, user_service)
|
||||
|
||||
# Fall back to session validation (for magic link sessions)
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
@@ -951,7 +1088,7 @@ def get_current_user(
|
||||
)
|
||||
user_public = _build_user_public(user, feedback_eligible=feedback_eligible)
|
||||
|
||||
return UserProfileResponse(user=user_public, has_session=True)
|
||||
return _profile_response(user, user_public, user_service)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -972,11 +1109,12 @@ def list_credit_packages():
|
||||
price_cents=pkg["price_cents"],
|
||||
name=pkg["name"],
|
||||
description=pkg["description"],
|
||||
store_product_id=pkg.get("store_product_id"),
|
||||
)
|
||||
for pkg_id, pkg in CREDIT_PACKAGES.items()
|
||||
]
|
||||
|
||||
return CreditPackagesResponse(packages=packages)
|
||||
return CreditPackagesResponse(packages=packages, web_link=WebLink(**DEFAULT_WEB_LINK))
|
||||
|
||||
|
||||
def public_api_base_url() -> str:
|
||||
@@ -1681,7 +1819,7 @@ async def stripe_webhook(
|
||||
if amount_charged > 0:
|
||||
earning_result = referral_svc.record_earning(
|
||||
referred_email=user_email,
|
||||
stripe_session_id=session_id,
|
||||
source_key=session_id,
|
||||
purchase_amount_cents=amount_charged,
|
||||
)
|
||||
if earning_result:
|
||||
@@ -1829,6 +1967,43 @@ async def stripe_webhook(
|
||||
return {"status": "received", "type": event_type}
|
||||
|
||||
|
||||
@router.post("/webhooks/revenuecat")
|
||||
async def revenuecat_webhook(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
iap: IapService = Depends(get_iap_service),
|
||||
):
|
||||
"""RevenueCat events for mobile in-app credit packs (see backend/services/iap_service.py).
|
||||
|
||||
Authenticated by the Authorization header configured in the RevenueCat
|
||||
dashboard (REVENUECAT_WEBHOOK_AUTH; 503 while unset). Every handled outcome,
|
||||
including duplicates and unmatched users, is a 200 so RevenueCat stops
|
||||
retrying; a Firestore failure is a 5xx so it retries.
|
||||
"""
|
||||
secret = get_settings().revenuecat_webhook_auth
|
||||
if not secret:
|
||||
raise HTTPException(status_code=503, detail="not configured")
|
||||
if not hmac.compare_digest((authorization or "").encode(), secret.encode()):
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
body = await request.json()
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid JSON")
|
||||
event = body.get("event") if isinstance(body, dict) else None
|
||||
if not isinstance(event, dict):
|
||||
raise HTTPException(status_code=400, detail="missing event")
|
||||
|
||||
try:
|
||||
result = await asyncio.to_thread(iap.handle_event, event)
|
||||
except TransactionContention:
|
||||
raise HTTPException(status_code=503, detail="busy, retry")
|
||||
logger.info(
|
||||
f"RevenueCat webhook {event.get('type')} {event.get('store')}:{event.get('transaction_id')} "
|
||||
f"-> {result.action}"
|
||||
)
|
||||
return {"status": "received", "action": result.action}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# User Feedback-for-Credits Endpoints
|
||||
# =============================================================================
|
||||
|
||||
+28
-3
@@ -270,7 +270,8 @@ class Settings(BaseSettings):
|
||||
# Requires use_gce_encoding to be enabled and the GCE worker to support /encode-preview endpoint.
|
||||
use_gce_preview_encoding: bool = os.getenv("USE_GCE_PREVIEW_ENCODING", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
# Karaoke-Decide catalog API (for song/artist autocomplete)
|
||||
# Karaoke-Decide main API: catalog autocomplete, and the partner call that
|
||||
# erases a deleted account's decide data (DELETE /api/partner/gen/users)
|
||||
karaoke_decide_api_url: str = os.getenv("KARAOKE_DECIDE_API_URL", "https://decide.nomadkaraoke.com")
|
||||
|
||||
# Storage paths
|
||||
@@ -342,8 +343,10 @@ class Settings(BaseSettings):
|
||||
# for the karaoke-night "make it" flow. Every endpoint 503s while the secret is
|
||||
# empty, so deploys are dark until it's wired (Secret Manager: kjbox-partner-secret).
|
||||
kjbox_partner_secret: str = os.getenv("KJBOX_PARTNER_SECRET", "")
|
||||
# karaoke-decide's own secret (header X-Partner-Secret) for POST /api/kjbox/catalog/resolve
|
||||
# only (Secret Manager: decide-gen-partner-secret). Empty = decide is not accepted.
|
||||
# karaoke-decide's shared secret (header X-Partner-Secret, Secret Manager:
|
||||
# decide-gen-partner-secret): decide sends it to POST /api/kjbox/catalog/resolve, and
|
||||
# gen sends it to decide's DELETE /api/partner/gen/users on account deletion.
|
||||
# Empty = decide is not accepted, and account deletion 503s at the decide step.
|
||||
decide_partner_secret: str = os.getenv("DECIDE_GEN_PARTNER_SECRET", "")
|
||||
# Partner-wide cap on NEW gen accounts created via kjbox per rolling 24h (a venue
|
||||
# shares one IP, so gen's per-IP signup cap is bypassed for kjbox; this bounds it).
|
||||
@@ -393,6 +396,21 @@ class Settings(BaseSettings):
|
||||
# ip-api, encoding VM) are skipped. Startup refuses it in production.
|
||||
# See backend/services/fake_workers/ and docs/TESTING.md § Local stack.
|
||||
fake_workers: bool = os.getenv("FAKE_WORKERS", "").lower() in ("1", "true", "yes")
|
||||
# Mobile app account deletion (DELETE /api/users/me). Off in prod until
|
||||
# Andrew's manual pass; on in the local stack.
|
||||
account_deletion_enabled: bool = os.getenv("ACCOUNT_DELETION_ENABLED", "").lower() in ("1", "true", "yes")
|
||||
# App Review demo login: inert unless this AND the app-review-demo-code secret are set.
|
||||
app_review_demo_email: str = os.getenv("APP_REVIEW_DEMO_EMAIL", "")
|
||||
# Secret Manager: app-review-demo-code, mounted as APP_REVIEW_DEMO_CODE.
|
||||
app_review_demo_code: str = os.getenv("APP_REVIEW_DEMO_CODE", "")
|
||||
# RevenueCat (mobile in-app credit packs). The webhook (POST
|
||||
# /api/users/webhooks/revenuecat) compares the Authorization header to this
|
||||
# value and 503s while it is empty (Secret Manager: revenuecat-webhook-auth).
|
||||
revenuecat_webhook_auth: str = os.getenv("REVENUECAT_WEBHOOK_AUTH", "")
|
||||
# RevenueCat secret REST API key (Secret Manager: revenuecat-secret-api-key).
|
||||
revenuecat_secret_api_key: str = os.getenv("REVENUECAT_SECRET_API_KEY", "")
|
||||
# RevenueCat project the v2 key belongs to (account deletion's customer delete).
|
||||
revenuecat_project_id: str = os.getenv("REVENUECAT_PROJECT_ID", "9ea947ce")
|
||||
# URL scheme of the Nomad Karaoke mobile app. App checkouts return through
|
||||
# GET /api/users/credits/app-return, which 302s to {scheme}://checkout?status=…
|
||||
mobile_app_scheme: str = os.getenv("MOBILE_APP_SCHEME", "nomadkaraoke")
|
||||
@@ -410,6 +428,13 @@ class Settings(BaseSettings):
|
||||
# Accepted `aud` values for Apple ID tokens (POST /api/users/auth/apple):
|
||||
# the app's bundle ID (native iOS), plus any Services ID used for web/Android.
|
||||
apple_signin_audiences: str = os.getenv("APPLE_SIGNIN_AUDIENCES", "com.nomadkaraoke.mobile")
|
||||
|
||||
# Sign in with Apple token revocation (account deletion). The .p8 PEM text
|
||||
# and key id come from Secret Manager; unset => revocation is skipped.
|
||||
apple_siwa_key_p8: Optional[str] = os.getenv("APPLE_SIWA_KEY_P8")
|
||||
apple_siwa_key_id: Optional[str] = os.getenv("APPLE_SIWA_KEY_ID")
|
||||
apple_team_id: str = os.getenv("APPLE_TEAM_ID", "55B76HN73D")
|
||||
apple_client_id: str = os.getenv("APPLE_CLIENT_ID", "com.nomadkaraoke.mobile")
|
||||
# Canonical YouTube description template. Placeholders ({title}, {artist},
|
||||
# {artist_hashtag}, {brand_code}) are filled by
|
||||
# backend.services.youtube_description.render_youtube_description, which is the
|
||||
|
||||
@@ -8,7 +8,7 @@ Supports:
|
||||
- API request/response shapes for referral endpoints
|
||||
"""
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from typing import Literal, Optional, List
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
@@ -79,13 +79,16 @@ class ReferralEarning(BaseModel):
|
||||
"""
|
||||
Record of a single earning from a referred purchase.
|
||||
|
||||
Created when a referred user completes a Stripe checkout.
|
||||
Created when a referred user completes a Stripe checkout or an in-app
|
||||
(App Store / Play Store) credit purchase.
|
||||
"""
|
||||
id: str
|
||||
referrer_email: str
|
||||
referred_email: str
|
||||
referral_code: str
|
||||
stripe_session_id: str
|
||||
source: Literal["stripe", "app_store", "play_store"] = "stripe"
|
||||
stripe_session_id: Optional[str] = None # Stripe rows
|
||||
store_transaction_id: Optional[str] = None # store rows: "{STORE}:{transaction_id}"
|
||||
purchase_amount_cents: int
|
||||
earning_amount_cents: int
|
||||
status: str = "pending" # pending, paid, cancelled
|
||||
|
||||
+27
-1
@@ -9,7 +9,7 @@ Supports:
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
from typing import Annotated, Optional, List, Dict
|
||||
from typing import Annotated, Literal, Optional, List, Dict
|
||||
from pydantic import BaseModel, EmailStr, Field, StringConstraints
|
||||
|
||||
|
||||
@@ -49,6 +49,24 @@ class PushSubscription(BaseModel):
|
||||
last_used_at: Optional[datetime] = None # Last time a notification was sent
|
||||
|
||||
|
||||
PUSH_PREF_KINDS = ("ready", "review", "problems")
|
||||
|
||||
|
||||
def effective_push_prefs(stored: Optional[Dict[str, bool]]) -> Dict[str, bool]:
|
||||
"""Per-type mobile push preferences with defaults applied (all on unless stored False)."""
|
||||
stored = stored or {}
|
||||
return {kind: bool(stored.get(kind, True)) for kind in PUSH_PREF_KINDS}
|
||||
|
||||
|
||||
class ExpoPushToken(BaseModel):
|
||||
"""Expo push token for one device of the Nomad Karaoke mobile app."""
|
||||
token: str
|
||||
platform: Literal["ios", "android"]
|
||||
device_id: str
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_used_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
"""
|
||||
User model stored in Firestore.
|
||||
@@ -105,6 +123,14 @@ class User(BaseModel):
|
||||
# Users can subscribe from multiple devices/browsers
|
||||
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
|
||||
|
||||
# Mobile app: opaque UUID4 sent to RevenueCat (never the email), minted once
|
||||
# by UserService.ensure_app_user_id
|
||||
app_user_id: Optional[str] = None
|
||||
# Mobile push categories ("ready", "review", "problems"); missing key = on
|
||||
push_prefs: Dict[str, bool] = Field(default_factory=dict)
|
||||
# Expo push tokens, one per signed-in device (a token belongs to one user)
|
||||
expo_push_tokens: List[ExpoPushToken] = Field(default_factory=list)
|
||||
|
||||
# Feedback-for-credits program
|
||||
has_submitted_feedback: bool = False
|
||||
|
||||
|
||||
@@ -0,0 +1,720 @@
|
||||
"""Self-serve account deletion (``DELETE /api/users/me``) and the kjbox deletion queue.
|
||||
|
||||
App Store 5.1.1(v) and Google Play require in-app account deletion. Steps run in
|
||||
a fixed order, each idempotent, and any failure stops the run so the client
|
||||
retries (503 with the step name):
|
||||
|
||||
1. preconditions: refuse (409) admins and accounts that carry money or work
|
||||
(a Firestore failure here is a 503 ``preconditions``)
|
||||
2. cancel the user's active jobs (no refund: unused credits are forfeited)
|
||||
3. decide: erase the user's decide data (partner API)
|
||||
4. RevenueCat: delete the v2 customer ``app_user_id`` (skipped without a key)
|
||||
5. Apple: revoke Sign in with Apple when the app sent an authorization code
|
||||
(best-effort: a failed revoke is a WARNING, never a 503)
|
||||
6. kjbox: enqueue ``account_deletions/{sha256(email)}`` for the box to pull
|
||||
7. gen inputs + personal data in jobs: delete ``uploads/{id}/**`` and
|
||||
``jobs/{id}/input/**``, revoke the customer's Dropbox share link, strip
|
||||
names/emails/IPs from the job doc and set ``user_email = "deleted:{uuid}"``.
|
||||
Published outputs (stems, renders, MP4s, the Dropbox folder, YouTube) are
|
||||
NEVER deleted.
|
||||
8. gen records: ``deleted_users/{uuid}`` (no email/name, only ``email_sha256``),
|
||||
delete magic links, login codes and email_log entries sent to the user (and
|
||||
drop the address from other entries' cc/bcc); anonymise records kept for
|
||||
accounting/history (kjbox show credits, the referral link (disabled), vanity
|
||||
requests, referral earnings, credit evaluations (signup IP/fingerprint
|
||||
removed), IAP purchase/refund markers, song requests and votes); delete
|
||||
sessions, then ``gen_users/{email}``
|
||||
|
||||
Sessions go last so a run that fails part-way leaves the user signed in to retry.
|
||||
The ``deletion_id`` (UUID4) is minted on the first attempt and stored on the user
|
||||
doc, so every retry reuses it. After the final step decide is called a second
|
||||
time (best-effort) to catch a decide profile a still-valid token recreated
|
||||
mid-deletion.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
from google.api_core import exceptions as google_exceptions
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, FieldFilter
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.decide_partner_client import DecidePartnerClient, DecidePartnerError
|
||||
from backend.services.kjbox_partner_service import (
|
||||
LOGIN_CODES_COLLECTION as KJBOX_LOGIN_CODES_COLLECTION,
|
||||
SHOW_CREDIT_USERS_COLLECTION,
|
||||
SHOW_CREDITS_COLLECTION,
|
||||
SIGNUPS_COLLECTION as KJBOX_SIGNUPS_COLLECTION,
|
||||
)
|
||||
from backend.services.login_code_store import TransactionContention, code_doc_id, run_firestore_transaction
|
||||
from backend.services.referral_service import (
|
||||
REFERRAL_EARNINGS_COLLECTION,
|
||||
REFERRAL_LINKS_COLLECTION,
|
||||
REFERRAL_VANITY_REQUESTS_COLLECTION,
|
||||
)
|
||||
from backend.services.user_service import (
|
||||
MAGIC_LINKS_COLLECTION,
|
||||
SESSIONS_COLLECTION,
|
||||
USERS_COLLECTION,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ACCOUNT_DELETIONS_COLLECTION = "account_deletions"
|
||||
DELETED_USERS_COLLECTION = "deleted_users"
|
||||
GEN_LOGIN_CODES_COLLECTION = "login_codes" # backend/api/routes/login_code.py
|
||||
# Owned by modules too heavy to import here (tests guard these against drift):
|
||||
CREDIT_EVALUATIONS_COLLECTION = "credit_evaluations" # credit_evaluation_service
|
||||
SONG_REQUESTS_COLLECTION = "song_requests" # song_request_service.REQUESTS_COLLECTION
|
||||
SONG_REQUEST_VOTES_COLLECTION = "song_request_votes" # song_request_service.VOTES_COLLECTION
|
||||
EMAIL_LOG_COLLECTION = "email_log" # postmark_admin_service / email_service
|
||||
PROCESSED_IAP_TRANSACTIONS_COLLECTION = "processed_revenuecat_transactions" # iap_service
|
||||
|
||||
# API v2 (the stored key is a project-scoped v2 secret key). Deletion is queued by RevenueCat.
|
||||
REVENUECAT_CUSTOMER_URL = "https://api.revenuecat.com/v2/projects/{project_id}/customers/{customer_id}"
|
||||
_HTTP_TIMEOUT_SECONDS = 20
|
||||
|
||||
# Job statuses that are finished; everything else counts as "in progress".
|
||||
TERMINAL_STATUSES = frozenset({"complete", "prep_complete", "failed", "cancelled", "error"})
|
||||
# GCS prefixes that hold only what the user supplied (or edits of it), never outputs:
|
||||
# - uploads/{id}/ signed-URL / multipart uploads, downloaded source audio, lyrics files
|
||||
# - jobs/{id}/input/ the persisted copy of uploads/ (backend/services/input_persistence.py)
|
||||
# - jobs/{id}/uploads/ a custom instrumental uploaded in review (routes/jobs.py
|
||||
# _instrumental_source_prefix); its output stems/custom_instrumental.flac stays
|
||||
# - jobs/{id}/audio_edit/ audio-edit uploads (upload_*), edited input mixes (edit_*), edit log, waveform
|
||||
# - jobs/{id}/style/ style params and the user's uploaded backgrounds / font
|
||||
INPUT_PREFIXES = (
|
||||
"uploads/{job_id}/",
|
||||
"jobs/{job_id}/input/",
|
||||
"jobs/{job_id}/uploads/",
|
||||
"jobs/{job_id}/audio_edit/",
|
||||
"jobs/{job_id}/style/",
|
||||
)
|
||||
# Job-root copies of the user's own instrumental (backend/utils/existing_instrumental.py).
|
||||
STAGED_INSTRUMENTAL_STEMS = ("custom_instrumental", "existing_instrumental")
|
||||
# Personal keys inside a job's state_data (names, emails, notification addresses).
|
||||
PERSONAL_STATE_KEYS = ("customer_email", "customer_name", "notification_email", "display_name")
|
||||
|
||||
# 409 reason codes (the app and web show "Contact support to close this account").
|
||||
REFUSAL_CODES = ("admin", "referral_balance", "connect_account", "order_in_progress")
|
||||
|
||||
|
||||
def email_sha256(email: str) -> str:
|
||||
return hashlib.sha256(email.strip().lower().encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def deleted_owner(deletion_id: str) -> str:
|
||||
return f"deleted:{deletion_id}"
|
||||
|
||||
|
||||
class AccountNotFound(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AccountDeletionRefused(Exception):
|
||||
def __init__(self, code: str):
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
|
||||
|
||||
class AccountDeletionStepFailed(Exception):
|
||||
def __init__(self, step: str):
|
||||
super().__init__(step)
|
||||
self.step = step
|
||||
|
||||
|
||||
class RevenueCatError(RuntimeError):
|
||||
"""RevenueCat answered non-2xx (other than 404)."""
|
||||
|
||||
|
||||
def _is_retryable(exc: BaseException) -> bool:
|
||||
"""A transient remote/platform failure the client's retry is expected to clear."""
|
||||
if isinstance(exc, (DecidePartnerError, RevenueCatError, httpx.HTTPError, TransactionContention)):
|
||||
return True
|
||||
if isinstance(exc, (
|
||||
google_exceptions.ServerError, # 5xx incl. ServiceUnavailable, DeadlineExceeded
|
||||
google_exceptions.TooManyRequests,
|
||||
google_exceptions.Aborted,
|
||||
)):
|
||||
return True
|
||||
# Dropbox SDK transient errors (imported lazily: the SDK is optional at import time)
|
||||
return type(exc).__name__ in ("InternalServerError", "RateLimitError") and type(exc).__module__.startswith("dropbox")
|
||||
|
||||
|
||||
def _log_step_failure(deletion_id: str, step: str, exc: BaseException) -> None:
|
||||
"""#alerts rule: a retryable failure is a WARNING (the client retries on 503);
|
||||
anything unexpected is an ERROR, once per request, naming the step."""
|
||||
if _is_retryable(exc):
|
||||
logger.warning(
|
||||
"Account deletion %s: step %s failed (%s: %s); client will retry",
|
||||
deletion_id, step, type(exc).__name__, exc,
|
||||
)
|
||||
else:
|
||||
logger.exception("Account deletion %s failed at step %s; client will retry", deletion_id, step)
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _iso(value: Any) -> Optional[str]:
|
||||
if isinstance(value, datetime):
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.isoformat()
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
def _aware(value: Any) -> Optional[datetime]:
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
return None
|
||||
|
||||
|
||||
def _default_apple_revoke(code: str) -> bool:
|
||||
from backend.services.apple_revoke_service import AppleRevoker
|
||||
|
||||
# Called from a sync (threadpool) route handler, so there is no running loop.
|
||||
return asyncio.run(AppleRevoker().revoke(code))
|
||||
|
||||
|
||||
def _default_cancel_job(job_id: str) -> bool:
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
return JobManager().cancel_job(job_id, reason="account deleted", refund=False)
|
||||
|
||||
|
||||
class AccountDeletionService:
|
||||
def __init__(
|
||||
self,
|
||||
db,
|
||||
*,
|
||||
jobs_collection: Optional[str] = None,
|
||||
cancel_job: Optional[Callable[[str], bool]] = None,
|
||||
bucket=None,
|
||||
dropbox=None,
|
||||
decide: Optional[DecidePartnerClient] = None,
|
||||
http_client=None,
|
||||
apple_revoke: Optional[Callable[[str], bool]] = None,
|
||||
transaction_runner: Optional[Callable] = None,
|
||||
settings=None,
|
||||
):
|
||||
self.db = db
|
||||
self.settings = settings or get_settings()
|
||||
self.jobs_collection = jobs_collection or self.settings.firestore_collection
|
||||
self._cancel_job = cancel_job or _default_cancel_job
|
||||
self._bucket = bucket
|
||||
self._dropbox = dropbox
|
||||
self._decide = decide
|
||||
self._http_client = http_client # injectable httpx.Client (RevenueCat)
|
||||
self._apple_revoke = apple_revoke or _default_apple_revoke
|
||||
self._transaction_runner = transaction_runner
|
||||
|
||||
# ------------------------------------------------------------ lazy deps
|
||||
|
||||
@property
|
||||
def bucket(self):
|
||||
if self._bucket is None:
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
self._bucket = StorageService().bucket
|
||||
return self._bucket
|
||||
|
||||
@property
|
||||
def dropbox(self):
|
||||
if self._dropbox is None:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
self._dropbox = get_dropbox_service()
|
||||
return self._dropbox
|
||||
|
||||
@property
|
||||
def decide(self) -> DecidePartnerClient:
|
||||
if self._decide is None:
|
||||
self._decide = DecidePartnerClient()
|
||||
return self._decide
|
||||
|
||||
def _run_transaction(self, fn):
|
||||
if self._transaction_runner is not None:
|
||||
return self._transaction_runner(fn)
|
||||
return run_firestore_transaction(self.db, fn)
|
||||
|
||||
# ------------------------------------------------------------- queries
|
||||
|
||||
def _jobs(self):
|
||||
return self.db.collection(self.jobs_collection)
|
||||
|
||||
def _owned_jobs(self, email: str) -> List[Any]:
|
||||
return list(self._jobs().where(filter=FieldFilter("user_email", "==", email)).stream())
|
||||
|
||||
def _customer_jobs(self, email: str) -> List[Any]:
|
||||
"""Made-for-you orders: owned by the admin, delivered to ``customer_email``."""
|
||||
return list(
|
||||
self._jobs()
|
||||
.where(filter=FieldFilter("customer_email", "==", email))
|
||||
.where(filter=FieldFilter("made_for_you", "==", True))
|
||||
.stream()
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _is_active(job: dict) -> bool:
|
||||
return str(job.get("status") or "").lower() not in TERMINAL_STATUSES
|
||||
|
||||
def _any(self, query) -> bool:
|
||||
return any(True for _ in query.limit(1).stream())
|
||||
|
||||
# ------------------------------------------------------- preconditions
|
||||
|
||||
def refusal_code(self, email: str, user: dict, is_admin: bool = False) -> Optional[str]:
|
||||
"""The 409 reason this account can't self-delete, or None."""
|
||||
if is_admin or str(user.get("role") or "").lower() == "admin":
|
||||
return "admin"
|
||||
pending_earnings = (
|
||||
self.db.collection(REFERRAL_EARNINGS_COLLECTION)
|
||||
.where(filter=FieldFilter("referrer_email", "==", email))
|
||||
.where(filter=FieldFilter("status", "==", "pending"))
|
||||
)
|
||||
if self._any(pending_earnings):
|
||||
return "referral_balance"
|
||||
if user.get("stripe_connect_account_id"):
|
||||
return "connect_account"
|
||||
if any(self._is_active(snap.to_dict() or {}) for snap in self._customer_jobs(email)):
|
||||
return "order_in_progress"
|
||||
return None
|
||||
|
||||
def _user_ref(self, email: str):
|
||||
"""The user's doc: keyed by email, or (older docs) by hash with an ``email`` field."""
|
||||
users = self.db.collection(USERS_COLLECTION)
|
||||
ref = users.document(email)
|
||||
if ref.get().exists:
|
||||
return ref
|
||||
for snap in users.where(filter=FieldFilter("email", "==", email)).limit(1).stream():
|
||||
return snap.reference
|
||||
raise AccountNotFound(email)
|
||||
|
||||
def _load_user(self, email: str) -> dict:
|
||||
return self._user_ref(email).get().to_dict() or {}
|
||||
|
||||
def preview(self, email: str, is_admin: bool = False) -> dict:
|
||||
email = email.strip().lower()
|
||||
user = self._load_user(email)
|
||||
in_progress = sum(1 for snap in self._owned_jobs(email) if self._is_active(snap.to_dict() or {}))
|
||||
return {
|
||||
"credits": max(int(user.get("credits") or 0), 0),
|
||||
"jobs_in_progress": in_progress,
|
||||
"blocked": self.refusal_code(email, user, is_admin=is_admin),
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------- delete
|
||||
|
||||
def delete(self, email: str, apple_code: Optional[str] = None, is_admin: bool = False) -> dict:
|
||||
"""Run every deletion step. Raises AccountNotFound / AccountDeletionRefused /
|
||||
AccountDeletionStepFailed; returns a per-step summary on success."""
|
||||
email = email.strip().lower()
|
||||
try:
|
||||
user = self._load_user(email)
|
||||
code = self.refusal_code(email, user, is_admin=is_admin)
|
||||
if code:
|
||||
logger.info("Account deletion refused (%s)", code)
|
||||
raise AccountDeletionRefused(code)
|
||||
deletion_id = self._ensure_deletion_id(email)
|
||||
except (AccountNotFound, AccountDeletionRefused):
|
||||
raise
|
||||
except Exception as e:
|
||||
_log_step_failure("-", "preconditions", e)
|
||||
raise AccountDeletionStepFailed("preconditions")
|
||||
|
||||
summary: Dict[str, Any] = {"deletion_id": deletion_id}
|
||||
steps = (
|
||||
("jobs", lambda: self._cancel_active_jobs(email)),
|
||||
("decide", lambda: self.decide.delete_user(email).get("deleted", {})),
|
||||
("revenuecat", lambda: self._delete_revenuecat(user.get("app_user_id"))),
|
||||
("apple", lambda: self._revoke_apple(apple_code)),
|
||||
("kjbox", lambda: self._enqueue_kjbox(email, deletion_id)),
|
||||
("files", lambda: self._scrub_jobs(email, deletion_id)),
|
||||
("records", lambda: self._delete_records(email, deletion_id)),
|
||||
)
|
||||
for step, run in steps:
|
||||
try:
|
||||
summary[step] = run()
|
||||
except Exception as e:
|
||||
_log_step_failure(deletion_id, step, e)
|
||||
raise AccountDeletionStepFailed(step)
|
||||
|
||||
# A token that was still valid mid-run could have recreated a decide profile.
|
||||
try:
|
||||
self.decide.delete_user(email)
|
||||
except Exception as e:
|
||||
logger.warning("Account deletion %s: second decide delete failed (%s)", deletion_id, e)
|
||||
|
||||
logger.info("Account deletion %s complete: %s", deletion_id, summary)
|
||||
return summary
|
||||
|
||||
def _ensure_deletion_id(self, email: str) -> str:
|
||||
ref = self._user_ref(email)
|
||||
|
||||
def txn(transaction):
|
||||
snap = ref.get(transaction=transaction)
|
||||
existing = (snap.to_dict() or {}).get("deletion_id")
|
||||
if existing:
|
||||
return existing
|
||||
new_id = str(uuid.uuid4())
|
||||
transaction.update(ref, {"deletion_id": new_id, "deletion_started_at": _now()})
|
||||
return new_id
|
||||
|
||||
return self._run_transaction(txn)
|
||||
|
||||
# Step 2
|
||||
def _cancel_active_jobs(self, email: str) -> int:
|
||||
cancelled = 0
|
||||
for snap in self._owned_jobs(email):
|
||||
if self._is_active(snap.to_dict() or {}) and self._cancel_job(snap.id):
|
||||
cancelled += 1
|
||||
return cancelled
|
||||
|
||||
# Step 4
|
||||
def _delete_revenuecat(self, app_user_id: Optional[str]) -> str:
|
||||
key = getattr(self.settings, "revenuecat_secret_api_key", "")
|
||||
if not key:
|
||||
logger.info("Account deletion: RevenueCat skipped (REVENUECAT_SECRET_API_KEY not set)")
|
||||
return "skipped"
|
||||
if not app_user_id:
|
||||
return "no_app_user"
|
||||
project_id = getattr(self.settings, "revenuecat_project_id", "") or "9ea947ce"
|
||||
url = REVENUECAT_CUSTOMER_URL.format(
|
||||
project_id=quote(project_id, safe=""), customer_id=quote(app_user_id, safe=""))
|
||||
headers = {"Authorization": f"Bearer {key}"}
|
||||
if self._http_client is not None:
|
||||
resp = self._http_client.request("DELETE", url, headers=headers)
|
||||
else:
|
||||
with httpx.Client(timeout=_HTTP_TIMEOUT_SECONDS) as client:
|
||||
resp = client.request("DELETE", url, headers=headers)
|
||||
if resp.status_code == 404:
|
||||
return "absent"
|
||||
if not 200 <= resp.status_code < 300:
|
||||
raise RevenueCatError(f"RevenueCat delete returned HTTP {resp.status_code}")
|
||||
return "deleted"
|
||||
|
||||
# Step 5
|
||||
def _revoke_apple(self, code: Optional[str]) -> str:
|
||||
if not code:
|
||||
return "no_code"
|
||||
try:
|
||||
revoked = self._apple_revoke(code)
|
||||
except Exception as e: # the revoker never raises, but erasure must not depend on it
|
||||
logger.warning("Account deletion: Apple revoke raised %s", type(e).__name__)
|
||||
revoked = False
|
||||
if not revoked:
|
||||
logger.warning("Account deletion: Sign in with Apple token not revoked")
|
||||
return "failed"
|
||||
return "revoked"
|
||||
|
||||
# Step 6
|
||||
def _enqueue_kjbox(self, email: str, deletion_id: str) -> str:
|
||||
email_hash = email_sha256(email)
|
||||
ref = self.db.collection(ACCOUNT_DELETIONS_COLLECTION).document(email_hash)
|
||||
snap = ref.get()
|
||||
if snap.exists and (snap.to_dict() or {}).get("deletion_id") == deletion_id:
|
||||
return "already_queued"
|
||||
# New entry, or an earlier deletion of a re-created account: (re)queue it.
|
||||
ref.set({
|
||||
"email_hash": email_hash,
|
||||
"deletion_id": deletion_id,
|
||||
"created_at": _now(),
|
||||
"targets": {"kjbox": "pending"},
|
||||
})
|
||||
return "queued"
|
||||
|
||||
# Step 7
|
||||
def _scrub_jobs(self, email: str, deletion_id: str) -> dict:
|
||||
totals = {"jobs": 0, "input_objects_deleted": 0, "dropbox_links_revoked": 0}
|
||||
seen = set()
|
||||
for snap in self._owned_jobs(email) + self._customer_jobs(email):
|
||||
if snap.id in seen:
|
||||
continue
|
||||
seen.add(snap.id)
|
||||
result = self._scrub_job(snap, email, deletion_id)
|
||||
totals["jobs"] += 1
|
||||
totals["input_objects_deleted"] += result["input_objects_deleted"]
|
||||
totals["dropbox_links_revoked"] += result["dropbox_link_revoked"]
|
||||
logger.info(
|
||||
"Account deletion %s: job %s scrubbed (%d input objects deleted, dropbox link revoked: %s)",
|
||||
deletion_id, snap.id, result["input_objects_deleted"], result["dropbox_link_revoked"],
|
||||
)
|
||||
return totals
|
||||
|
||||
def _delete_prefix(self, prefix: str) -> int:
|
||||
deleted = 0
|
||||
for blob in self.bucket.list_blobs(prefix=prefix):
|
||||
try:
|
||||
blob.delete()
|
||||
deleted += 1
|
||||
except google_exceptions.NotFound:
|
||||
pass
|
||||
return deleted
|
||||
|
||||
def _delete_staged_instrumentals(self, job_id: str) -> int:
|
||||
"""The user's own instrumental, copied to the job root (``jobs/{id}/custom_instrumental.<ext>``,
|
||||
``jobs/{id}/existing_instrumental.<ext>``; see backend/utils/existing_instrumental.py).
|
||||
Only direct children of the job root: ``stems/custom_instrumental.flac`` is an output."""
|
||||
root = f"jobs/{job_id}/"
|
||||
deleted = 0
|
||||
for blob in self.bucket.list_blobs(prefix=root):
|
||||
rel = blob.name[len(root):]
|
||||
if "/" in rel or rel.rsplit(".", 1)[0] not in STAGED_INSTRUMENTAL_STEMS:
|
||||
continue
|
||||
try:
|
||||
blob.delete()
|
||||
deleted += 1
|
||||
except google_exceptions.NotFound:
|
||||
pass
|
||||
return deleted
|
||||
|
||||
def _scrub_job(self, snap, email: str, deletion_id: str) -> dict:
|
||||
"""Delete one job's inputs, revoke its share link, then anonymise the doc.
|
||||
|
||||
The doc update comes last: until it lands the job still matches the
|
||||
user's email, so a retry picks it up again.
|
||||
"""
|
||||
job_id = snap.id
|
||||
data = snap.to_dict() or {}
|
||||
state = data.get("state_data") or {}
|
||||
|
||||
deleted = sum(self._delete_prefix(prefix.format(job_id=job_id)) for prefix in INPUT_PREFIXES)
|
||||
deleted += self._delete_staged_instrumentals(job_id)
|
||||
|
||||
link = state.get("dropbox_link")
|
||||
revoked = 0
|
||||
if link and self.dropbox.revoke_shared_link(link) is not False:
|
||||
revoked = 1
|
||||
|
||||
tomb = deleted_owner(deletion_id)
|
||||
updates: Dict[str, Any] = {}
|
||||
if data.get("user_email") == email:
|
||||
updates["user_email"] = tomb
|
||||
if data.get("customer_email") == email:
|
||||
updates["customer_email"] = tomb
|
||||
if data.get("customer_notes"):
|
||||
updates["customer_notes"] = None
|
||||
if data.get("creation_ip"):
|
||||
updates["creation_ip"] = None
|
||||
for key in PERSONAL_STATE_KEYS + ("dropbox_link",):
|
||||
if key in state:
|
||||
updates[f"state_data.{key}"] = DELETE_FIELD
|
||||
if "client_ip" in (data.get("request_metadata") or {}):
|
||||
updates["request_metadata.client_ip"] = DELETE_FIELD
|
||||
if updates:
|
||||
self._jobs().document(job_id).update(updates)
|
||||
return {"input_objects_deleted": deleted, "dropbox_link_revoked": revoked}
|
||||
|
||||
# Step 8
|
||||
def _delete_where(self, collection: str, field: str, value: str) -> int:
|
||||
count = 0
|
||||
for snap in self.db.collection(collection).where(filter=FieldFilter(field, "==", value)).stream():
|
||||
snap.reference.delete()
|
||||
count += 1
|
||||
return count
|
||||
|
||||
def _delete_records(self, email: str, deletion_id: str) -> dict:
|
||||
user_ref = self._user_ref(email)
|
||||
user = user_ref.get().to_dict() or {}
|
||||
|
||||
tomb_ref = self.db.collection(DELETED_USERS_COLLECTION).document(deletion_id)
|
||||
if not tomb_ref.get().exists:
|
||||
tomb_ref.set({
|
||||
"deletion_id": deletion_id,
|
||||
"email_sha256": email_sha256(email),
|
||||
"credits_forfeited": max(int(user.get("credits") or 0), 0),
|
||||
"credits": int(user.get("credits") or 0),
|
||||
"credit_transactions": user.get("credit_transactions") or [],
|
||||
"total_jobs_created": user.get("total_jobs_created") or 0,
|
||||
"total_jobs_completed": user.get("total_jobs_completed") or 0,
|
||||
"total_spent": user.get("total_spent") or 0,
|
||||
"welcome_credits_granted": bool(user.get("welcome_credits_granted")),
|
||||
"created_at": user.get("created_at"),
|
||||
"deleted_at": _now(),
|
||||
})
|
||||
|
||||
summary = {
|
||||
"magic_links": self._delete_where(MAGIC_LINKS_COLLECTION, "email", email),
|
||||
"kjbox_signups": self._delete_where(KJBOX_SIGNUPS_COLLECTION, "email", email),
|
||||
}
|
||||
login_codes = 0
|
||||
for collection in (GEN_LOGIN_CODES_COLLECTION, KJBOX_LOGIN_CODES_COLLECTION):
|
||||
ref = self.db.collection(collection).document(code_doc_id(email))
|
||||
if ref.get().exists:
|
||||
ref.delete()
|
||||
login_codes += 1
|
||||
summary["login_codes"] = login_codes
|
||||
summary["anonymised"] = self._anonymise_kept_records(email, deletion_id)
|
||||
summary["email_log"] = self._delete_where(EMAIL_LOG_COLLECTION, "recipient", email)
|
||||
summary["email_log_copies"] = self._remove_from_email_log_copies(email)
|
||||
# Sessions, then the user doc, last: a failure before here leaves the
|
||||
# user signed in so the app can retry. (Web Push subscriptions and Expo
|
||||
# push tokens live on the user doc and go with it.)
|
||||
# Narrow window: if the user-doc delete below fails after the sessions are
|
||||
# gone, the app can't retry with its old token, but the gen_users doc (with
|
||||
# its deletion_id) is still there, so the user can sign in again and retry,
|
||||
# and the retry reuses the same deletion_id.
|
||||
summary["sessions"] = self._delete_where(SESSIONS_COLLECTION, "user_email", email)
|
||||
user_ref.delete()
|
||||
return summary
|
||||
|
||||
def _remove_from_email_log_copies(self, email: str) -> int:
|
||||
"""Drop the address from cc/bcc of mail sent to someone else (that log entry is theirs)."""
|
||||
touched = set()
|
||||
for field in ("cc", "bcc"):
|
||||
for snap in self.db.collection(EMAIL_LOG_COLLECTION).where(
|
||||
filter=FieldFilter(field, "array_contains", email)).stream():
|
||||
kept = [a for a in (snap.to_dict() or {}).get(field) or []
|
||||
if not isinstance(a, str) or a.strip().lower() != email]
|
||||
snap.reference.update({field: kept})
|
||||
touched.add(snap.id)
|
||||
return len(touched)
|
||||
|
||||
def _anonymise_where(self, collection: str, field: str, email: str, tomb: str, extra=None) -> int:
|
||||
"""Replace ``field == email`` with the tombstone (plus ``extra`` updates) on every match."""
|
||||
count = 0
|
||||
for snap in self.db.collection(collection).where(filter=FieldFilter(field, "==", email)).stream():
|
||||
snap.reference.update({field: tomb, **(extra(snap.to_dict() or {}) if extra else {})})
|
||||
count += 1
|
||||
return count
|
||||
|
||||
def _move_doc(self, collection: str, snap, new_id: str, updates: dict) -> None:
|
||||
"""Re-key a doc whose id contains the email (create the new doc first, then delete)."""
|
||||
data = snap.to_dict() or {}
|
||||
data.update(updates)
|
||||
self.db.collection(collection).document(new_id).set(data)
|
||||
snap.reference.delete()
|
||||
|
||||
def _anonymise_kept_records(self, email: str, deletion_id: str) -> dict:
|
||||
"""Records kept for accounting or history, with the email replaced by ``deleted:{id}``.
|
||||
|
||||
Idempotent: every lookup is by the email, which a finished pass has removed.
|
||||
"""
|
||||
tomb = deleted_owner(deletion_id)
|
||||
out: Dict[str, int] = {}
|
||||
|
||||
# kjbox show-credit grants: per-singer free-credit accounting (doc ids are hashes).
|
||||
out["kjbox_show_credits"] = self._anonymise_where(SHOW_CREDITS_COLLECTION, "email", email, tomb)
|
||||
counter = self.db.collection(SHOW_CREDIT_USERS_COLLECTION).document(email_sha256(email))
|
||||
snap = counter.get()
|
||||
if snap.exists and (snap.to_dict() or {}).get("email") == email:
|
||||
counter.update({"email": tomb})
|
||||
out["kjbox_show_credit_users"] = 1
|
||||
|
||||
# The user's own referral link: disabled (ReferralLink.enabled) and anonymised.
|
||||
out["referral_links"] = self._anonymise_where(
|
||||
REFERRAL_LINKS_COLLECTION, "owner_email", email, tomb,
|
||||
extra=lambda d: {"enabled": False, "display_name": None, "custom_message": None},
|
||||
)
|
||||
|
||||
# Vanity requests are keyed by the owner's email: re-key them.
|
||||
moved = 0
|
||||
vanity = self.db.collection(REFERRAL_VANITY_REQUESTS_COLLECTION)
|
||||
for snap in vanity.where(filter=FieldFilter("owner_email", "==", email)).stream():
|
||||
self._move_doc(REFERRAL_VANITY_REQUESTS_COLLECTION, snap, tomb, {"id": tomb, "owner_email": tomb})
|
||||
moved += 1
|
||||
out["referral_vanity_requests"] = moved
|
||||
|
||||
# Referral earnings stay for payout accounting; the emails go.
|
||||
out["referral_earnings"] = sum(
|
||||
self._anonymise_where(REFERRAL_EARNINGS_COLLECTION, field, email, tomb)
|
||||
for field in ("referred_email", "referrer_email")
|
||||
)
|
||||
|
||||
def _scrub_evaluation(d):
|
||||
updates = {}
|
||||
reasoning = d.get("reasoning")
|
||||
if isinstance(reasoning, str) and email in reasoning:
|
||||
updates["reasoning"] = reasoning.replace(email, tomb)
|
||||
# The signup IP and device fingerprint are personal data; the match counts are not.
|
||||
snapshot = d.get("signals_snapshot")
|
||||
if isinstance(snapshot, dict):
|
||||
for key in ("user_ip", "user_fingerprint"):
|
||||
if key in snapshot:
|
||||
updates[f"signals_snapshot.{key}"] = DELETE_FIELD
|
||||
return updates
|
||||
|
||||
out["credit_evaluations"] = self._anonymise_where(
|
||||
CREDIT_EVALUATIONS_COLLECTION, "email", email, tomb, extra=_scrub_evaluation)
|
||||
|
||||
# IAP purchase/refund markers keep the owner for refund matching; a refund
|
||||
# whose purchase owner is ``deleted:…`` is ignored, never debited from a
|
||||
# new account that later signs up with the same email.
|
||||
out["iap_transactions"] = self._anonymise_where(
|
||||
PROCESSED_IAP_TRANSACTIONS_COLLECTION, "email", email, tomb)
|
||||
|
||||
# Song requests: submitter, current owner and the handoff history.
|
||||
requests = self.db.collection(SONG_REQUESTS_COLLECTION)
|
||||
touched = set()
|
||||
for field in ("submitted_by", "owner_email"):
|
||||
for snap in requests.where(filter=FieldFilter(field, "==", email)).stream():
|
||||
snap.reference.update({field: tomb})
|
||||
touched.add(snap.id)
|
||||
for snap in requests.where(filter=FieldFilter("attempted_owners", "array_contains", email)).stream():
|
||||
owners = [tomb if o == email else o for o in (snap.to_dict() or {}).get("attempted_owners") or []]
|
||||
snap.reference.update({"attempted_owners": owners})
|
||||
touched.add(snap.id)
|
||||
out["song_requests"] = len(touched)
|
||||
|
||||
# Votes are keyed "{email}__{date}": re-key them so the vote totals stay explainable.
|
||||
votes = 0
|
||||
for snap in self.db.collection(SONG_REQUEST_VOTES_COLLECTION).where(
|
||||
filter=FieldFilter("voter_email", "==", email)).stream():
|
||||
day = (snap.to_dict() or {}).get("voted_date") or snap.id.rsplit("__", 1)[-1]
|
||||
self._move_doc(SONG_REQUEST_VOTES_COLLECTION, snap, f"{tomb}__{day}", {"voter_email": tomb})
|
||||
votes += 1
|
||||
out["song_request_votes"] = votes
|
||||
return out
|
||||
|
||||
# ------------------------------------------------------------ kjbox queue
|
||||
|
||||
def list_kjbox_pending(self, since: Optional[datetime] = None) -> List[dict]:
|
||||
query = self.db.collection(ACCOUNT_DELETIONS_COLLECTION).where(
|
||||
filter=FieldFilter("targets.kjbox", "==", "pending")
|
||||
)
|
||||
since = _aware(since) if since is not None else None
|
||||
out = []
|
||||
for snap in query.stream():
|
||||
data = snap.to_dict() or {}
|
||||
created = _aware(data.get("created_at"))
|
||||
if since is not None and (created is None or created <= since):
|
||||
continue
|
||||
out.append({"id": snap.id, "email_hash": data.get("email_hash"), "created_at": _iso(created)})
|
||||
out.sort(key=lambda e: e["created_at"] or "")
|
||||
return out
|
||||
|
||||
def ack_kjbox(self, deletion_doc_id: str) -> bool:
|
||||
ref = self.db.collection(ACCOUNT_DELETIONS_COLLECTION).document(deletion_doc_id)
|
||||
if not ref.get().exists:
|
||||
return False
|
||||
ref.update({"targets.kjbox": "done", "kjbox_acked_at": _now()})
|
||||
return True
|
||||
|
||||
|
||||
def is_deleted_email(db, email: str) -> bool:
|
||||
"""True when an account with this email was self-deleted before (no second welcome credit)."""
|
||||
query = db.collection(DELETED_USERS_COLLECTION).where(
|
||||
filter=FieldFilter("email_sha256", "==", email_sha256(email))
|
||||
).limit(1)
|
||||
return any(True for _ in query.stream())
|
||||
|
||||
|
||||
def get_account_deletion_service() -> AccountDeletionService:
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
return AccountDeletionService(get_user_service().db)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Revoke Sign in with Apple tokens (App Store guideline 5.1.1(v)).
|
||||
|
||||
Account deletion exchanges the app's one-time ``authorization_code`` for
|
||||
tokens, then revokes them so the app disappears from the user's Apple ID
|
||||
"Sign in with Apple" list. Best-effort: never raises; a stale code must not
|
||||
block erasure.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
import jwt
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
APPLE_AUDIENCE = "https://appleid.apple.com"
|
||||
TOKEN_URL = f"{APPLE_AUDIENCE}/auth/token"
|
||||
REVOKE_URL = f"{APPLE_AUDIENCE}/auth/revoke"
|
||||
_CLIENT_SECRET_TTL_SECONDS = 300
|
||||
_HTTP_TIMEOUT_SECONDS = 10
|
||||
|
||||
|
||||
class AppleRevoker:
|
||||
def __init__(self, settings=None):
|
||||
self._settings = settings or get_settings()
|
||||
|
||||
def _client_secret(self) -> str:
|
||||
s = self._settings
|
||||
now = int(time.time())
|
||||
return jwt.encode(
|
||||
{
|
||||
"iss": s.apple_team_id,
|
||||
"iat": now,
|
||||
"exp": now + _CLIENT_SECRET_TTL_SECONDS,
|
||||
"aud": APPLE_AUDIENCE,
|
||||
"sub": s.apple_client_id,
|
||||
},
|
||||
s.apple_siwa_key_p8,
|
||||
algorithm="ES256",
|
||||
headers={"kid": s.apple_siwa_key_id},
|
||||
)
|
||||
|
||||
async def revoke(self, authorization_code: Optional[str]) -> bool:
|
||||
"""Exchange the code and revoke the resulting token. True only if Apple revoked it."""
|
||||
s = self._settings
|
||||
if not (s.apple_siwa_key_p8 and s.apple_siwa_key_id):
|
||||
logger.warning("Apple revocation skipped: APPLE_SIWA_KEY_P8/APPLE_SIWA_KEY_ID not configured")
|
||||
return False
|
||||
if not authorization_code:
|
||||
logger.warning("Apple revocation skipped: no authorization code")
|
||||
return False
|
||||
try:
|
||||
secret = self._client_secret()
|
||||
async with httpx.AsyncClient(timeout=_HTTP_TIMEOUT_SECONDS) as client:
|
||||
resp = await client.post(
|
||||
TOKEN_URL,
|
||||
data={
|
||||
"client_id": s.apple_client_id,
|
||||
"client_secret": secret,
|
||||
"code": authorization_code,
|
||||
"grant_type": "authorization_code",
|
||||
},
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
logger.warning("Apple token exchange failed: HTTP %s", resp.status_code)
|
||||
return False
|
||||
body = resp.json()
|
||||
refresh = body.get("refresh_token")
|
||||
token = refresh or body.get("access_token")
|
||||
if not token:
|
||||
logger.warning("Apple token exchange returned no token")
|
||||
return False
|
||||
resp = await client.post(
|
||||
REVOKE_URL,
|
||||
data={
|
||||
"client_id": s.apple_client_id,
|
||||
"client_secret": secret,
|
||||
"token": token,
|
||||
"token_type_hint": "refresh_token" if refresh else "access_token",
|
||||
},
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
logger.warning("Apple token revoke failed: HTTP %s", resp.status_code)
|
||||
return False
|
||||
return True
|
||||
except Exception as e: # never raise into account deletion
|
||||
logger.warning("Apple revocation error: %s", type(e).__name__)
|
||||
return False
|
||||
@@ -19,6 +19,7 @@ import asyncio
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import nest_asyncio
|
||||
@@ -175,13 +176,62 @@ def _check_filename_mismatch(search_title: str, result: Dict[str, Any]) -> bool:
|
||||
return not matches
|
||||
|
||||
|
||||
def pick_auto_selection(results: List[Dict[str, Any]], search_title: str = "") -> Optional[int]:
|
||||
def _edit_distance(a: str, b: str) -> int:
|
||||
prev = list(range(len(b) + 1))
|
||||
for i in range(1, len(a) + 1):
|
||||
cur = [i]
|
||||
for j in range(1, len(b) + 1):
|
||||
cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] != b[j - 1])))
|
||||
prev = cur
|
||||
return prev[len(b)]
|
||||
|
||||
|
||||
def _norm_artist(x: str) -> str:
|
||||
"""Lowercase, accents folded, "&"/"+" as "and", punctuation dropped, a leading
|
||||
"the" removed. Unicode-aware: CJK/Cyrillic names survive (unlike [a-z0-9])."""
|
||||
x = unicodedata.normalize("NFKD", (x or "").casefold())
|
||||
x = "".join(ch for ch in x if not unicodedata.combining(ch))
|
||||
x = re.sub(r"\s*[&+]\s*", " and ", x)
|
||||
x = re.sub(r"[^\w\s]|_", " ", x)
|
||||
x = re.sub(r"\s+", " ", x).strip()
|
||||
return re.sub(r"^the\s+", "", x)
|
||||
|
||||
|
||||
def is_artist_match(search_artist: str, result: Dict[str, Any]) -> bool:
|
||||
"""Port of isArtistMatch() — the result's artist is the one searched for.
|
||||
|
||||
"The Killers" vs "Killers", "X, Someone" vs "X" and "Simon & Garfunkel" vs
|
||||
"Simon and Garfunkel" match; small typos are tolerated for names of 5+
|
||||
characters. A searched name that normalizes to nothing can't be compared, so
|
||||
it isn't held against the result (mirrors _check_filename_mismatch).
|
||||
"""
|
||||
raw_have = result.get("artist") or ""
|
||||
if search_artist and search_artist.strip().casefold() == raw_have.strip().casefold():
|
||||
return True
|
||||
want = _norm_artist(search_artist)
|
||||
have = _norm_artist(raw_have)
|
||||
if not want:
|
||||
return True
|
||||
if len(want) < 2 or not have:
|
||||
return False
|
||||
if have == want or f" {want} " in f" {have} " or f" {have} " in f" {want} ":
|
||||
return True
|
||||
if len(want) < 5:
|
||||
return False
|
||||
return _edit_distance(want, have) <= len(want) // 5
|
||||
|
||||
|
||||
def pick_auto_selection(
|
||||
results: List[Dict[str, Any]], search_title: str = "", search_artist: str = ""
|
||||
) -> Optional[int]:
|
||||
"""Return the index to auto-select, or None if no confident lossless pick.
|
||||
|
||||
Tier-1 rule (mirrors getSearchConfidence): the best result must be in the
|
||||
BEST CHOICE category (lossless, BEST_CHOICE_MIN_SEEDERS+ seeders, non-vinyl) AND its filename
|
||||
must match ``search_title`` (the song the user searched for). Otherwise we
|
||||
defer to human selection.
|
||||
BEST CHOICE category (lossless, BEST_CHOICE_MIN_SEEDERS+ seeders, non-vinyl),
|
||||
its filename must match ``search_title`` (the song the user searched for),
|
||||
and, when ``search_artist`` is given, its artist must match too (a
|
||||
well-seeded cover or tribute isn't a perfect match). Otherwise we defer to
|
||||
human selection.
|
||||
"""
|
||||
if not results:
|
||||
return None
|
||||
@@ -192,13 +242,22 @@ def pick_auto_selection(results: List[Dict[str, Any]], search_title: str = "") -
|
||||
best = _get_best_result(results)
|
||||
if best is None:
|
||||
return None
|
||||
if _categorize_result(best) != "BEST CHOICE":
|
||||
return None
|
||||
if _check_filename_mismatch(search_title, best):
|
||||
if not _is_confident_pick(best, search_title, search_artist):
|
||||
return None
|
||||
return best.get("index")
|
||||
|
||||
|
||||
def _is_confident_pick(result: Dict[str, Any], search_title: str, search_artist: str = "") -> bool:
|
||||
"""BEST CHOICE category, filename names the track, and (if given) the right artist."""
|
||||
if _categorize_result(result) != "BEST CHOICE":
|
||||
return False
|
||||
if _check_filename_mismatch(search_title, result):
|
||||
return False
|
||||
if search_artist and not is_artist_match(search_artist, result):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class AudioSearchService:
|
||||
"""
|
||||
Service for searching and downloading audio files.
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Bulk "By album": one album search for the whole batch instead of one per track.
|
||||
|
||||
flacfetch's ``POST /search/album`` returns the album's lossless torrents, each
|
||||
with ``track_files`` mapping our track keys (job IDs) to a file in the torrent.
|
||||
This module turns that response into each job's ``audio_search_results`` (the
|
||||
same dict shape as ``AudioSearchResult.to_dict()``, so the selection modal,
|
||||
``_validate_and_prepare_selection`` and the download worker work unchanged), and
|
||||
decides which torrent the batch should use.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from backend.services.audio_search_service import (
|
||||
_categorize_result,
|
||||
_is_confident_pick,
|
||||
pick_auto_selection,
|
||||
)
|
||||
|
||||
|
||||
def _result_for_track(torrent: Dict[str, Any], track_file: Dict[str, Any], index: int) -> Dict[str, Any]:
|
||||
"""One torrent + one of its files as an audio search result dict."""
|
||||
return {
|
||||
"title": torrent.get("title"),
|
||||
"artist": torrent.get("artist"),
|
||||
"url": "",
|
||||
"provider": torrent.get("provider"),
|
||||
"duration": None,
|
||||
"quality": torrent.get("quality"),
|
||||
"quality_data": torrent.get("quality_data"),
|
||||
"is_lossless": torrent.get("is_lossless", False),
|
||||
"source_id": torrent.get("source_id"),
|
||||
"index": index,
|
||||
"seeders": torrent.get("seeders"),
|
||||
"size_bytes": torrent.get("size_bytes"),
|
||||
"formatted_size": torrent.get("formatted_size"),
|
||||
"year": torrent.get("year"),
|
||||
"label": torrent.get("label"),
|
||||
"edition_info": torrent.get("edition_info"),
|
||||
"release_type": torrent.get("release_type"),
|
||||
"target_file": track_file.get("target_file"),
|
||||
"target_file_size": track_file.get("target_file_size"),
|
||||
"match_score": track_file.get("match_score", 0.0),
|
||||
# Marks results that came from the batch's album search (diagnostics).
|
||||
"album_search": True,
|
||||
}
|
||||
|
||||
|
||||
def _torrent_id(torrent: Dict[str, Any]) -> tuple:
|
||||
return (torrent.get("provider"), torrent.get("source_id"))
|
||||
|
||||
|
||||
def choose_batch_torrent(torrents: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""The torrent the whole batch should download from.
|
||||
|
||||
flacfetch orders torrents by tracks covered, then non-vinyl, then seeders; take
|
||||
the first that is a BEST CHOICE source (lossless, non-vinyl, enough seeders),
|
||||
so every track comes from one torrent. None if no torrent qualifies.
|
||||
"""
|
||||
for torrent in torrents:
|
||||
if _categorize_result(torrent) == "BEST CHOICE":
|
||||
return torrent
|
||||
return None
|
||||
|
||||
|
||||
def build_track_results(
|
||||
torrents: List[Dict[str, Any]],
|
||||
track_key: str,
|
||||
batch_torrent: Optional[Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""A job's search results from the album search: every torrent that has a file
|
||||
for this track, the batch torrent first, then flacfetch's order."""
|
||||
covering = [t for t in torrents if track_key in (t.get("track_files") or {})]
|
||||
if batch_torrent is not None:
|
||||
batch_id = _torrent_id(batch_torrent)
|
||||
covering.sort(key=lambda t: _torrent_id(t) != batch_id) # stable: batch torrent first
|
||||
return [
|
||||
_result_for_track(t, t["track_files"][track_key], index)
|
||||
for index, t in enumerate(covering)
|
||||
]
|
||||
|
||||
|
||||
def pick_album_auto_selection(
|
||||
results: List[Dict[str, Any]],
|
||||
batch_torrent: Optional[Dict[str, Any]],
|
||||
search_title: str,
|
||||
search_artist: str,
|
||||
) -> Optional[int]:
|
||||
"""Auto-select this track's file in the batch torrent, if it's a confident pick.
|
||||
|
||||
Album mode sticks to the batch torrent so the whole album downloads once; the
|
||||
same tier-1 checks apply to it (BEST CHOICE, the file names the track, the
|
||||
artist matches). A track the batch torrent doesn't cover (or a batch with no
|
||||
BEST CHOICE torrent) gets the normal per-track pick among the album torrents
|
||||
that do cover it: one extra torrent for that track beats parking it.
|
||||
"""
|
||||
if not results:
|
||||
return None
|
||||
if len((search_title or "").strip()) < 3:
|
||||
return None
|
||||
first = results[0]
|
||||
if batch_torrent is None or _torrent_id(first) != _torrent_id(batch_torrent):
|
||||
return pick_auto_selection(results, search_title, search_artist)
|
||||
if not _is_confident_pick(first, search_title, search_artist):
|
||||
return None
|
||||
return first.get("index")
|
||||
@@ -0,0 +1,60 @@
|
||||
"""gen → karaoke-decide partner calls (``X-Partner-Secret``).
|
||||
|
||||
decide already authenticates to gen with ``DECIDE_GEN_PARTNER_SECRET``; account
|
||||
deletion uses the same secret in the other direction to erase a gen user's
|
||||
decide data. The host is gen's existing decide setting
|
||||
(``karaoke_decide_api_url``, default https://decide.nomadkaraoke.com), which is
|
||||
decide's main API (the catalog proxy uses the same host).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_TIMEOUT_SECONDS = 30
|
||||
USERS_PATH = "/api/partner/gen/users"
|
||||
|
||||
|
||||
class DecidePartnerError(RuntimeError):
|
||||
"""decide is unconfigured or answered non-2xx."""
|
||||
|
||||
|
||||
class DecidePartnerClient:
|
||||
def __init__(self, base_url: Optional[str] = None, secret: Optional[str] = None, http_client=None):
|
||||
settings = get_settings()
|
||||
self.base_url = (base_url if base_url is not None else settings.karaoke_decide_api_url or "").rstrip("/")
|
||||
self.secret = secret if secret is not None else settings.decide_partner_secret
|
||||
self._http_client = http_client # injectable httpx.Client for tests
|
||||
|
||||
def delete_user(self, email: str) -> dict:
|
||||
"""Erase every decide store for the gen user ``email``. Idempotent on decide's side.
|
||||
|
||||
Returns decide's ``{"deleted": {collection: count}}``. Raises
|
||||
:class:`DecidePartnerError` when unconfigured or on any non-2xx.
|
||||
"""
|
||||
if not self.base_url or not self.secret:
|
||||
raise DecidePartnerError("decide partner API not configured (karaoke_decide_api_url / DECIDE_GEN_PARTNER_SECRET)")
|
||||
url = f"{self.base_url}{USERS_PATH}"
|
||||
headers = {"X-Partner-Secret": self.secret}
|
||||
body = {"email": email.strip().lower()}
|
||||
try:
|
||||
if self._http_client is not None:
|
||||
resp = self._http_client.request("DELETE", url, json=body, headers=headers)
|
||||
else:
|
||||
with httpx.Client(timeout=_TIMEOUT_SECONDS) as client:
|
||||
resp = client.request("DELETE", url, json=body, headers=headers)
|
||||
except httpx.HTTPError as e:
|
||||
raise DecidePartnerError(f"decide delete request failed: {type(e).__name__}") from e
|
||||
if not 200 <= resp.status_code < 300:
|
||||
raise DecidePartnerError(f"decide delete returned HTTP {resp.status_code}")
|
||||
try:
|
||||
data = resp.json()
|
||||
except ValueError:
|
||||
data = {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
@@ -466,6 +466,34 @@ class DropboxService:
|
||||
return links.links[0].url
|
||||
raise
|
||||
|
||||
def revoke_shared_link(self, url: str) -> bool:
|
||||
"""Revoke a shared link (the folder and its files stay). Idempotent.
|
||||
|
||||
Returns True when revoked or already gone. A link Dropbox can't revoke
|
||||
(malformed, or a link type that has no revoke) is nothing to revoke:
|
||||
WARNING and False, so it never blocks account deletion. Any other
|
||||
failure (network, auth, rate limit, access denied) raises.
|
||||
"""
|
||||
from dropbox.exceptions import ApiError
|
||||
|
||||
try:
|
||||
self.client.sharing_revoke_shared_link(url)
|
||||
logger.info("Revoked Dropbox shared link")
|
||||
return True
|
||||
except ApiError as e:
|
||||
err = getattr(e, "error", None)
|
||||
|
||||
def _is(name: str) -> bool:
|
||||
return bool(err is not None and getattr(err, name, lambda: False)())
|
||||
|
||||
if _is("is_shared_link_not_found"):
|
||||
logger.info("Dropbox shared link already gone")
|
||||
return True
|
||||
if _is("is_shared_link_malformed") or _is("is_unsupported_link_type"):
|
||||
logger.warning("Dropbox shared link can't be revoked (%s); nothing to revoke", err)
|
||||
return False
|
||||
raise
|
||||
|
||||
def delete_folder(self, path: str) -> bool:
|
||||
"""
|
||||
Delete a folder and all its contents from Dropbox.
|
||||
|
||||
@@ -61,6 +61,15 @@ MONITORED_CLOUD_RUN_JOBS: list[str] = [
|
||||
"lb-refresh",
|
||||
# karaoke-decide song search index build (eval-gated)
|
||||
"song-index-build",
|
||||
# karaoke-decide Phase 3d voice pool (us-central1): select -> fetch -> analyse
|
||||
"voice-pool-select",
|
||||
"voice-pool-fetch",
|
||||
"voice-pool-analyse",
|
||||
# karaoke-decide vocal-range generation (us-central1); logs one ERROR from task 0
|
||||
# only when every attempted job fails
|
||||
"vocal-range-gen",
|
||||
# gen GPU separation job for the voice pool (us-east4; no region filter in the log query)
|
||||
"voice-pool-separate-job",
|
||||
]
|
||||
|
||||
# Gen2 Cloud Functions log as cloud_run_revision, not cloud_function.
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Expo push notifications for the Nomad Karaoke mobile app.
|
||||
|
||||
Tokens live on the gen user (``expo_push_tokens``, one entry per device). A flat
|
||||
``expo_push_token_values`` array mirrors the token strings so a token can be found
|
||||
across users with ``array_contains`` (Firestore cannot query inside array objects).
|
||||
|
||||
A token belongs to exactly one user: registering it removes it from everyone else,
|
||||
so a device that signs into another account never receives the previous account's
|
||||
notifications.
|
||||
|
||||
In fake-workers mode (the local E2E stack) ``send`` records to an in-memory outbox
|
||||
instead of calling Expo.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Literal, Optional
|
||||
|
||||
import httpx
|
||||
from google.cloud.firestore_v1.base_query import FieldFilter
|
||||
|
||||
from backend.models.user import ExpoPushToken, effective_push_prefs
|
||||
from backend.services.fake_workers import fake_workers_enabled
|
||||
from backend.services.login_code_store import run_firestore_transaction
|
||||
from backend.services.user_service import USERS_COLLECTION, UserService, get_user_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
EXPO_PUSH_URL = "https://exp.host/--/api/v2/push/send"
|
||||
EXPO_BATCH_SIZE = 100
|
||||
TOKENS_FIELD = "expo_push_tokens"
|
||||
VALUES_FIELD = "expo_push_token_values"
|
||||
|
||||
PushKind = Literal["ready", "review", "problems"]
|
||||
|
||||
|
||||
def _token_of(entry) -> Optional[str]:
|
||||
return entry.get("token") if isinstance(entry, dict) else None
|
||||
|
||||
|
||||
class ExpoPushService:
|
||||
def __init__(self, user_service: Optional[UserService] = None, transaction_runner=None, http_post=None):
|
||||
self._user_service = user_service
|
||||
self._transaction_runner = transaction_runner # injectable for in-memory Firestore fakes
|
||||
self._http_post = http_post or httpx.post
|
||||
|
||||
@property
|
||||
def user_service(self) -> UserService:
|
||||
return self._user_service or get_user_service()
|
||||
|
||||
@property
|
||||
def db(self):
|
||||
return self.user_service.db
|
||||
|
||||
def _run_transaction(self, fn):
|
||||
if self._transaction_runner is not None:
|
||||
return self._transaction_runner(fn)
|
||||
return run_firestore_transaction(self.db, fn)
|
||||
|
||||
# ------------------------------------------------------------------ tokens
|
||||
|
||||
def register_token(self, email: str, token: str, platform: str, device_id: str) -> None:
|
||||
"""Store ``token`` for ``email`` (one entry per device) and remove it from every other user."""
|
||||
self.user_service.get_or_create_user(email)
|
||||
me_ref = self.user_service.get_user_doc_ref(email)
|
||||
if me_ref is None:
|
||||
raise ValueError(f"user not found: {email}")
|
||||
users = self.db.collection(USERS_COLLECTION)
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
def txn(transaction):
|
||||
# All reads before any write.
|
||||
mine = me_ref.get(transaction=transaction)
|
||||
others = list(
|
||||
users.where(filter=FieldFilter(VALUES_FIELD, "array_contains", token)).stream(transaction=transaction)
|
||||
)
|
||||
existing = (mine.to_dict() or {}).get(TOKENS_FIELD) or []
|
||||
kept = [e for e in existing if _token_of(e) != token and e.get("device_id") != device_id]
|
||||
entry = ExpoPushToken(token=token, platform=platform, device_id=device_id, created_at=now).model_dump()
|
||||
new_list = kept + [entry]
|
||||
for other in others:
|
||||
if other.reference.id == me_ref.id:
|
||||
continue
|
||||
remaining = [e for e in (other.to_dict() or {}).get(TOKENS_FIELD) or [] if _token_of(e) != token]
|
||||
transaction.update(other.reference, {
|
||||
TOKENS_FIELD: remaining,
|
||||
VALUES_FIELD: [_token_of(e) for e in remaining],
|
||||
})
|
||||
transaction.set(me_ref, {
|
||||
TOKENS_FIELD: new_list,
|
||||
VALUES_FIELD: [_token_of(e) for e in new_list],
|
||||
}, merge=True)
|
||||
|
||||
self._run_transaction(txn)
|
||||
|
||||
def remove_tokens(self, email: str, tokens: List[str]) -> None:
|
||||
"""Remove ``tokens`` from ``email`` (no-op for unknown users or tokens)."""
|
||||
if not tokens:
|
||||
return
|
||||
me_ref = self.user_service.get_user_doc_ref(email)
|
||||
if me_ref is None:
|
||||
return
|
||||
drop = set(tokens)
|
||||
|
||||
def txn(transaction):
|
||||
snap = me_ref.get(transaction=transaction)
|
||||
if not snap.exists:
|
||||
return
|
||||
existing = (snap.to_dict() or {}).get(TOKENS_FIELD) or []
|
||||
remaining = [e for e in existing if _token_of(e) not in drop]
|
||||
if len(remaining) == len(existing):
|
||||
return
|
||||
transaction.update(me_ref, {
|
||||
TOKENS_FIELD: remaining,
|
||||
VALUES_FIELD: [_token_of(e) for e in remaining],
|
||||
})
|
||||
|
||||
self._run_transaction(txn)
|
||||
|
||||
# ------------------------------------------------------------------ sending
|
||||
|
||||
def send(self, email: str, kind: PushKind, title: str, body: str, url: str) -> int:
|
||||
"""Push to every Expo token of ``email`` if their ``kind`` preference is on.
|
||||
|
||||
Returns the number of notifications Expo accepted (or captured, in fake mode).
|
||||
Never raises: a failed push must not affect job processing.
|
||||
"""
|
||||
try:
|
||||
user = self.user_service.get_user(email)
|
||||
if user is None:
|
||||
return 0
|
||||
if not effective_push_prefs(getattr(user, "push_prefs", None)).get(kind, True):
|
||||
logger.debug("Expo push %s suppressed by preference for %s", kind, email)
|
||||
return 0
|
||||
tokens = [t.token for t in user.expo_push_tokens]
|
||||
if not tokens:
|
||||
return 0
|
||||
|
||||
if fake_workers_enabled():
|
||||
from backend.services.fake_workers.outbox import record_push
|
||||
|
||||
record_push(email, kind, title, body, url)
|
||||
return len(tokens)
|
||||
|
||||
return self._send_batches(email, tokens, kind, title, body, url)
|
||||
except Exception:
|
||||
logger.exception("Expo push failed for %s", email)
|
||||
return 0
|
||||
|
||||
def _send_batches(self, email: str, tokens: List[str], kind: str, title: str, body: str, url: str) -> int:
|
||||
sent = 0
|
||||
dead: List[str] = []
|
||||
for i in range(0, len(tokens), EXPO_BATCH_SIZE):
|
||||
batch = tokens[i:i + EXPO_BATCH_SIZE]
|
||||
messages = [
|
||||
{"to": tok, "title": title, "body": body, "sound": "default", "data": {"url": url, "kind": kind}}
|
||||
for tok in batch
|
||||
]
|
||||
try:
|
||||
resp = self._http_post(
|
||||
EXPO_PUSH_URL, json=messages, timeout=15,
|
||||
headers={"Accept": "application/json", "Content-Type": "application/json"},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
tickets = resp.json().get("data") or []
|
||||
except Exception as exc:
|
||||
logger.warning("Expo push batch of %d failed: %s", len(batch), exc)
|
||||
continue
|
||||
for tok, ticket in zip(batch, tickets):
|
||||
if ticket.get("status") == "ok":
|
||||
sent += 1
|
||||
elif (ticket.get("details") or {}).get("error") == "DeviceNotRegistered":
|
||||
dead.append(tok)
|
||||
else:
|
||||
logger.warning("Expo ticket error for a token of %s: %s", email, ticket.get("message"))
|
||||
if dead:
|
||||
self.remove_tokens(email, dead)
|
||||
logger.info("Removed %d unregistered Expo tokens for %s", len(dead), email)
|
||||
return sent
|
||||
|
||||
|
||||
_expo_push_service: Optional[ExpoPushService] = None
|
||||
|
||||
|
||||
def get_expo_push_service() -> ExpoPushService:
|
||||
global _expo_push_service
|
||||
if _expo_push_service is None:
|
||||
_expo_push_service = ExpoPushService()
|
||||
return _expo_push_service
|
||||
@@ -8,6 +8,7 @@ from __future__ import annotations
|
||||
import html
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
@@ -64,3 +65,31 @@ def list_emails(to_email: Optional[str] = None, limit: int = 20) -> List[Dict[st
|
||||
if isinstance(d.get("created_at"), datetime):
|
||||
d["created_at"] = d["created_at"].isoformat()
|
||||
return docs[:limit]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Expo push sink
|
||||
# In-memory (fake workers run in the API process, so no Firestore round-trip is needed).
|
||||
_push_outbox: List[Dict[str, Any]] = []
|
||||
_push_lock = threading.Lock()
|
||||
|
||||
|
||||
def record_push(email: str, kind: str, title: str, body: str, url: str) -> None:
|
||||
with _push_lock:
|
||||
_push_outbox.append({
|
||||
"to": (email or "").strip().lower(), "kind": kind, "title": title, "body": body, "url": url,
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
|
||||
|
||||
def list_pushes(email: Optional[str] = None, limit: int = 50) -> List[Dict[str, Any]]:
|
||||
"""Newest first."""
|
||||
with _push_lock:
|
||||
rows = list(_push_outbox)
|
||||
if email:
|
||||
rows = [r for r in rows if r["to"] == email.strip().lower()]
|
||||
return list(reversed(rows))[:limit]
|
||||
|
||||
|
||||
def clear_pushes() -> None:
|
||||
with _push_lock:
|
||||
_push_outbox.clear()
|
||||
@@ -87,6 +87,36 @@ def frontend_fixture() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def build_album_response(artist: str, album: str, tracks: List[Dict[str, Any]], confidence: str = "perfect") -> Dict[str, Any]:
|
||||
"""Fake flacfetch ``/search/album`` response: one lossless CD torrent of the
|
||||
album with a file for every requested track, seeded per ``confidence``
|
||||
(``unsure`` names every file after a different song, so nothing auto-picks)."""
|
||||
seeders = {"perfect": 120, "recommended": 5, "unsure": 3}[confidence]
|
||||
track_files = {}
|
||||
for i, t in enumerate(tracks, start=1):
|
||||
name = _MISMATCHED_TITLE if confidence == "unsure" else t["title"]
|
||||
track_files[t["key"]] = {
|
||||
"target_file": f"{t.get('position') or i:02d} - {name}.flac",
|
||||
"target_file_size": 30_000_000,
|
||||
"match_score": 1.0 if confidence != "unsure" else 0.3,
|
||||
}
|
||||
return {
|
||||
"artist": artist,
|
||||
"album": album,
|
||||
"tracks_requested": len(tracks),
|
||||
"results_count": 1,
|
||||
"results": [{
|
||||
"title": album, "artist": artist, "provider": "RED",
|
||||
"source_id": _source_id("RED", artist, album),
|
||||
"quality": "FLAC 16bit CD",
|
||||
"quality_data": {"format": "FLAC", "bit_depth": 16, "media": "CD"},
|
||||
"is_lossless": True, "seeders": seeders, "size_bytes": 400_000_000,
|
||||
"formatted_size": "381.5 MB", "year": 2001, "label": "Fake Records",
|
||||
"release_type": "Album", "matched_count": len(track_files), "track_files": track_files,
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
class FakeAudioSearchService:
|
||||
"""Drop-in for ``AudioSearchService`` (the methods the API routes call)."""
|
||||
|
||||
@@ -112,6 +142,15 @@ class FakeAudioSearchService:
|
||||
return 0
|
||||
|
||||
|
||||
class FakeAlbumSearchClient:
|
||||
"""Drop-in for ``FlacfetchClient.search_album`` on the local stack."""
|
||||
|
||||
async def search_album(self, artist: str, album: str, tracks: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
from backend.services.fake_workers.config import get_fake_config
|
||||
|
||||
return build_album_response(artist, album, tracks, get_fake_config().search_confidence)
|
||||
|
||||
|
||||
if __name__ == "__main__": # python -m backend.services.fake_workers.search --write-fixture
|
||||
import sys
|
||||
|
||||
|
||||
@@ -296,6 +296,66 @@ class FlacfetchClient:
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
async def search_album(
|
||||
self,
|
||||
artist: str,
|
||||
album: str,
|
||||
tracks: List[Dict[str, Any]],
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Find lossless torrents of one album, with each requested track mapped to a file.
|
||||
|
||||
``tracks`` is ``[{"key", "title", "position"?}]``. Returns flacfetch's album
|
||||
search response: ``results`` (torrents, best coverage first) each with
|
||||
``track_files`` ``{key: {target_file, target_file_size, match_score}}``.
|
||||
A 404 (no torrent covers any track, or a flacfetch without the endpoint)
|
||||
returns empty ``results`` so callers fall back to per-track search.
|
||||
|
||||
Shares the per-track search's retry policy and total time budget.
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On failure after retries, or timeout.
|
||||
"""
|
||||
settings = get_settings()
|
||||
total_timeout = settings.flacfetch_search_total_timeout
|
||||
try:
|
||||
return await asyncio.wait_for(
|
||||
with_retry(
|
||||
self._search_album_impl,
|
||||
artist,
|
||||
album,
|
||||
tracks,
|
||||
retry_max_attempts=settings.flacfetch_search_retry_max_attempts,
|
||||
retry_min_wait=settings.flacfetch_search_retry_wait,
|
||||
retry_max_wait=settings.flacfetch_search_retry_wait,
|
||||
),
|
||||
timeout=total_timeout,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
raise FlacfetchServiceError(
|
||||
f"Album search timed out after {total_timeout:.0f}s total (including retries)"
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Album search request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Album search failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
async def _search_album_impl(
|
||||
self, artist: str, album: str, tracks: List[Dict[str, Any]]
|
||||
) -> Dict[str, Any]:
|
||||
"""Album search without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/search/album",
|
||||
headers=self._headers(),
|
||||
json={"artist": artist, "album": album, "tracks": tracks},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
if resp.status_code == 404:
|
||||
return {"artist": artist, "album": album, "results": [], "results_count": 0}
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
async def download(
|
||||
self,
|
||||
search_id: str,
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
"""
|
||||
In-app purchases (App Store / Play Store credit packs) via RevenueCat webhooks.
|
||||
|
||||
RevenueCat posts one event per store transaction. A consumable credit pack
|
||||
arrives as ``NON_RENEWING_PURCHASE``; a refund arrives as ``CANCELLATION``
|
||||
(``cancel_reason`` CUSTOMER_SUPPORT, negative price). ``REFUND`` is accepted as
|
||||
an alias (local stack fake-iap routes).
|
||||
|
||||
Exactly-once: each grant / debit runs in ONE Firestore transaction that reads
|
||||
and ``create``s a marker in ``processed_revenuecat_transactions``
|
||||
(``{store}:{transaction_id}`` for a purchase, ``…:refund`` for its refund),
|
||||
updates ``gen_users.credits`` and appends to ``credit_transactions``. A replay
|
||||
or a concurrent duplicate sees the marker and changes nothing. The
|
||||
``store_payments`` record (admin revenue) and the referral earning are written
|
||||
after the commit: the payment doc is keyed by transaction so a rewrite is
|
||||
harmless, and the earning is recorded only by the delivery that granted.
|
||||
|
||||
A refund debits the credits the purchase granted, from the account that
|
||||
received them, even when that takes the balance below zero (credits already
|
||||
spent). Job creation refuses a negative balance with 402. A CANCELLATION that
|
||||
is not a refund (positive price, another cancel_reason) changes nothing. A
|
||||
refund with no grant on record still writes its ``…:refund`` marker as a
|
||||
tombstone, so a purchase delivered after its own refund never grants.
|
||||
Sandbox purchases grant but never count toward ``total_spent``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from decimal import ROUND_FLOOR, Decimal, InvalidOperation
|
||||
from typing import Optional
|
||||
|
||||
from google.api_core import exceptions as google_exceptions
|
||||
|
||||
from backend.models.user import CreditTransaction
|
||||
from backend.services.login_code_store import TransactionContention, run_firestore_transaction
|
||||
from backend.services.stripe_service import CREDIT_PACKAGES
|
||||
from backend.services.user_service import MAX_CREDIT_TRANSACTIONS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PROCESSED_TRANSACTIONS_COLLECTION = "processed_revenuecat_transactions"
|
||||
STORE_PAYMENTS_COLLECTION = "store_payments"
|
||||
|
||||
PURCHASE_REASON = "iap_purchase"
|
||||
REFUND_REASON = "iap_refund"
|
||||
|
||||
PURCHASE_EVENT_TYPES = frozenset({"NON_RENEWING_PURCHASE"})
|
||||
REFUND_EVENT_TYPES = frozenset({"CANCELLATION", "REFUND"})
|
||||
|
||||
# RevenueCat ``store`` → our payment source (also the referral earning ``source``).
|
||||
STORE_SOURCES = {
|
||||
"APP_STORE": "app_store",
|
||||
"MAC_APP_STORE": "app_store",
|
||||
"PLAY_STORE": "play_store",
|
||||
}
|
||||
|
||||
# Used when an event lacks ``takehome_percentage`` (store commission ~15%).
|
||||
DEFAULT_TAKEHOME = Decimal("0.85")
|
||||
|
||||
ANONYMOUS_ID_PREFIX = "$RCAnonymousID:"
|
||||
|
||||
|
||||
@dataclass
|
||||
class IapResult:
|
||||
action: str # granted | debited | duplicate | ignored | unknown_user | unknown_product
|
||||
credits: Optional[int] = None # balance after a grant / debit
|
||||
email: Optional[str] = None
|
||||
|
||||
|
||||
def package_for_product(product_id: Optional[str]) -> Optional[tuple]:
|
||||
"""(package_id, package) for a store product id, or None."""
|
||||
for pkg_id, pkg in CREDIT_PACKAGES.items():
|
||||
if product_id and pkg.get("store_product_id") == product_id:
|
||||
return pkg_id, pkg
|
||||
return None
|
||||
|
||||
|
||||
def is_refund(event: dict) -> bool:
|
||||
"""A refund: ``REFUND`` (fake-iap alias), or a CANCELLATION with a negative
|
||||
price or cancel_reason CUSTOMER_SUPPORT (how RevenueCat reports refunds)."""
|
||||
if event.get("type") == "REFUND":
|
||||
return True
|
||||
price = _decimal(event.get("price"))
|
||||
return (price is not None and price < 0) or event.get("cancel_reason") == "CUSTOMER_SUPPORT"
|
||||
|
||||
|
||||
def _is_sandbox(event: dict) -> bool:
|
||||
return (event.get("environment") or "PRODUCTION").upper() == "SANDBOX"
|
||||
|
||||
|
||||
def _decimal(value) -> Optional[Decimal]:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return Decimal(str(value))
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def price_cents(event: dict) -> int:
|
||||
"""Gross USD cents (RevenueCat ``price`` is USD), rounded down, never negative."""
|
||||
price = _decimal(event.get("price")) or Decimal(0)
|
||||
return int((abs(price) * 100).to_integral_value(rounding=ROUND_FLOOR))
|
||||
|
||||
|
||||
def net_cents(event: dict) -> int:
|
||||
"""USD cents after the store's cut: price × takehome_percentage (default 0.85), rounded down."""
|
||||
price = _decimal(event.get("price")) or Decimal(0)
|
||||
takehome = _decimal(event.get("takehome_percentage"))
|
||||
if takehome is None:
|
||||
takehome = DEFAULT_TAKEHOME
|
||||
return int((abs(price) * 100 * takehome).to_integral_value(rounding=ROUND_FLOOR))
|
||||
|
||||
|
||||
class IapService:
|
||||
def __init__(self, db, user_service, referral_service=None, transaction_runner=None):
|
||||
self.db = db
|
||||
self.user_service = user_service
|
||||
self._referral_service = referral_service
|
||||
# Injectable for unit tests (in-memory Firestore fake).
|
||||
self._transaction_runner = transaction_runner
|
||||
|
||||
def _run_transaction(self, fn):
|
||||
if self._transaction_runner is not None:
|
||||
return self._transaction_runner(fn)
|
||||
try:
|
||||
return run_firestore_transaction(self.db, fn)
|
||||
except google_exceptions.Aborted as exc:
|
||||
# A transactional read hit a lock timeout under contention (the
|
||||
# library retries only commit-time aborts). Nothing was written.
|
||||
raise TransactionContention() from exc
|
||||
|
||||
def _marker_ref(self, key: str):
|
||||
return self.db.collection(PROCESSED_TRANSACTIONS_COLLECTION).document(key)
|
||||
|
||||
def _payment_ref(self, key: str):
|
||||
return self.db.collection(STORE_PAYMENTS_COLLECTION).document(key)
|
||||
|
||||
# ------------------------------------------------------------------ entry
|
||||
|
||||
def handle_event(self, event: dict) -> IapResult:
|
||||
"""Apply one RevenueCat event (the ``event`` object of the webhook body)."""
|
||||
event_type = event.get("type")
|
||||
source = STORE_SOURCES.get(event.get("store") or "")
|
||||
transaction_id = event.get("transaction_id")
|
||||
if event_type not in PURCHASE_EVENT_TYPES | REFUND_EVENT_TYPES:
|
||||
return IapResult("ignored")
|
||||
if not source or not transaction_id:
|
||||
logger.info(
|
||||
f"RevenueCat {event_type} ignored: store={event.get('store')!r} "
|
||||
f"transaction={transaction_id!r}"
|
||||
)
|
||||
return IapResult("ignored")
|
||||
|
||||
found = package_for_product(event.get("product_id"))
|
||||
if not found:
|
||||
logger.warning(
|
||||
f"RevenueCat {event_type} for unknown product {event.get('product_id')!r} "
|
||||
f"({source} transaction {transaction_id}): no credits changed"
|
||||
)
|
||||
return IapResult("unknown_product")
|
||||
|
||||
key = f"{event.get('store')}:{transaction_id}"
|
||||
if event_type in PURCHASE_EVENT_TYPES:
|
||||
return self._grant(event, key, source, *found)
|
||||
if not is_refund(event):
|
||||
logger.warning(
|
||||
f"RevenueCat {event_type} {key} is not a refund "
|
||||
f"(cancel_reason={event.get('cancel_reason')!r}, price={event.get('price')!r}): no credits changed"
|
||||
)
|
||||
return IapResult("ignored")
|
||||
return self._refund(event, key, source)
|
||||
|
||||
# ------------------------------------------------------------------ grant
|
||||
|
||||
def _find_user(self, event: dict):
|
||||
candidates = [event.get("app_user_id"), event.get("original_app_user_id")]
|
||||
candidates += list(event.get("aliases") or [])
|
||||
seen = set()
|
||||
for app_user_id in candidates:
|
||||
if not app_user_id or app_user_id in seen or app_user_id.startswith(ANONYMOUS_ID_PREFIX):
|
||||
continue
|
||||
seen.add(app_user_id)
|
||||
user = self.user_service.find_by_app_user_id(app_user_id)
|
||||
if user:
|
||||
return user
|
||||
return None
|
||||
|
||||
def _grant(self, event: dict, key: str, source: str, package_id: str, package: dict) -> IapResult:
|
||||
user = self._find_user(event)
|
||||
user_ref = self.user_service.get_user_doc_ref(user.email.lower()) if user else None
|
||||
if user_ref is None:
|
||||
return self._unmatched_purchase(event, key, source, package_id, package)
|
||||
|
||||
email = user.email.lower()
|
||||
credits = int(package["credits"])
|
||||
# Sandbox (TestFlight / Play test) purchases grant but are not real spend.
|
||||
spent_cents = 0 if _is_sandbox(event) else price_cents(event)
|
||||
marker_ref = self._marker_ref(key)
|
||||
refund_ref = self._marker_ref(f"{key}:refund")
|
||||
|
||||
def _txn(transaction):
|
||||
if marker_ref.get(transaction=transaction).exists:
|
||||
return IapResult("duplicate", email=email)
|
||||
if refund_ref.get(transaction=transaction).exists:
|
||||
# The refund arrived first (out-of-order delivery): never grant.
|
||||
return IapResult("ignored", email=email)
|
||||
snap = user_ref.get(transaction=transaction)
|
||||
data = snap.to_dict() if snap.exists else None
|
||||
if data is None:
|
||||
return IapResult("unknown_user", email=email) # deleted since lookup; nothing written
|
||||
balance = int(data.get("credits") or 0) + credits
|
||||
entry = CreditTransaction(
|
||||
id=str(uuid.uuid4()), amount=credits, reason=PURCHASE_REASON,
|
||||
).model_dump(mode="json")
|
||||
history = list(data.get("credit_transactions") or [])[-(MAX_CREDIT_TRANSACTIONS - 1):] + [entry]
|
||||
transaction.create(marker_ref, {
|
||||
"kind": "purchase",
|
||||
"store": event.get("store"),
|
||||
"transaction_id": event.get("transaction_id"),
|
||||
"product_id": event.get("product_id"),
|
||||
"package_id": package_id,
|
||||
"credits": credits,
|
||||
"total_spent_cents": spent_cents,
|
||||
"email": email,
|
||||
"app_user_id": event.get("app_user_id"),
|
||||
"created_at": datetime.utcnow(),
|
||||
})
|
||||
transaction.update(user_ref, {
|
||||
"credits": balance,
|
||||
"credit_transactions": history,
|
||||
"total_spent": int(data.get("total_spent") or 0) + spent_cents,
|
||||
"updated_at": datetime.utcnow(),
|
||||
})
|
||||
return IapResult("granted", credits=balance, email=email)
|
||||
|
||||
result = self._run_transaction_once(_txn, email)
|
||||
if result.action == "unknown_user":
|
||||
return self._unmatched_purchase(event, key, source, package_id, package)
|
||||
if result.action == "ignored":
|
||||
logger.warning(f"RevenueCat purchase {key} for {email} was already refunded: no credits granted")
|
||||
return result
|
||||
if result.action != "granted":
|
||||
logger.info(f"RevenueCat purchase {key} already processed (duplicate delivery)")
|
||||
return result
|
||||
|
||||
logger.info(f"IAP: granted {credits} credits to {email} ({key}); balance {result.credits}")
|
||||
self._write_payment(key, event, source, package_id, package, email=email, unmatched=False)
|
||||
self._record_referral_earning(event, key, source, email)
|
||||
return result
|
||||
|
||||
def _unmatched_purchase(self, event, key, source, package_id, package) -> IapResult:
|
||||
# A customer paid and got nothing: actionable (ERROR alerts). Match the
|
||||
# account by hand, grant the credits, and fix the app's RevenueCat login.
|
||||
logger.error(
|
||||
f"IAP purchase not credited: no gen account for app_user_id {event.get('app_user_id')!r} "
|
||||
f"(store {event.get('store')}, transaction {event.get('transaction_id')}, "
|
||||
f"product {event.get('product_id')}). Recorded as unmatched in store_payments/{key}; "
|
||||
f"grant the credits manually once the account is found."
|
||||
)
|
||||
self._write_payment(key, event, source, package_id, package, email=None, unmatched=True)
|
||||
return IapResult("unknown_user")
|
||||
|
||||
# ----------------------------------------------------------------- refund
|
||||
|
||||
def _refund(self, event: dict, key: str, source: str) -> IapResult:
|
||||
purchase_ref = self._marker_ref(key)
|
||||
refund_ref = self._marker_ref(f"{key}:refund")
|
||||
|
||||
def _txn(transaction):
|
||||
if refund_ref.get(transaction=transaction).exists:
|
||||
return IapResult("duplicate")
|
||||
marker = {
|
||||
"kind": "refund",
|
||||
"store": event.get("store"),
|
||||
"transaction_id": event.get("transaction_id"),
|
||||
"product_id": event.get("product_id"),
|
||||
"created_at": datetime.utcnow(),
|
||||
}
|
||||
purchase_snap = purchase_ref.get(transaction=transaction)
|
||||
if not purchase_snap.exists:
|
||||
# Refund before (or without) a grant: leave a tombstone so a late
|
||||
# purchase delivery never grants.
|
||||
transaction.create(refund_ref, {**marker, "debited": False, "reason": "no_grant"})
|
||||
return IapResult("ignored")
|
||||
purchase = purchase_snap.to_dict()
|
||||
email = purchase["email"]
|
||||
if str(email).startswith("deleted:"):
|
||||
# The buyer deleted their account (marker anonymised): never debit
|
||||
# whoever holds that email now.
|
||||
transaction.create(refund_ref, {**marker, "email": email, "debited": False,
|
||||
"unmatched": True, "reason": "account_deleted"})
|
||||
return IapResult("ignored", email=email)
|
||||
credits = int(purchase["credits"])
|
||||
user_ref = self.user_service.get_user_doc_ref(email)
|
||||
snap = user_ref.get(transaction=transaction) if user_ref is not None else None
|
||||
data = snap.to_dict() if snap is not None and snap.exists else None
|
||||
if data is None:
|
||||
# Account deleted since the purchase: nothing to debit (and an
|
||||
# error here would make RevenueCat retry forever).
|
||||
transaction.create(refund_ref, {**marker, "email": email, "debited": False,
|
||||
"reason": "account_deleted"})
|
||||
return IapResult("ignored", email=email)
|
||||
balance = int(data.get("credits") or 0) - credits # may go negative
|
||||
entry = CreditTransaction(
|
||||
id=str(uuid.uuid4()), amount=-credits, reason=REFUND_REASON,
|
||||
).model_dump(mode="json")
|
||||
history = list(data.get("credit_transactions") or [])[-(MAX_CREDIT_TRANSACTIONS - 1):] + [entry]
|
||||
transaction.create(refund_ref, {**marker, "credits": credits, "email": email, "debited": True})
|
||||
spent = int(purchase.get("total_spent_cents") or 0)
|
||||
transaction.update(user_ref, {
|
||||
"credits": balance,
|
||||
"credit_transactions": history,
|
||||
"total_spent": max(0, int(data.get("total_spent") or 0) - spent),
|
||||
"updated_at": datetime.utcnow(),
|
||||
})
|
||||
return IapResult("debited", credits=balance, email=email)
|
||||
|
||||
result = self._run_transaction_once(_txn, None)
|
||||
if result.action == "ignored":
|
||||
logger.warning(
|
||||
f"RevenueCat refund {key}: no granted purchase or account on record "
|
||||
f"({result.email or 'no purchase'}): nothing debited"
|
||||
)
|
||||
elif result.action == "duplicate":
|
||||
logger.info(f"RevenueCat refund {key} already processed (duplicate delivery)")
|
||||
else:
|
||||
logger.info(f"IAP: refund {key} debited {result.email}; balance {result.credits}")
|
||||
if result.action in ("debited", "ignored"):
|
||||
self._mark_payment_refunded(key, event)
|
||||
return result
|
||||
|
||||
# ---------------------------------------------------------------- helpers
|
||||
|
||||
def _run_transaction_once(self, fn, email: Optional[str]) -> IapResult:
|
||||
try:
|
||||
return self._run_transaction(fn)
|
||||
except google_exceptions.AlreadyExists:
|
||||
# A concurrent delivery created the marker between our read and commit.
|
||||
return IapResult("duplicate", email=email)
|
||||
|
||||
def _write_payment(self, key, event, source, package_id, package, *, email, unmatched) -> None:
|
||||
gross = price_cents(event)
|
||||
net = net_cents(event)
|
||||
try:
|
||||
self._payment_ref(key).set({
|
||||
"payment_id": key,
|
||||
"source": source,
|
||||
"store": event.get("store"),
|
||||
"transaction_id": event.get("transaction_id"),
|
||||
"product_id": event.get("product_id"),
|
||||
"package_id": package_id,
|
||||
"credits_granted": 0 if unmatched else int(package["credits"]),
|
||||
"product_description": package.get("name"),
|
||||
"order_type": f"{source}_credit_purchase",
|
||||
"customer_email": email or "",
|
||||
"app_user_id": event.get("app_user_id"),
|
||||
"unmatched": unmatched,
|
||||
"amount_total": gross,
|
||||
"currency": "usd",
|
||||
"purchased_currency": event.get("currency"),
|
||||
"price_in_purchased_currency": event.get("price_in_purchased_currency"),
|
||||
"country_code": event.get("country_code"),
|
||||
"takehome_percentage": event.get("takehome_percentage"),
|
||||
"store_fee": gross - net,
|
||||
"net_amount": net,
|
||||
"status": "succeeded",
|
||||
"refund_amount": 0,
|
||||
"refunded_at": None,
|
||||
"is_test": _is_sandbox(event),
|
||||
"created_at": _event_time(event),
|
||||
"processed_at": datetime.utcnow(),
|
||||
})
|
||||
except Exception:
|
||||
logger.warning(f"Failed to store store_payments/{key}", exc_info=True)
|
||||
|
||||
def _mark_payment_refunded(self, key, event) -> None:
|
||||
try:
|
||||
ref = self._payment_ref(key)
|
||||
snap = ref.get()
|
||||
if not snap.exists:
|
||||
return # no payment on record: never create a phantom one
|
||||
refund = (snap.to_dict() or {}).get("amount_total")
|
||||
ref.set({
|
||||
"status": "refunded",
|
||||
"refund_amount": refund if refund is not None else price_cents(event),
|
||||
"refunded_at": datetime.utcnow(),
|
||||
}, merge=True)
|
||||
except Exception:
|
||||
logger.warning(f"Failed to mark store_payments/{key} refunded", exc_info=True)
|
||||
|
||||
def _record_referral_earning(self, event, key, source, email) -> None:
|
||||
if _is_sandbox(event):
|
||||
return
|
||||
amount = net_cents(event)
|
||||
if amount <= 0:
|
||||
return
|
||||
try:
|
||||
referral = self._referral_service
|
||||
if referral is None:
|
||||
from backend.services.referral_service import get_referral_service
|
||||
referral = get_referral_service()
|
||||
earning = referral.record_earning(
|
||||
referred_email=email,
|
||||
source_key=key,
|
||||
purchase_amount_cents=amount,
|
||||
source=source,
|
||||
)
|
||||
if earning:
|
||||
logger.info(
|
||||
f"Referral earning ${earning['earning_amount_cents'] / 100:.2f} "
|
||||
f"for {earning['referrer_email']} ({key})"
|
||||
)
|
||||
except Exception:
|
||||
logger.warning(f"Referral earning recording failed for {key}", exc_info=True)
|
||||
|
||||
|
||||
def _event_time(event: dict) -> datetime:
|
||||
ms = event.get("purchased_at_ms") or event.get("event_timestamp_ms")
|
||||
try:
|
||||
return datetime.utcfromtimestamp(int(ms) / 1000) if ms else datetime.utcnow()
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
def get_iap_service() -> IapService:
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
user_service = get_user_service()
|
||||
return IapService(user_service.db, user_service)
|
||||
+110
-10
@@ -37,6 +37,24 @@ PREP_PHASE_STATUSES = frozenset({
|
||||
})
|
||||
|
||||
|
||||
# state_data flag: this run's failure push was sent (see _failure_already_notified).
|
||||
FAILURE_PUSH_SENT_KEY = 'failure_push_sent'
|
||||
|
||||
|
||||
def _cloud_run_retry_pending(state_data: Optional[Dict[str, Any]]) -> bool:
|
||||
"""True if the audio-download worker recorded an unexpired Cloud Run auto-retry marker."""
|
||||
pending = (state_data or {}).get('cloud_run_retry_pending')
|
||||
if not isinstance(pending, dict) or not pending.get('expires_at'):
|
||||
return False
|
||||
try:
|
||||
expires_at = datetime.fromisoformat(str(pending['expires_at']).replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
||||
return expires_at > datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _mask_email(email: str) -> str:
|
||||
"""Mask email for logging to protect PII. Shows first char + domain."""
|
||||
if not email or "@" not in email:
|
||||
@@ -695,6 +713,20 @@ class JobManager:
|
||||
action_type = "instrumental"
|
||||
self._send_push_notification(job, action_type)
|
||||
|
||||
# Failure: push only (no email / idle reminder). AWAITING_AUDIO_SELECTION
|
||||
# is the normal interactive search step, not a problem, so it never pushes.
|
||||
elif new_status == JobStatus.FAILED:
|
||||
if _cloud_run_retry_pending(job.state_data):
|
||||
logger.info(f"Job {job_id}: failure push skipped, Cloud Run auto-retry pending")
|
||||
return
|
||||
from backend.services.admin_rerender_service import suppress_customer_notifications
|
||||
if suppress_customer_notifications(job):
|
||||
logger.info(f"Job {job_id}: failure push suppressed (quiet re-render)")
|
||||
return
|
||||
self._send_push_notification(job, "failed")
|
||||
# Lets a second worker failing the same run skip a duplicate push.
|
||||
self.firestore.update_job(job_id, {f'state_data.{FAILURE_PUSH_SENT_KEY}': True})
|
||||
|
||||
except Exception as e:
|
||||
# Never let notification failures affect job processing
|
||||
logger.error(f"Error triggering notifications for job {job_id}: {e}")
|
||||
@@ -844,15 +876,43 @@ class JobManager:
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to schedule idle reminder for job {job.job_id}: {e}")
|
||||
|
||||
# action_type -> (Expo kind, mobile deep-link path, i18n key prefix under pushNotifications)
|
||||
_EXPO_ROUTES = {
|
||||
"complete": ("ready", "/job/{id}", ("videoReadyTitle", "videoReadyBody")),
|
||||
"lyrics": ("review", "/review/{id}", ("reviewLyricsTitle", "reviewLyricsBody")),
|
||||
"duration_confirm": ("review", "/job/duration/{id}", ("confirmDurationTitle", "confirmDurationBody")),
|
||||
"audio_edit": ("review", "/job/{id}", ("reviewLyricsTitle", "reviewLyricsBody")),
|
||||
"instrumental": ("review", "/job/{id}", ("selectInstrumentalTitle", "selectInstrumentalBody")),
|
||||
"failed": ("problems", "/job/{id}", ("jobProblemTitle", "jobProblemBody")),
|
||||
}
|
||||
|
||||
def _send_expo_push(self, job: Job, action_type: str, stalled_download: bool = False) -> None:
|
||||
"""Send the mobile-app (Expo) push for a job event. Blocking; call from a worker thread."""
|
||||
from backend.i18n import t
|
||||
from backend.services.expo_push_service import get_expo_push_service
|
||||
|
||||
kind, path, (title_key, body_key) = self._EXPO_ROUTES[action_type]
|
||||
if stalled_download:
|
||||
body_key = "jobStalledBody"
|
||||
locale = "en" # like Web Push: job.locale is an admin signal, not a notification preference
|
||||
get_expo_push_service().send(
|
||||
job.user_email,
|
||||
kind,
|
||||
t(locale, f"pushNotifications.{title_key}"),
|
||||
t(locale, f"pushNotifications.{body_key}", title=job.title or "", artist=job.artist or ""),
|
||||
path.format(id=job.job_id),
|
||||
)
|
||||
|
||||
def _send_push_notification(self, job: Job, action_type: str) -> None:
|
||||
"""
|
||||
Send a push notification for job state changes.
|
||||
Send push notifications (Web Push and mobile Expo push) for job state changes.
|
||||
|
||||
Fire-and-forget - failures don't affect job processing.
|
||||
|
||||
Args:
|
||||
job: Job object
|
||||
action_type: Type of notification ("lyrics", "instrumental", or "complete")
|
||||
action_type: "complete", "lyrics", "instrumental", "audio_edit",
|
||||
"duration_confirm" or "failed"
|
||||
"""
|
||||
import asyncio
|
||||
import threading
|
||||
@@ -861,11 +921,9 @@ class JobManager:
|
||||
from backend.services.push_notification_service import get_push_notification_service
|
||||
|
||||
push_service = get_push_notification_service()
|
||||
web_enabled = push_service.is_enabled()
|
||||
|
||||
# Skip if push notifications not enabled
|
||||
if not push_service.is_enabled():
|
||||
logger.debug("Push notifications not enabled, skipping")
|
||||
return
|
||||
stalled = bool((job.error_details or {}).get("code") == "audio_download_stalled")
|
||||
|
||||
# Build job dict for notification service
|
||||
job_dict = {
|
||||
@@ -874,13 +932,29 @@ class JobManager:
|
||||
"artist": job.artist,
|
||||
"title": job.title,
|
||||
"tenant_id": job.tenant_id or None,
|
||||
"stalled_download": stalled,
|
||||
}
|
||||
|
||||
async def send_notification():
|
||||
if action_type == "complete":
|
||||
await push_service.send_completion_notification(job_dict)
|
||||
else:
|
||||
await push_service.send_blocking_notification(job_dict, action_type)
|
||||
# Each channel is isolated so one failing cannot stop the other.
|
||||
if web_enabled:
|
||||
try:
|
||||
if action_type == "complete":
|
||||
await push_service.send_completion_notification(job_dict)
|
||||
elif action_type == "failed":
|
||||
await push_service.send_problem_notification(job_dict)
|
||||
else:
|
||||
await push_service.send_blocking_notification(job_dict, action_type)
|
||||
except Exception as e:
|
||||
logger.error(f"Web push failed for job {job.job_id}: {e}")
|
||||
# The mobile app is Nomad-only: a white-label tenant's job never
|
||||
# reaches it (Web Push above is already tenant-scoped).
|
||||
if job.tenant_id:
|
||||
return
|
||||
try:
|
||||
await asyncio.to_thread(self._send_expo_push, job, action_type, stalled)
|
||||
except Exception as e:
|
||||
logger.error(f"Expo push failed for job {job.job_id}: {e}")
|
||||
|
||||
# Try to get existing event loop, create new one if none exists
|
||||
try:
|
||||
@@ -1137,6 +1211,8 @@ class JobManager:
|
||||
True if successful
|
||||
"""
|
||||
try:
|
||||
already_notified = self._failure_already_notified(job_id)
|
||||
|
||||
# Update error fields
|
||||
self.update_job(job_id, {
|
||||
'error_message': error_message,
|
||||
@@ -1157,6 +1233,9 @@ class JobManager:
|
||||
if job:
|
||||
self._refund_credit_for_job(job_id, job, reason="job_failed")
|
||||
|
||||
if not already_notified:
|
||||
self._trigger_state_notifications(job_id, JobStatus.FAILED)
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Error marking job {job_id} as failed: {e}")
|
||||
@@ -1466,6 +1545,7 @@ class JobManager:
|
||||
if error_details:
|
||||
updates['error_details'] = error_details
|
||||
|
||||
already_notified = self._failure_already_notified(job_id)
|
||||
self.firestore.update_job_status(
|
||||
job_id=job_id,
|
||||
status=JobStatus.FAILED,
|
||||
@@ -1474,6 +1554,26 @@ class JobManager:
|
||||
**updates
|
||||
)
|
||||
logger.error(f"Job {job_id} failed: {error_message}")
|
||||
if not already_notified:
|
||||
self._trigger_state_notifications(job_id, JobStatus.FAILED)
|
||||
|
||||
def _failure_already_notified(self, job_id: str) -> bool:
|
||||
"""True if this run already failed AND its failure push went out.
|
||||
|
||||
Then a second worker failing the same job must not push again. A job that
|
||||
is FAILED without the marker (e.g. a Cloud Run auto-retry attempt, which
|
||||
runs while the job is still FAILED and whose first failure skipped the
|
||||
push) still pushes. A manual retry moves the job out of FAILED, so a later
|
||||
failure pushes again. Best-effort: a read error counts as "not notified".
|
||||
"""
|
||||
try:
|
||||
job = self.get_job(job_id)
|
||||
return bool(
|
||||
job and job.status == JobStatus.FAILED
|
||||
and (job.state_data or {}).get(FAILURE_PUSH_SENT_KEY)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def increment_retry_count(self, job_id: str) -> int:
|
||||
"""
|
||||
|
||||
@@ -271,3 +271,26 @@ class LoginCodeStore:
|
||||
|
||||
ref.update({"code_hash": None, "used_at": _now()})
|
||||
return VerifyOutcome.OK, after
|
||||
|
||||
def verify_fixed_code(self, email: str, code: str, fixed_code: str) -> tuple[str, Optional[dict]]:
|
||||
"""Verify ``code`` against a fixed, operator-configured code (App Review demo).
|
||||
|
||||
Same attempt accounting as :meth:`verify_code` (atomic increment BEFORE the
|
||||
comparison, lockout above MAX_VERIFY_ATTEMPTS) on the same per-email record,
|
||||
but the code is reusable (reviewers sign in repeatedly): a success resets the
|
||||
counter. A locked-out record stays locked until a new code is issued
|
||||
(``issue_code`` resets attempts). Returns (outcome, record-or-{}).
|
||||
"""
|
||||
email = email.strip().lower()
|
||||
ref = self.code_ref(email)
|
||||
if not ref.get().exists:
|
||||
ref.set({"email": email, "attempts": 0}, merge=True)
|
||||
ref.update({"attempts": Increment(1)})
|
||||
after = ref.get().to_dict() or {}
|
||||
if int(after.get("attempts") or 0) > MAX_VERIFY_ATTEMPTS:
|
||||
return VerifyOutcome.TOO_MANY_ATTEMPTS, None
|
||||
candidate = (code or "").strip()
|
||||
if not (fixed_code and hmac.compare_digest(candidate.encode("utf-8"), fixed_code.encode("utf-8"))):
|
||||
return VerifyOutcome.INVALID, None
|
||||
ref.update({"attempts": 0})
|
||||
return VerifyOutcome.OK, after
|
||||
@@ -13,7 +13,8 @@ our cloud egress has no business hammering it (see
|
||||
Queries go through the BigQuery REST ``jobs.query`` endpoint (httpx + ADC) so
|
||||
the backend doesn't need the BigQuery client library. Every table read is
|
||||
clustered on the column we filter by, so lookups bill MB, not GB:
|
||||
- artists: ``mb_artists_normalized`` (~0.3 GB — small, unclustered)
|
||||
- artists: ``mb_artists_normalized`` + ``musicbrainz.artist_alias`` (~0.4 GB, full
|
||||
scan: matching folds accents per row, so there is no column to cluster on)
|
||||
- albums: ``mb_artist_credit_artists`` (artist_mbid) → ``mb_release_groups``
|
||||
- editions: ``mb_releases`` (release_group_mbid)
|
||||
- tracks: ``mb_release_tracks`` (release_group_mbid, release_mbid)
|
||||
@@ -25,6 +26,7 @@ import asyncio
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
import unicodedata
|
||||
from collections import Counter
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
@@ -34,6 +36,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
BQ_PROJECT = "nomadkaraoke"
|
||||
MB_DATASET = f"{BQ_PROJECT}.karaoke_decide"
|
||||
# Full MusicBrainz table mirror (same weekly refresh); used for artist aliases.
|
||||
MB_RAW_DATASET = f"{BQ_PROJECT}.musicbrainz"
|
||||
_BQ_QUERY_URL = f"https://bigquery.googleapis.com/bigquery/v2/projects/{BQ_PROJECT}/queries"
|
||||
_BQ_SCOPES = ["https://www.googleapis.com/auth/bigquery.readonly"]
|
||||
_CACHE_TTL_S = 600 # 10 min — album metadata is effectively static
|
||||
@@ -118,11 +122,35 @@ def classify_extra(title: str, disambiguation: str = "") -> tuple[bool, str]:
|
||||
return False, ""
|
||||
|
||||
|
||||
def normalize_name(s: str) -> str:
|
||||
"""Python twin of karaoke-decide's ``norm()`` SQL (``mb_artists*.name_normalized``):
|
||||
lowercase, every char outside ``[a-z0-9 ]`` → space, spaces collapsed, trimmed.
|
||||
Not accent-folded, matching those columns."""
|
||||
return re.sub(r" +", " ", re.sub(r"[^a-z0-9 ]", " ", (s or "").lower())).strip()
|
||||
# Accent- and script-aware search key: NFKD, drop combining marks, lowercase,
|
||||
# fold the Latin letters NFKD leaves alone (ø ł đ ı ß æ œ þ), then everything
|
||||
# that isn't a letter or digit in any script -> space, collapsed. "Maxïmo Park"
|
||||
# and "maximo park" share a key, and "Мумий Тролль" / "宇多田ヒカル" keep theirs
|
||||
# (decide's ``norm()`` / ``name_normalized`` maps those to "max mo park" and "").
|
||||
# SEARCH_KEY_SQL is the matching function; search_key only screens blank queries.
|
||||
_FOLD_MULTI = (("ß", "ss"), ("æ", "ae"), ("œ", "oe"), ("þ", "th"))
|
||||
_FOLD_SINGLE = str.maketrans("øłđı", "oldi")
|
||||
|
||||
SEARCH_KEY_SQL = r"""
|
||||
CREATE TEMP FUNCTION search_key(s STRING) AS (
|
||||
TRIM(REGEXP_REPLACE(REGEXP_REPLACE(
|
||||
REPLACE(REPLACE(REPLACE(REPLACE(
|
||||
TRANSLATE(LOWER(REGEXP_REPLACE(NORMALIZE(s, NFKD), r'\pM', '')), 'øłđı', 'oldi'),
|
||||
'ß', 'ss'), 'æ', 'ae'), 'œ', 'oe'), 'þ', 'th'),
|
||||
r'[^\p{L}\p{N} ]', ' '), r' +', ' '))
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def search_key(s: str) -> str:
|
||||
"""Python twin of ``SEARCH_KEY_SQL``."""
|
||||
decomposed = unicodedata.normalize("NFKD", s or "")
|
||||
t = "".join(ch for ch in decomposed if not unicodedata.category(ch).startswith("M"))
|
||||
t = t.lower().translate(_FOLD_SINGLE)
|
||||
for src, dst in _FOLD_MULTI:
|
||||
t = t.replace(src, dst)
|
||||
t = "".join(ch if ch == " " or unicodedata.category(ch)[0] in "LN" else " " for ch in t)
|
||||
return re.sub(r" +", " ", t).strip()
|
||||
|
||||
|
||||
def _decode_value(field: Dict[str, Any], value: Any) -> Any:
|
||||
@@ -208,28 +236,50 @@ class MusicBrainzService:
|
||||
# -- Public API --------------------------------------------------------
|
||||
|
||||
async def search_artists(self, name: str, limit: int = 8) -> List[Dict[str, Any]]:
|
||||
"""Search artists by name: exact (incl. a leading "The") → prefix → substring,
|
||||
then by popularity (Spotify, 50 when unmapped)."""
|
||||
q = normalize_name(name)
|
||||
if not q:
|
||||
"""Search artists by name or MusicBrainz alias, accent- and script-insensitive.
|
||||
|
||||
Ranks exact (incl. a leading "The") → prefix → substring, a primary-name
|
||||
hit before an alias hit, then popularity (Spotify, 50 when unmapped).
|
||||
``alias`` is set when only an alias matched (e.g. "Hikaru Utada" for
|
||||
宇多田ヒカル), so the UI can say why the row is there.
|
||||
"""
|
||||
if not search_key(name):
|
||||
return []
|
||||
rows = await self._query(
|
||||
f"""
|
||||
SELECT artist_mbid, artist_name, disambiguation, artist_type, area_name, match_rank
|
||||
FROM (
|
||||
SELECT *,
|
||||
SEARCH_KEY_SQL
|
||||
+ f"""
|
||||
WITH names AS (
|
||||
SELECT artist_mbid, search_key(artist_name) AS key, CAST(NULL AS STRING) AS alias
|
||||
FROM `{MB_DATASET}.mb_artists_normalized`
|
||||
UNION ALL
|
||||
SELECT ar.gid, search_key(al.name), al.name
|
||||
FROM `{MB_RAW_DATASET}.artist_alias` al
|
||||
JOIN `{MB_RAW_DATASET}.artist` ar ON ar.id = al.artist
|
||||
),
|
||||
hits AS (
|
||||
SELECT artist_mbid, alias,
|
||||
CASE
|
||||
WHEN name_normalized = @q OR name_normalized = CONCAT('the ', @q) THEN 0
|
||||
WHEN STARTS_WITH(name_normalized, @q) THEN 1
|
||||
WHEN key = search_key(@q) OR key = CONCAT('the ', search_key(@q)) THEN 0
|
||||
WHEN STARTS_WITH(key, search_key(@q)) THEN 1
|
||||
ELSE 2
|
||||
END AS match_rank
|
||||
FROM `{MB_DATASET}.mb_artists_normalized`
|
||||
WHERE STRPOS(name_normalized, @q) > 0
|
||||
FROM names
|
||||
WHERE STRPOS(key, search_key(@q)) > 0
|
||||
),
|
||||
best AS (
|
||||
SELECT artist_mbid,
|
||||
ARRAY_AGG(STRUCT(match_rank, alias) ORDER BY match_rank, alias IS NOT NULL LIMIT 1)[OFFSET(0)] AS b
|
||||
FROM hits
|
||||
GROUP BY artist_mbid
|
||||
)
|
||||
ORDER BY match_rank, popularity DESC, artist_name
|
||||
SELECT a.artist_mbid, a.artist_name, a.disambiguation, a.artist_type, a.area_name,
|
||||
best.b.match_rank AS match_rank, best.b.alias AS alias
|
||||
FROM best
|
||||
JOIN `{MB_DATASET}.mb_artists_normalized` a USING (artist_mbid)
|
||||
ORDER BY match_rank, a.popularity DESC, a.artist_name
|
||||
LIMIT {int(limit)}
|
||||
""",
|
||||
{"q": q},
|
||||
{"q": name.strip()},
|
||||
)
|
||||
return [
|
||||
{
|
||||
@@ -238,6 +288,7 @@ class MusicBrainzService:
|
||||
"disambiguation": r.get("disambiguation") or "",
|
||||
"type": r.get("artist_type"),
|
||||
"country": r.get("area_name"),
|
||||
"alias": r.get("alias"),
|
||||
"score": 100 - 10 * r["match_rank"],
|
||||
}
|
||||
for r in rows
|
||||
|
||||
@@ -13,7 +13,7 @@ from google.cloud.firestore_v1 import ArrayRemove
|
||||
from pywebpush import webpush, WebPushException
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.models.user import User, PushSubscription
|
||||
from backend.models.user import User, PushSubscription, effective_push_prefs
|
||||
from backend.i18n import t
|
||||
|
||||
|
||||
@@ -89,7 +89,8 @@ class PushNotificationService:
|
||||
body: str,
|
||||
url: str = "/app/",
|
||||
tag: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
tenant_id: Optional[str] = None,
|
||||
kind: Optional[str] = None,
|
||||
) -> int:
|
||||
"""Async entry point: runs ``send_push_sync`` in a worker thread.
|
||||
|
||||
@@ -99,7 +100,7 @@ class PushNotificationService:
|
||||
``push_notification_service.py:166 in send_push`` with a request waiting).
|
||||
"""
|
||||
return await asyncio.to_thread(
|
||||
self.send_push_sync, user_email, title, body, url, tag, tenant_id
|
||||
self.send_push_sync, user_email, title, body, url, tag, tenant_id, kind
|
||||
)
|
||||
|
||||
def send_push_sync(
|
||||
@@ -109,7 +110,8 @@ class PushNotificationService:
|
||||
body: str,
|
||||
url: str = "/app/",
|
||||
tag: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
tenant_id: Optional[str] = None,
|
||||
kind: Optional[str] = None,
|
||||
) -> int:
|
||||
"""
|
||||
Send a push notification to a user's subscribed devices for a specific tenant.
|
||||
@@ -125,6 +127,8 @@ class PushNotificationService:
|
||||
tag: Optional tag for notification grouping (replaces notifications with same tag)
|
||||
tenant_id: Tenant scope - only send to subscriptions for this tenant
|
||||
(None or "" = consumer/default portal)
|
||||
kind: Notification type ("ready", "review" or "problems"). When the user
|
||||
turned that type off (``push_prefs``), nothing is sent.
|
||||
|
||||
Returns:
|
||||
Number of notifications successfully sent
|
||||
@@ -140,6 +144,9 @@ class PushNotificationService:
|
||||
return 0
|
||||
|
||||
user_data = user_doc.to_dict()
|
||||
if kind and not effective_push_prefs(user_data.get("push_prefs")).get(kind, True):
|
||||
logger.debug(f"Web push '{kind}' suppressed by preference for {user_email}")
|
||||
return 0
|
||||
all_subscriptions = user_data.get("push_subscriptions", [])
|
||||
|
||||
# Filter subscriptions to only those matching the target tenant
|
||||
@@ -290,6 +297,35 @@ class PushNotificationService:
|
||||
url=url,
|
||||
tag=tag,
|
||||
tenant_id=tenant_id,
|
||||
kind="review",
|
||||
)
|
||||
|
||||
async def send_problem_notification(self, job: dict) -> int:
|
||||
"""Send notification when a job failed."""
|
||||
user_email = job.get("user_email")
|
||||
if not user_email:
|
||||
return 0
|
||||
|
||||
job_id = job.get("job_id", "unknown")
|
||||
artist = job.get("artist", "Unknown Artist")
|
||||
title = job.get("title", "Unknown Title")
|
||||
locale = job.get("locale") or "en"
|
||||
|
||||
if job.get("stalled_download"):
|
||||
notif_title = t(locale, "pushNotifications.jobProblemTitle")
|
||||
notif_body = t(locale, "pushNotifications.jobStalledBody", title=title, artist=artist)
|
||||
else:
|
||||
notif_title = t(locale, "pushNotifications.jobProblemTitle")
|
||||
notif_body = t(locale, "pushNotifications.jobProblemBody", title=title, artist=artist)
|
||||
|
||||
return await self.send_push(
|
||||
user_email=user_email,
|
||||
title=notif_title,
|
||||
body=notif_body,
|
||||
url=f"/app/jobs#/{job_id}",
|
||||
tag=f"problem-{job_id}",
|
||||
tenant_id=job.get("tenant_id") or None,
|
||||
kind="problems",
|
||||
)
|
||||
|
||||
async def send_completion_notification(self, job: dict) -> int:
|
||||
@@ -319,6 +355,7 @@ class PushNotificationService:
|
||||
url=f"/app/?job={job_id}",
|
||||
tag=f"complete-{job_id}",
|
||||
tenant_id=tenant_id,
|
||||
kind="ready",
|
||||
)
|
||||
|
||||
async def add_subscription(
|
||||
|
||||
@@ -446,8 +446,20 @@ class ReferralService:
|
||||
# Earnings
|
||||
# ========================================================================
|
||||
|
||||
def record_earning(self, referred_email: str, stripe_session_id: str, purchase_amount_cents: int) -> Optional[dict]:
|
||||
"""Record a referral earning after a credit purchase."""
|
||||
def record_earning(
|
||||
self,
|
||||
referred_email: str,
|
||||
source_key: str,
|
||||
purchase_amount_cents: int,
|
||||
source: str = "stripe",
|
||||
) -> Optional[dict]:
|
||||
"""Record a referral earning after a credit purchase.
|
||||
|
||||
``source`` is "stripe" (``source_key`` = Stripe checkout session id, stored
|
||||
as ``stripe_session_id``) or "app_store" / "play_store" (``source_key`` =
|
||||
the store payment key, stored as ``store_transaction_id``). Store purchases
|
||||
pass the amount net of the store's commission.
|
||||
"""
|
||||
referred_email = referred_email.lower()
|
||||
|
||||
# Look up the referred user
|
||||
@@ -489,7 +501,9 @@ class ReferralService:
|
||||
referrer_email=link.owner_email,
|
||||
referred_email=referred_email,
|
||||
referral_code=referral_code,
|
||||
stripe_session_id=stripe_session_id,
|
||||
source=source,
|
||||
stripe_session_id=source_key if source == "stripe" else None,
|
||||
store_transaction_id=None if source == "stripe" else source_key,
|
||||
purchase_amount_cents=purchase_amount_cents,
|
||||
earning_amount_cents=earning_amount,
|
||||
)
|
||||
|
||||
@@ -17,6 +17,7 @@ from typing import Optional, Dict, Any, List, Tuple
|
||||
|
||||
import stripe
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.stripe_service import StripeService
|
||||
@@ -25,6 +26,10 @@ from backend.services.stripe_service import StripeService
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STRIPE_PAYMENTS_COLLECTION = "stripe_payments"
|
||||
# In-app (App Store / Play Store) purchases, written by IapService. Same amount
|
||||
# fields as stripe_payments (store_fee in place of stripe_fee) so revenue sums both.
|
||||
STORE_PAYMENTS_COLLECTION = "store_payments"
|
||||
REVENUE_COLLECTIONS = (STRIPE_PAYMENTS_COLLECTION, STORE_PAYMENTS_COLLECTION)
|
||||
STRIPE_WEBHOOK_EVENTS_COLLECTION = "stripe_webhook_events"
|
||||
|
||||
|
||||
@@ -217,6 +222,15 @@ class StripeAdminService:
|
||||
# Revenue Analytics
|
||||
# =========================================================================
|
||||
|
||||
def _revenue_docs(self, cutoff: Optional[datetime]):
|
||||
"""Payment dicts from Stripe and the app stores, optionally created since ``cutoff``."""
|
||||
for name in REVENUE_COLLECTIONS:
|
||||
query = self.db.collection(name)
|
||||
if cutoff is not None:
|
||||
query = query.where(filter=FieldFilter("created_at", ">=", cutoff))
|
||||
for doc in query.stream():
|
||||
yield doc.to_dict()
|
||||
|
||||
def get_revenue_summary(
|
||||
self, days: int = 30, exclude_test: bool = True
|
||||
) -> Dict[str, Any]:
|
||||
@@ -236,12 +250,7 @@ class StripeAdminService:
|
||||
return self._revenue_cache
|
||||
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
query = collection
|
||||
|
||||
if days > 0:
|
||||
cutoff = datetime.utcnow() - timedelta(days=days)
|
||||
query = query.where("created_at", ">=", cutoff)
|
||||
cutoff = datetime.utcnow() - timedelta(days=days) if days > 0 else None
|
||||
|
||||
total_gross = 0
|
||||
total_fees = 0
|
||||
@@ -250,14 +259,13 @@ class StripeAdminService:
|
||||
count = 0
|
||||
by_type: Dict[str, int] = {}
|
||||
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
for data in self._revenue_docs(cutoff):
|
||||
if exclude_test and data.get("is_test"):
|
||||
continue
|
||||
|
||||
amount = data.get("amount_total", 0)
|
||||
total_gross += amount
|
||||
total_fees += data.get("stripe_fee", 0)
|
||||
total_fees += _fee(data)
|
||||
total_net += data.get("net_amount", 0)
|
||||
total_refunds += data.get("refund_amount", 0)
|
||||
count += 1
|
||||
@@ -312,14 +320,11 @@ class StripeAdminService:
|
||||
List of {date, gross, net, fees, count} dicts
|
||||
"""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
cutoff = datetime.utcnow() - timedelta(days=days)
|
||||
query = collection.where("created_at", ">=", cutoff)
|
||||
|
||||
buckets: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
for data in self._revenue_docs(cutoff):
|
||||
if exclude_test and data.get("is_test"):
|
||||
continue
|
||||
|
||||
@@ -346,7 +351,7 @@ class StripeAdminService:
|
||||
|
||||
buckets[key]["gross"] += data.get("amount_total", 0)
|
||||
buckets[key]["net"] += data.get("net_amount", 0)
|
||||
buckets[key]["fees"] += data.get("stripe_fee", 0)
|
||||
buckets[key]["fees"] += _fee(data)
|
||||
buckets[key]["count"] += 1
|
||||
|
||||
result = sorted(buckets.values(), key=lambda x: x["date"])
|
||||
@@ -778,6 +783,11 @@ class StripeAdminService:
|
||||
_stripe_admin_service = None
|
||||
|
||||
|
||||
def _fee(payment: Dict[str, Any]) -> int:
|
||||
"""Processor fee in cents: Stripe's fee, or the app store's commission."""
|
||||
return payment.get("stripe_fee", payment.get("store_fee", 0)) or 0
|
||||
|
||||
|
||||
def get_stripe_admin_service() -> StripeAdminService:
|
||||
"""Get the global Stripe admin service instance."""
|
||||
global _stripe_admin_service
|
||||
|
||||
@@ -27,24 +27,28 @@ UNPARSEABLE_SIGNATURE_HEADER = "Unable to extract timestamp and signatures from
|
||||
CREDIT_PACKAGES = {
|
||||
"1_credit": {
|
||||
"credits": 1,
|
||||
"store_product_id": "nomad_credits_1", # App Store / Play product id
|
||||
"price_cents": 1000, # $10.00
|
||||
"name": "1 Karaoke Credit",
|
||||
"description": "Create 1 professional karaoke video",
|
||||
},
|
||||
"3_credits": {
|
||||
"credits": 3,
|
||||
"store_product_id": "nomad_credits_3", # App Store / Play product id
|
||||
"price_cents": 2400, # $24.00 (20% discount)
|
||||
"name": "3 Karaoke Credits",
|
||||
"description": "Create 3 professional karaoke videos (Save 20%)",
|
||||
},
|
||||
"5_credits": {
|
||||
"credits": 5,
|
||||
"store_product_id": "nomad_credits_5", # App Store / Play product id
|
||||
"price_cents": 3500, # $35.00 (30% discount)
|
||||
"name": "5 Karaoke Credits",
|
||||
"description": "Create 5 professional karaoke videos (Save 30%)",
|
||||
},
|
||||
"10_credits": {
|
||||
"credits": 10,
|
||||
"store_product_id": "nomad_credits_10", # App Store / Play product id
|
||||
"price_cents": 6000, # $60.00 (40% discount)
|
||||
"name": "10 Karaoke Credits",
|
||||
"description": "Create 10 professional karaoke videos (Save 40%)",
|
||||
|
||||
@@ -123,6 +123,38 @@ class UserService:
|
||||
logger.exception(f"Error getting user {email}")
|
||||
return None
|
||||
|
||||
def ensure_app_user_id(self, email: str) -> str:
|
||||
"""Return the user's mobile-app id, minting a UUID4 once.
|
||||
|
||||
Read-then-set-if-absent inside a Firestore transaction, so concurrent
|
||||
callers all end up with the same id.
|
||||
"""
|
||||
import uuid
|
||||
|
||||
doc_ref = self.get_user_doc_ref(email) or self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
|
||||
@firestore.transactional
|
||||
def mint(transaction):
|
||||
snap = doc_ref.get(transaction=transaction)
|
||||
existing = (snap.to_dict() or {}).get("app_user_id") if snap.exists else None
|
||||
if existing:
|
||||
return existing
|
||||
new_id = str(uuid.uuid4())
|
||||
transaction.set(doc_ref, {"app_user_id": new_id}, merge=True)
|
||||
return new_id
|
||||
|
||||
return mint(self.db.transaction())
|
||||
|
||||
def find_by_app_user_id(self, app_user_id: str) -> Optional[User]:
|
||||
"""The user whose mobile-app id (RevenueCat app_user_id) is ``app_user_id``."""
|
||||
if not app_user_id:
|
||||
return None
|
||||
query = self.db.collection(USERS_COLLECTION).where(
|
||||
filter=FieldFilter("app_user_id", "==", app_user_id)
|
||||
).limit(1)
|
||||
results = list(query.stream())
|
||||
return User(**results[0].to_dict()) if results else None
|
||||
|
||||
def get_or_create_user(
|
||||
self,
|
||||
email: str,
|
||||
@@ -533,6 +565,14 @@ class UserService:
|
||||
if txn.reason == "welcome_credit":
|
||||
return False, "already_granted"
|
||||
|
||||
# A self-deleted account's email signing up again gets no second
|
||||
# welcome credit (deleted_users keeps only sha256(email)).
|
||||
from backend.services.account_deletion_service import is_deleted_email
|
||||
if is_deleted_email(self.db, email):
|
||||
self.update_user(email, welcome_credits_granted=True)
|
||||
logger.info("Welcome credit not granted: email belonged to a deleted account")
|
||||
return False, "already_granted"
|
||||
|
||||
# Skip AI evaluation for test emails (e.g. E2E test accounts)
|
||||
# to avoid wasting LLM credits and sending unnecessary denial emails
|
||||
from backend.utils.test_data import is_test_email
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""
|
||||
Emulator integration tests for AccountDeletionService.
|
||||
|
||||
Real Firestore and GCS emulators, so the parts a fake can't prove are real:
|
||||
dotted-path DELETE_FIELD updates on job docs, the ``targets.kjbox`` query behind
|
||||
the kjbox queue, the two-equality made-for-you query, the deleted_users hash
|
||||
lookup, real object deletes, and the deletion_id transaction under concurrency.
|
||||
Only decide, RevenueCat, Apple, Dropbox and job cancellation are faked.
|
||||
Run with: scripts/run-emulator-tests.sh
|
||||
"""
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from google.cloud import firestore, storage
|
||||
|
||||
from backend.services.account_deletion_service import (
|
||||
AccountDeletionService,
|
||||
email_sha256,
|
||||
is_deleted_email,
|
||||
)
|
||||
|
||||
from .conftest import emulators_running
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_running(),
|
||||
reason="GCP emulators not running. Start with: scripts/start-emulators.sh",
|
||||
)
|
||||
|
||||
JOBS = "account-deletion-test-jobs"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
return firestore.Client()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bucket():
|
||||
client = storage.Client()
|
||||
try:
|
||||
client.create_bucket("test-bucket")
|
||||
except Exception:
|
||||
pass # already exists
|
||||
return client.bucket("test-bucket")
|
||||
|
||||
|
||||
def _service(db, bucket, cancelled=None):
|
||||
decide = MagicMock()
|
||||
decide.delete_user.return_value = {"deleted": {}}
|
||||
|
||||
def cancel(job_id):
|
||||
(cancelled if cancelled is not None else []).append(job_id)
|
||||
db.collection(JOBS).document(job_id).update({"status": "cancelled"})
|
||||
return True
|
||||
|
||||
return AccountDeletionService(
|
||||
db,
|
||||
jobs_collection=JOBS,
|
||||
cancel_job=cancel,
|
||||
bucket=bucket,
|
||||
dropbox=MagicMock(),
|
||||
decide=decide,
|
||||
apple_revoke=lambda code: True,
|
||||
settings=SimpleNamespace(revenuecat_secret_api_key="", firestore_collection=JOBS),
|
||||
)
|
||||
|
||||
|
||||
def _seed(db, bucket):
|
||||
email = f"del-{uuid.uuid4().hex[:8]}@example.com"
|
||||
db.collection("gen_users").document(email).set({
|
||||
"email": email, "role": "user", "credits": 2,
|
||||
"credit_transactions": [{"id": "t1", "amount": 2, "reason": "purchase"}],
|
||||
})
|
||||
job_id = f"job-{uuid.uuid4().hex[:8]}"
|
||||
db.collection(JOBS).document(job_id).set({
|
||||
"job_id": job_id, "status": "awaiting_review", "user_email": email,
|
||||
"creation_ip": "203.0.113.9",
|
||||
"request_metadata": {"client_ip": "203.0.113.9", "environment": "test"},
|
||||
"state_data": {"customer_name": "Sam", "notification_email": email, "brand_code": "NOMAD-1"},
|
||||
"output_files": {"mp4": f"jobs/{job_id}/finals/out.mp4"},
|
||||
})
|
||||
mfy_id = f"mfy-{uuid.uuid4().hex[:8]}"
|
||||
db.collection(JOBS).document(mfy_id).set({
|
||||
"job_id": mfy_id, "status": "complete", "user_email": "admin@nomadkaraoke.com",
|
||||
"made_for_you": True, "customer_email": email, "customer_notes": "invented note", "state_data": {},
|
||||
})
|
||||
for name in (f"uploads/{job_id}/audio/mix.flac", f"jobs/{job_id}/input/audio/mix.flac",
|
||||
f"jobs/{job_id}/uploads/custom_instrumental_source.wav", f"jobs/{job_id}/custom_instrumental.wav",
|
||||
f"jobs/{job_id}/finals/out.mp4", f"jobs/{job_id}/stems/vocals.flac",
|
||||
f"jobs/{job_id}/stems/custom_instrumental.flac"):
|
||||
bucket.blob(name).upload_from_string(b"x")
|
||||
return email, job_id, mfy_id
|
||||
|
||||
|
||||
def _names(bucket, prefix):
|
||||
return {b.name for b in bucket.list_blobs(prefix=prefix)}
|
||||
|
||||
|
||||
def test_full_deletion_against_emulators(db, bucket):
|
||||
cancelled = []
|
||||
svc = _service(db, bucket, cancelled)
|
||||
email, job_id, mfy_id = _seed(db, bucket)
|
||||
req_id = f"req-{uuid.uuid4().hex[:8]}"
|
||||
db.collection("song_requests").document(req_id).set(
|
||||
{"submitted_by": "x@example.com", "owner_email": "x@example.com", "attempted_owners": ["x@example.com", email]})
|
||||
db.collection("kjbox_show_credit_users").document(email_sha256(email)).set({"email": email, "grant_times": []})
|
||||
log_id = f"log-{uuid.uuid4().hex[:8]}"
|
||||
db.collection("email_log").document(log_id).set({"recipient": email, "subject": "s"})
|
||||
session_id = f"sess-{uuid.uuid4().hex}"
|
||||
db.collection("sessions").document(session_id).set({"user_email": email, "is_active": True})
|
||||
|
||||
assert svc.preview(email) == {"credits": 2, "jobs_in_progress": 1, "blocked": None}
|
||||
summary = svc.delete(email)
|
||||
deletion_id = summary["deletion_id"]
|
||||
|
||||
assert cancelled == [job_id]
|
||||
assert not db.collection("gen_users").document(email).get().exists
|
||||
assert not db.collection("sessions").document(session_id).get().exists
|
||||
|
||||
job = db.collection(JOBS).document(job_id).get().to_dict()
|
||||
assert job["user_email"] == f"deleted:{deletion_id}"
|
||||
assert job["state_data"] == {"brand_code": "NOMAD-1"}
|
||||
assert job["request_metadata"] == {"environment": "test"}
|
||||
assert job["creation_ip"] is None
|
||||
assert job["output_files"] == {"mp4": f"jobs/{job_id}/finals/out.mp4"}
|
||||
|
||||
mfy = db.collection(JOBS).document(mfy_id).get().to_dict()
|
||||
assert mfy["customer_email"] == f"deleted:{deletion_id}" and mfy["customer_notes"] is None
|
||||
|
||||
assert _names(bucket, f"uploads/{job_id}/") == set()
|
||||
assert _names(bucket, f"jobs/{job_id}/input/") == set()
|
||||
assert _names(bucket, f"jobs/{job_id}/") == {
|
||||
f"jobs/{job_id}/finals/out.mp4", f"jobs/{job_id}/stems/vocals.flac",
|
||||
f"jobs/{job_id}/stems/custom_instrumental.flac"}
|
||||
|
||||
assert db.collection("song_requests").document(req_id).get().to_dict()["attempted_owners"] == [
|
||||
"x@example.com", f"deleted:{deletion_id}"]
|
||||
assert db.collection("kjbox_show_credit_users").document(email_sha256(email)).get().to_dict()["email"] == \
|
||||
f"deleted:{deletion_id}"
|
||||
assert not db.collection("email_log").document(log_id).get().exists
|
||||
|
||||
tomb = db.collection("deleted_users").document(deletion_id).get().to_dict()
|
||||
assert tomb["email_sha256"] == email_sha256(email) and email not in repr(tomb)
|
||||
assert is_deleted_email(db, email) and not is_deleted_email(db, "never@example.com")
|
||||
|
||||
pending = [e["id"] for e in svc.list_kjbox_pending()]
|
||||
assert email_sha256(email) in pending
|
||||
assert svc.ack_kjbox(email_sha256(email)) is True
|
||||
assert email_sha256(email) not in [e["id"] for e in svc.list_kjbox_pending()]
|
||||
queued = db.collection("account_deletions").document(email_sha256(email)).get().to_dict()
|
||||
assert queued["targets"] == {"kjbox": "done"}
|
||||
|
||||
|
||||
def test_in_progress_made_for_you_order_refuses(db, bucket):
|
||||
svc = _service(db, bucket)
|
||||
email, _, mfy_id = _seed(db, bucket)
|
||||
db.collection(JOBS).document(mfy_id).update({"status": "rendering_video"})
|
||||
assert svc.preview(email)["blocked"] == "order_in_progress"
|
||||
|
||||
|
||||
def test_concurrent_attempts_share_one_deletion_id(db, bucket):
|
||||
svc = _service(db, bucket)
|
||||
email, _, _ = _seed(db, bucket)
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
ids = list(pool.map(lambda _: svc._ensure_deletion_id(email), range(4)))
|
||||
assert len(set(ids)) == 1
|
||||
assert db.collection("gen_users").document(email).get().to_dict()["deletion_id"] == ids[0]
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
Emulator integration tests for IapService (RevenueCat in-app purchases).
|
||||
|
||||
Runs against a REAL Firestore emulator so the exactly-once guarantee rests on
|
||||
real transactions and create()-only markers, not a fake: concurrent duplicate
|
||||
deliveries of one store transaction grant once, and a refund debits once.
|
||||
Run with: scripts/run-emulator-tests.sh
|
||||
"""
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.services import iap_service as iap
|
||||
from backend.services.login_code_store import TransactionContention
|
||||
from backend.services.user_service import UserService
|
||||
|
||||
from .conftest import emulators_running
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_running(),
|
||||
reason="GCP emulators not running. Start with: scripts/start-emulators.sh",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
return firestore.Client()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def svc(db):
|
||||
user_service = UserService.__new__(UserService)
|
||||
user_service.db = db
|
||||
user_service.settings = MagicMock()
|
||||
referral = MagicMock()
|
||||
referral.record_earning.return_value = None
|
||||
return iap.IapService(db, user_service, referral_service=referral)
|
||||
|
||||
|
||||
def _seed_user(db, credits=0):
|
||||
email = f"iap-{uuid.uuid4().hex[:8]}@example.com"
|
||||
app_user_id = str(uuid.uuid4())
|
||||
ref = db.collection("gen_users").document(email)
|
||||
ref.set({"email": email, "credits": credits, "app_user_id": app_user_id, "credit_transactions": []})
|
||||
return email, app_user_id, ref
|
||||
|
||||
|
||||
def _event(app_user_id, transaction_id, **over):
|
||||
event = {
|
||||
"type": "NON_RENEWING_PURCHASE",
|
||||
"app_user_id": app_user_id,
|
||||
"product_id": "nomad_credits_3",
|
||||
"transaction_id": transaction_id,
|
||||
"store": "APP_STORE",
|
||||
"price": 23.99,
|
||||
"currency": "USD",
|
||||
"takehome_percentage": 0.85,
|
||||
"environment": "PRODUCTION",
|
||||
}
|
||||
event.update(over)
|
||||
return event
|
||||
|
||||
|
||||
def _handle_with_retry(svc, event):
|
||||
# RevenueCat retries a 5xx (contention → 503); emulate that redelivery.
|
||||
for _ in range(20):
|
||||
try:
|
||||
return svc.handle_event(event).action
|
||||
except TransactionContention:
|
||||
time.sleep(0.05)
|
||||
return "contention"
|
||||
|
||||
|
||||
def test_concurrent_duplicates_grant_once(svc, db):
|
||||
email, app_user_id, ref = _seed_user(db)
|
||||
event = _event(app_user_id, f"txn-{uuid.uuid4().hex}")
|
||||
|
||||
with ThreadPoolExecutor(max_workers=5) as pool:
|
||||
actions = list(pool.map(lambda _: _handle_with_retry(svc, dict(event)), range(5)))
|
||||
|
||||
assert actions.count("granted") == 1
|
||||
assert set(actions) <= {"granted", "duplicate"}
|
||||
user = ref.get().to_dict()
|
||||
assert user["credits"] == 3
|
||||
assert [t["reason"] for t in user["credit_transactions"]] == ["iap_purchase"]
|
||||
assert svc._referral_service.record_earning.call_count == 1
|
||||
|
||||
|
||||
def test_concurrent_refunds_debit_once(svc, db):
|
||||
email, app_user_id, ref = _seed_user(db)
|
||||
txn = f"txn-{uuid.uuid4().hex}"
|
||||
assert svc.handle_event(_event(app_user_id, txn, product_id="nomad_credits_1", price=9.99)).action == "granted"
|
||||
ref.update({"credits": 0}) # the credit is spent
|
||||
|
||||
refund = _event(app_user_id, txn, type="CANCELLATION", cancel_reason="CUSTOMER_SUPPORT",
|
||||
product_id="nomad_credits_1", price=-9.99)
|
||||
with ThreadPoolExecutor(max_workers=5) as pool:
|
||||
actions = list(pool.map(lambda _: _handle_with_retry(svc, dict(refund)), range(5)))
|
||||
|
||||
assert actions.count("debited") == 1
|
||||
assert ref.get().to_dict()["credits"] == -1
|
||||
payment = db.collection(iap.STORE_PAYMENTS_COLLECTION).document(f"APP_STORE:{txn}").get().to_dict()
|
||||
assert payment["status"] == "refunded" and payment["refund_amount"] == 999
|
||||
|
||||
|
||||
def test_find_by_app_user_id_real_query(svc, db):
|
||||
email, app_user_id, _ = _seed_user(db)
|
||||
assert svc.user_service.find_by_app_user_id(app_user_id).email == email
|
||||
assert svc.user_service.find_by_app_user_id(str(uuid.uuid4())) is None
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,127 @@
|
||||
"""Tests for Sign in with Apple revocation (httpx mocked; throwaway P-256 key)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import jwt
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
|
||||
from backend.services import apple_revoke_service as mod
|
||||
from backend.services.apple_revoke_service import AppleRevoker
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def keypair():
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
priv = key.private_bytes(
|
||||
serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()
|
||||
).decode()
|
||||
pub = key.public_key().public_bytes(
|
||||
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
|
||||
).decode()
|
||||
return priv, pub
|
||||
|
||||
|
||||
def _settings(priv="PEM", kid="KEY123"):
|
||||
return SimpleNamespace(
|
||||
apple_siwa_key_p8=priv, apple_siwa_key_id=kid,
|
||||
apple_team_id="55B76HN73D", apple_client_id="com.nomadkaraoke.mobile",
|
||||
)
|
||||
|
||||
|
||||
def _patch_http(monkeypatch, handler):
|
||||
real = httpx.AsyncClient
|
||||
monkeypatch.setattr(
|
||||
mod.httpx, "AsyncClient",
|
||||
lambda **kw: real(transport=httpx.MockTransport(handler), **kw),
|
||||
)
|
||||
|
||||
|
||||
def test_builds_client_secret_claims(keypair):
|
||||
priv, pub = keypair
|
||||
secret = AppleRevoker(_settings(priv))._client_secret()
|
||||
assert jwt.get_unverified_header(secret) == {"alg": "ES256", "kid": "KEY123", "typ": "JWT"}
|
||||
claims = jwt.decode(secret, pub, algorithms=["ES256"], audience="https://appleid.apple.com")
|
||||
assert claims["iss"] == "55B76HN73D"
|
||||
assert claims["sub"] == "com.nomadkaraoke.mobile"
|
||||
assert 0 < claims["exp"] - claims["iat"] <= 300
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_token_then_revoke_calls(keypair, monkeypatch):
|
||||
calls = []
|
||||
|
||||
def handler(req: httpx.Request):
|
||||
form = dict(x.split("=", 1) for x in req.content.decode().split("&"))
|
||||
calls.append((str(req.url), form))
|
||||
if req.url.path == "/auth/token":
|
||||
return httpx.Response(200, json={"access_token": "acc", "refresh_token": "ref"})
|
||||
return httpx.Response(200)
|
||||
|
||||
_patch_http(monkeypatch, handler)
|
||||
assert await AppleRevoker(_settings(keypair[0])).revoke("code-1") is True
|
||||
(u1, f1), (u2, f2) = calls
|
||||
assert u1 == "https://appleid.apple.com/auth/token"
|
||||
assert f1["grant_type"] == "authorization_code" and f1["code"] == "code-1"
|
||||
assert f1["client_id"] == "com.nomadkaraoke.mobile"
|
||||
assert u2 == "https://appleid.apple.com/auth/revoke"
|
||||
assert f2["token"] == "ref" and f2["token_type_hint"] == "refresh_token"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_revoke_falls_back_to_access_token(keypair, monkeypatch):
|
||||
seen = {}
|
||||
|
||||
def handler(req):
|
||||
if req.url.path == "/auth/token":
|
||||
return httpx.Response(200, json={"access_token": "acc"})
|
||||
seen["body"] = req.content.decode()
|
||||
return httpx.Response(200)
|
||||
|
||||
_patch_http(monkeypatch, handler)
|
||||
assert await AppleRevoker(_settings(keypair[0])).revoke("c") is True
|
||||
assert "token=acc" in seen["body"] and "access_token" in seen["body"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_key_returns_false(caplog):
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert await AppleRevoker(_settings(priv=None, kid=None)).revoke("c") is False
|
||||
assert any(r.levelno == logging.WARNING for r in caplog.records)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_apple_error_returns_false_and_warns(keypair, monkeypatch, caplog):
|
||||
_patch_http(monkeypatch, lambda req: httpx.Response(400, json={"error": "invalid_grant"}))
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert await AppleRevoker(_settings(keypair[0])).revoke("stale") is False
|
||||
assert any("token exchange failed" in r.message for r in caplog.records)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_revoke_error_returns_false(keypair, monkeypatch):
|
||||
def handler(req):
|
||||
if req.url.path == "/auth/token":
|
||||
return httpx.Response(200, json={"refresh_token": "r"})
|
||||
return httpx.Response(500)
|
||||
|
||||
_patch_http(monkeypatch, handler)
|
||||
assert await AppleRevoker(_settings(keypair[0])).revoke("c") is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_network_error_never_raises(keypair, monkeypatch):
|
||||
def handler(req):
|
||||
raise httpx.ConnectError("boom")
|
||||
|
||||
_patch_http(monkeypatch, handler)
|
||||
assert await AppleRevoker(_settings(keypair[0])).revoke("c") is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bad_pem_never_raises():
|
||||
assert await AppleRevoker(_settings(priv="not a pem")).revoke("c") is False
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Album-mode search helpers: per-track results from one album search."""
|
||||
|
||||
from backend.services.bulk_album_search import (
|
||||
build_track_results,
|
||||
choose_batch_torrent,
|
||||
pick_album_auto_selection,
|
||||
)
|
||||
|
||||
|
||||
def _torrent(source_id, track_files, seeders=31, media="CD", lossless=True, artist="Daft Punk"):
|
||||
return {
|
||||
"title": "Discovery", "artist": artist, "provider": "RED", "source_id": source_id,
|
||||
"quality": "FLAC 16bit CD", "quality_data": {"format": "FLAC", "bit_depth": 16, "media": media},
|
||||
"is_lossless": lossless, "seeders": seeders, "release_type": "Album",
|
||||
"track_files": {k: {"target_file": f, "target_file_size": 10, "match_score": 1.0}
|
||||
for k, f in track_files.items()},
|
||||
}
|
||||
|
||||
|
||||
class TestChooseBatchTorrent:
|
||||
def test_first_best_choice_in_flacfetch_order(self):
|
||||
low = _torrent("low", {"a": "01 A.flac"}, seeders=3)
|
||||
ok = _torrent("ok", {"a": "01 A.flac"}, seeders=12)
|
||||
assert choose_batch_torrent([low, ok])["source_id"] == "ok"
|
||||
|
||||
def test_vinyl_never_batch(self):
|
||||
assert choose_batch_torrent([_torrent("v", {"a": "A1 A.flac"}, seeders=900, media="Vinyl")]) is None
|
||||
|
||||
def test_none_when_empty(self):
|
||||
assert choose_batch_torrent([]) is None
|
||||
|
||||
|
||||
class TestBuildTrackResults:
|
||||
def test_batch_torrent_first_and_result_shape(self):
|
||||
other = _torrent("other", {"j1": "1-01 One More Time.flac"}, seeders=90)
|
||||
batch = _torrent("batch", {"j1": "01 One More Time.flac", "j2": "02 Aerodynamic.flac"})
|
||||
results = build_track_results([other, batch], "j1", batch)
|
||||
assert [r["source_id"] for r in results] == ["batch", "other"]
|
||||
first = results[0]
|
||||
assert first["index"] == 0 and results[1]["index"] == 1
|
||||
assert first["provider"] == "RED" and first["target_file"] == "01 One More Time.flac"
|
||||
assert first["is_lossless"] is True and first["seeders"] == 31
|
||||
assert first["quality_data"]["media"] == "CD"
|
||||
|
||||
def test_only_torrents_covering_the_track(self):
|
||||
batch = _torrent("batch", {"j1": "01 X.flac"})
|
||||
assert build_track_results([batch], "j2", batch) == []
|
||||
|
||||
|
||||
class TestPickAlbumAutoSelection:
|
||||
def _results(self, **kw):
|
||||
batch = _torrent("batch", {"j1": "01 One More Time.flac"}, **kw)
|
||||
return build_track_results([batch], "j1", batch), batch
|
||||
|
||||
def test_confident(self):
|
||||
results, batch = self._results()
|
||||
assert pick_album_auto_selection(results, batch, "One More Time", "Daft Punk") == 0
|
||||
|
||||
def test_low_seeders(self):
|
||||
results, batch = self._results(seeders=9)
|
||||
assert pick_album_auto_selection(results, batch, "One More Time", "Daft Punk") is None
|
||||
|
||||
def test_wrong_artist(self):
|
||||
results, batch = self._results(artist="Tribute Band Collective")
|
||||
assert pick_album_auto_selection(results, batch, "One More Time", "Daft Punk") is None
|
||||
|
||||
def test_filename_names_another_track(self):
|
||||
batch = _torrent("batch", {"j1": "05 Something Else.flac"})
|
||||
results = build_track_results([batch], "j1", batch)
|
||||
assert pick_album_auto_selection(results, batch, "One More Time", "Daft Punk") is None
|
||||
|
||||
def test_track_only_in_another_torrent_gets_the_per_track_pick(self):
|
||||
batch = _torrent("batch", {"j2": "02 Aerodynamic.flac"})
|
||||
other = _torrent("other", {"j1": "01 One More Time.flac"}, seeders=200)
|
||||
results = build_track_results([batch, other], "j1", batch)
|
||||
assert results[0]["source_id"] == "other"
|
||||
assert pick_album_auto_selection(results, batch, "One More Time", "Daft Punk") == 0
|
||||
|
||||
def test_track_only_in_a_weak_torrent_parks(self):
|
||||
batch = _torrent("batch", {"j2": "02 Aerodynamic.flac"})
|
||||
weak = _torrent("weak", {"j1": "01 One More Time.flac"}, seeders=2)
|
||||
results = build_track_results([batch, weak], "j1", batch)
|
||||
assert pick_album_auto_selection(results, batch, "One More Time", "Daft Punk") is None
|
||||
|
||||
def test_no_batch_torrent_uses_per_track_rules(self):
|
||||
results, _ = self._results(seeders=5)
|
||||
assert pick_album_auto_selection(results, None, "One More Time", "Daft Punk") is None
|
||||
@@ -123,3 +123,44 @@ def test_best_choice_min_seeders_matches_frontend():
|
||||
m = re.search(r"export const BEST_CHOICE_MIN_SEEDERS = (\d+)", ts)
|
||||
assert m, "BEST_CHOICE_MIN_SEEDERS not found in frontend/lib/audio-search-utils.ts"
|
||||
assert int(m.group(1)) == BEST_CHOICE_MIN_SEEDERS
|
||||
|
||||
|
||||
class TestArtistMatch:
|
||||
"""Port of isArtistMatch (frontend tier 1 requires the right artist)."""
|
||||
|
||||
def _m(self, want, have):
|
||||
from backend.services.audio_search_service import is_artist_match
|
||||
return is_artist_match(want, {"artist": have})
|
||||
|
||||
def test_exact_and_the_prefix(self):
|
||||
assert self._m("The Killers", "Killers")
|
||||
assert self._m("Chase & Status", "Chase & Status")
|
||||
|
||||
def test_featured_credit_contains(self):
|
||||
assert self._m("Chase & Status", "Chase & Status, Delilah")
|
||||
|
||||
def test_small_typo(self):
|
||||
assert self._m("Radiohead", "Radiohed")
|
||||
|
||||
def test_non_latin_names(self):
|
||||
assert self._m("宇多田ヒカル", "宇多田ヒカル")
|
||||
assert self._m("Би-2", "би-2")
|
||||
assert not self._m("宇多田ヒカル", "椎名林檎")
|
||||
|
||||
def test_ampersand_and_accents(self):
|
||||
assert self._m("Simon & Garfunkel", "Simon and Garfunkel")
|
||||
assert self._m("Beyoncé", "Beyonce")
|
||||
|
||||
def test_uncomparable_search_name_is_not_held_against_result(self):
|
||||
assert self._m("!!!", "Chk Chk Chk")
|
||||
|
||||
def test_different_artist(self):
|
||||
assert not self._m("Daft Punk", "Tribute Band Collective")
|
||||
assert not self._m("ABBA", "ABBX") # short names: no typo tolerance
|
||||
|
||||
def test_pick_auto_selection_rejects_wrong_artist(self):
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
r = _lossless_best(0, seeders=80, title="Bohemian Rhapsody")
|
||||
r["artist"] = "Tribute Band Collective"
|
||||
assert pick_auto_selection([r], "Bohemian Rhapsody", "Queen") is None
|
||||
assert pick_auto_selection([r], "Bohemian Rhapsody") == 0 # no artist given: not checked
|
||||
@@ -203,3 +203,220 @@ async def test_auto_select_never_charges_bypassed_job(monkeypatch, patched, stat
|
||||
update = jm.update_job.call_args_list[-1][0][1]
|
||||
assert update["state_data.credits_charged"] == 0
|
||||
assert update["state_data.payment_bypassed"] is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Album path: one flacfetch album search for an album-mode batch
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
ALBUM = {"artist": "Daft Punk", "title": "Discovery", "release_group_mbid": "rg-1"}
|
||||
|
||||
|
||||
def _album_job(job_id, title, position):
|
||||
job = _make_job(job_id, state_extra={"bulk_album": ALBUM, "bulk_track_position": position})
|
||||
job.title = job.audio_search_title = title
|
||||
return job
|
||||
|
||||
|
||||
def _torrent(source_id, track_files, seeders=31, media="CD", release_type="Album"):
|
||||
return {
|
||||
"title": "Discovery", "artist": "Daft Punk", "provider": "RED", "source_id": source_id,
|
||||
"quality": "FLAC 16bit CD", "quality_data": {"format": "FLAC", "bit_depth": 16, "media": media},
|
||||
"is_lossless": True, "seeders": seeders, "release_type": release_type,
|
||||
"matched_count": len(track_files),
|
||||
"track_files": {k: {"target_file": f, "target_file_size": 1, "match_score": 1.0}
|
||||
for k, f in track_files.items()},
|
||||
}
|
||||
|
||||
|
||||
class FakeAlbumClient:
|
||||
def __init__(self, response=None, error=None):
|
||||
self.response, self.error, self.calls = response, error, []
|
||||
|
||||
async def search_album(self, artist, album, tracks):
|
||||
self.calls.append((artist, album, tracks))
|
||||
if self.error:
|
||||
raise self.error
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def album_env(monkeypatch, patched):
|
||||
jm, _ass, transitions = patched
|
||||
monkeypatch.setattr("backend.api.routes.audio_search._validate_and_prepare_selection",
|
||||
lambda job_id, idx: {"ok": True})
|
||||
stored = {}
|
||||
jm.update_job.side_effect = lambda job_id, updates: stored.setdefault(job_id, {}).update(updates)
|
||||
|
||||
def use(client):
|
||||
monkeypatch.setattr(worker, "_album_search_client", lambda: client)
|
||||
return client
|
||||
return jm, transitions, stored, use
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_album_batch_makes_one_search_and_auto_selects_every_track(album_env):
|
||||
jm, transitions, stored, use = album_env
|
||||
jobs = [_album_job("j1", "One More Time", 1), _album_job("j2", "Aerodynamic", 2)]
|
||||
client = use(FakeAlbumClient({"results": [
|
||||
_torrent("cd-31", {"j1": "01 One More Time.flac", "j2": "02 Aerodynamic.flac"}, seeders=31),
|
||||
_torrent("web-15", {"j1": "1-01 One More Time.flac", "j2": "1-02 Aerodynamic.flac"},
|
||||
seeders=15, media="WEB"),
|
||||
]}))
|
||||
|
||||
fallback = await worker.process_album_jobs(ALBUM, jobs, jm)
|
||||
|
||||
assert fallback == []
|
||||
assert len(client.calls) == 1
|
||||
artist, album, tracks = client.calls[0]
|
||||
assert (artist, album) == ("Daft Punk", "Discovery")
|
||||
assert tracks == [{"key": "j1", "title": "One More Time", "position": 1},
|
||||
{"key": "j2", "title": "Aerodynamic", "position": 2}]
|
||||
for job_id, expected in (("j1", "01 One More Time.flac"), ("j2", "02 Aerodynamic.flac")):
|
||||
results = stored[job_id]["state_data.audio_search_results"]
|
||||
# Batch torrent first, the other edition kept as an alternative.
|
||||
assert [r["source_id"] for r in results] == ["cd-31", "web-15"]
|
||||
assert results[0]["target_file"] == expected
|
||||
assert stored[job_id]["state_data.bulk_auto_selected"] is True
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION not in transitions
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_uncovered_tracks_fall_back_to_per_track_search(album_env):
|
||||
jm, _t, stored, use = album_env
|
||||
jobs = [_album_job("j1", "One More Time", 1), _album_job("j2", "Bonus Thing", 15)]
|
||||
use(FakeAlbumClient({"results": [_torrent("cd", {"j1": "01 One More Time.flac"})]}))
|
||||
|
||||
fallback = await worker.process_album_jobs(ALBUM, jobs, jm)
|
||||
|
||||
assert [j.job_id for j in fallback] == ["j2"]
|
||||
assert "j2" not in stored
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_album_search_failure_falls_back_for_all(album_env):
|
||||
from backend.services.flacfetch_client import FlacfetchServiceError
|
||||
jm, _t, stored, use = album_env
|
||||
jobs = [_album_job("j1", "One More Time", 1)]
|
||||
use(FakeAlbumClient(error=FlacfetchServiceError("timed out")))
|
||||
assert await worker.process_album_jobs(ALBUM, jobs, jm) == jobs
|
||||
assert stored == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_album_client_falls_back(album_env):
|
||||
jm, _t, _s, use = album_env
|
||||
use(None)
|
||||
jobs = [_album_job("j1", "One More Time", 1)]
|
||||
assert await worker.process_album_jobs(ALBUM, jobs, jm) == jobs
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_poorly_seeded_album_parks_with_album_options(album_env):
|
||||
jm, transitions, stored, use = album_env
|
||||
use(FakeAlbumClient({"results": [_torrent("cd-5", {"j1": "01 One More Time.flac"}, seeders=5)]}))
|
||||
await worker.process_album_jobs(ALBUM, [_album_job("j1", "One More Time", 1)], jm)
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
|
||||
assert stored["j1"]["state_data.audio_search_results"][0]["source_id"] == "cd-5"
|
||||
assert stored["j1"]["state_data.bulk_pending_search"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auto_select_disabled_parks_album_jobs(album_env):
|
||||
jm, transitions, _s, use = album_env
|
||||
job = _album_job("j1", "One More Time", 1)
|
||||
job.state_data["bulk_settings"]["auto_select_if_lossless"] = False
|
||||
use(FakeAlbumClient({"results": [_torrent("cd", {"j1": "01 One More Time.flac"})]}))
|
||||
await worker.process_album_jobs(ALBUM, [job], jm)
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION in transitions
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_batch_routes_album_jobs_then_searches_rest_one_at_a_time(monkeypatch):
|
||||
album_jobs = [_album_job("a1", "One More Time", 1), _album_job("a2", "Bonus Thing", 15)]
|
||||
text_job = _make_job("t1")
|
||||
jm = MagicMock()
|
||||
jm.list_jobs_by_batch_id.return_value = album_jobs + [text_job]
|
||||
monkeypatch.setattr(worker, "JobManager", lambda: jm)
|
||||
|
||||
seen_album = []
|
||||
|
||||
async def fake_album(album, jobs, job_manager):
|
||||
seen_album.append([j.job_id for j in jobs])
|
||||
return [j for j in jobs if j.job_id == "a2"] # uncovered track
|
||||
|
||||
in_flight = max_in_flight = 0
|
||||
searched = []
|
||||
|
||||
async def fake_process_job(job_id, job_manager, ass):
|
||||
nonlocal in_flight, max_in_flight
|
||||
in_flight += 1
|
||||
max_in_flight = max(max_in_flight, in_flight)
|
||||
import asyncio
|
||||
await asyncio.sleep(0.01)
|
||||
searched.append(job_id)
|
||||
in_flight -= 1
|
||||
|
||||
monkeypatch.setattr(worker, "process_album_jobs", fake_album)
|
||||
monkeypatch.setattr(worker, "process_job", fake_process_job)
|
||||
monkeypatch.setattr(worker, "AudioSearchService", MagicMock)
|
||||
|
||||
count = await worker.process_batch("b1")
|
||||
|
||||
assert count == 3
|
||||
assert seen_album == [["a1", "a2"]]
|
||||
assert sorted(searched) == ["a2", "t1"]
|
||||
assert max_in_flight == 1 # never more than one flacfetch search at a time
|
||||
|
||||
|
||||
def test_search_concurrency_is_one():
|
||||
assert worker.SEARCH_CONCURRENCY == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_jobs_past_the_batch_deadline_are_parked_not_searched(monkeypatch):
|
||||
jobs = [_make_job("t1"), _make_job("t2")]
|
||||
jm = MagicMock()
|
||||
jm.list_jobs_by_batch_id.return_value = jobs
|
||||
parked = []
|
||||
jm.transition_to_state.side_effect = lambda **kw: parked.append((kw["job_id"], kw["new_status"]))
|
||||
monkeypatch.setattr(worker, "JobManager", lambda: jm)
|
||||
monkeypatch.setattr(worker, "BATCH_SEARCH_DEADLINE_SECONDS", -1) # already past
|
||||
searched = []
|
||||
|
||||
async def fake_process_job(job_id, job_manager, ass):
|
||||
searched.append(job_id)
|
||||
|
||||
monkeypatch.setattr(worker, "process_job", fake_process_job)
|
||||
monkeypatch.setattr(worker, "AudioSearchService", MagicMock)
|
||||
|
||||
await worker.process_batch("b1")
|
||||
|
||||
assert searched == []
|
||||
assert sorted(parked) == [("t1", JobStatus.AWAITING_AUDIO_SELECTION), ("t2", JobStatus.AWAITING_AUDIO_SELECTION)]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unparkable_job_fails_the_batch_after_the_others_finish(monkeypatch):
|
||||
jobs = [_make_job("bad"), _make_job("good")]
|
||||
jm = MagicMock()
|
||||
jm.list_jobs_by_batch_id.return_value = jobs
|
||||
|
||||
def transition(**kw):
|
||||
if kw["job_id"] == "bad":
|
||||
raise RuntimeError("firestore down")
|
||||
jm.transition_to_state.side_effect = transition
|
||||
monkeypatch.setattr(worker, "JobManager", lambda: jm)
|
||||
searched = []
|
||||
|
||||
async def fake_process_job(job_id, job_manager, ass):
|
||||
if job_id == "bad":
|
||||
raise RuntimeError("search crashed")
|
||||
searched.append(job_id)
|
||||
|
||||
monkeypatch.setattr(worker, "process_job", fake_process_job)
|
||||
monkeypatch.setattr(worker, "AudioSearchService", MagicMock)
|
||||
|
||||
with pytest.raises(worker.BatchParkingError):
|
||||
await worker.process_batch("b1")
|
||||
assert searched == ["good"] # the independent job still ran
|
||||
@@ -150,6 +150,35 @@ def test_partial_failure_returns_created_jobs(client, monkeypatch):
|
||||
assert resp.json()["total"] == 2
|
||||
|
||||
|
||||
def test_album_batch_stamps_album_and_track_positions(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth()
|
||||
_patch_user_service(monkeypatch, credits=10)
|
||||
jm = _patch_job_manager(monkeypatch)
|
||||
|
||||
resp = client.post("/api/bulk/submit", json={
|
||||
"songs": [{"artist": "Daft Punk", "title": "One More Time", "position": 1},
|
||||
{"artist": "Daft Punk", "title": "Aerodynamic", "position": 2}],
|
||||
"settings": {},
|
||||
"album": {"artist": "Daft Punk", "title": "Discovery", "release_group_mbid": "rg-1"},
|
||||
})
|
||||
assert resp.status_code == 200, resp.text
|
||||
stamps = [c[0][1] for c in jm.update_job.call_args_list]
|
||||
assert [s["state_data.bulk_track_position"] for s in stamps] == [1, 2]
|
||||
assert stamps[0]["state_data.bulk_album"] == {
|
||||
"artist": "Daft Punk", "title": "Discovery", "release_group_mbid": "rg-1", "release_mbid": None,
|
||||
}
|
||||
|
||||
|
||||
def test_text_batch_has_no_album_state(client, monkeypatch):
|
||||
app.dependency_overrides[require_auth] = _auth()
|
||||
_patch_user_service(monkeypatch, credits=10)
|
||||
jm = _patch_job_manager(monkeypatch)
|
||||
client.post("/api/bulk/submit", json={"songs": [{"artist": "Daft Punk", "title": "One More Time"}]})
|
||||
stamped = jm.update_job.call_args[0][1]
|
||||
assert "state_data.bulk_album" not in stamped
|
||||
assert "state_data.bulk_track_position" not in stamped
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelled_request_still_dispatches_created_batch(monkeypatch):
|
||||
"""A client disconnect mid-creation must not strand created (and charged) jobs:
|
||||
|
||||
@@ -10,3 +10,14 @@ def test_decide_search_resources_monitored():
|
||||
def test_monitor_log_query_covers_them():
|
||||
assert "karaoke-decide-search" in monitor.RESOURCE_TYPE_FILTERS["cloud_run_revision"][1]
|
||||
assert "song-index-build" in monitor.RESOURCE_TYPE_FILTERS["cloud_run_job"][1]
|
||||
|
||||
|
||||
def test_voice_pool_jobs_monitored_across_regions():
|
||||
"""voice-pool-* jobs (decide us-central1, gen GPU us-east4) must reach #alerts."""
|
||||
jobs = monitor.RESOURCE_TYPE_FILTERS["cloud_run_job"][1]
|
||||
for job in ("voice-pool-select", "voice-pool-fetch", "voice-pool-analyse", "voice-pool-separate-job", "vocal-range-gen"):
|
||||
assert job in jobs
|
||||
# The query filters by job_name only (no region/location), so us-east4 is covered.
|
||||
flt = monitor._build_log_filter("cloud_run_job", jobs, 60)
|
||||
assert "voice-pool-separate-job" in flt
|
||||
assert "location" not in flt
|
||||
@@ -0,0 +1,486 @@
|
||||
"""Tests for Expo push: token registration, per-type prefs, sending and job triggers.
|
||||
|
||||
Composed over the in-memory Firestore fake from the kjbox partner tests: the real
|
||||
ExpoPushService, UserService, PushNotificationService and JobManager trigger code.
|
||||
Only the true boundaries (Expo HTTP, pywebpush) are faked.
|
||||
"""
|
||||
import json
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.api.routes import push as push_routes
|
||||
from backend.api.routes import users as users_routes
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services import expo_push_service as eps
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.services.expo_push_service import ExpoPushService
|
||||
from backend.services.fake_workers import outbox
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.push_notification_service import PushNotificationService
|
||||
from backend.services.user_service import UserService, get_user_service
|
||||
from backend.tests.test_kjbox_partner_api import FakeDb, FakeTransaction
|
||||
|
||||
A = "alice@example.com"
|
||||
B = "bob@example.com"
|
||||
TOKEN = "ExponentPushToken[abc123]"
|
||||
TOKEN2 = "ExponentPushToken[def456]"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
return FakeDb()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_service(db):
|
||||
svc = UserService.__new__(UserService)
|
||||
svc.db = db
|
||||
svc.settings = MagicMock()
|
||||
for email in (A, B):
|
||||
db.collection("gen_users").docs[email] = {"email": email}
|
||||
return svc
|
||||
|
||||
|
||||
def _service(db, user_service, http_post=None):
|
||||
return ExpoPushService(
|
||||
user_service=user_service,
|
||||
transaction_runner=lambda fn: fn(FakeTransaction(db.txn_writes)),
|
||||
http_post=http_post,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def expo(db, user_service):
|
||||
return _service(db, user_service)
|
||||
|
||||
|
||||
def _doc(db, email):
|
||||
return db.collection("gen_users").docs[email]
|
||||
|
||||
|
||||
def _tokens(db, email):
|
||||
return [e["token"] for e in _doc(db, email).get("expo_push_tokens", [])]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(db, user_service, expo):
|
||||
app = FastAPI()
|
||||
app.include_router(push_routes.router, prefix="/api")
|
||||
app.include_router(users_routes.router, prefix="/api")
|
||||
current = {"email": A}
|
||||
app.dependency_overrides[require_auth] = lambda: AuthResult(
|
||||
is_valid=True, user_type=UserType.UNLIMITED, remaining_uses=-1,
|
||||
message="ok", user_email=current["email"], is_admin=False,
|
||||
)
|
||||
app.dependency_overrides[get_user_service] = lambda: user_service
|
||||
with patch.object(push_routes, "get_expo_push_service", return_value=expo):
|
||||
c = TestClient(app)
|
||||
c.as_user = lambda email: current.update(email=email)
|
||||
yield c
|
||||
|
||||
|
||||
def _register(client, token=TOKEN, device_id="dev-1", platform="ios"):
|
||||
return client.post("/api/push/expo-token", json={"token": token, "platform": platform, "device_id": device_id})
|
||||
|
||||
|
||||
class TestTokenRoutes:
|
||||
def test_register_token_and_replace_per_device(self, client, db):
|
||||
assert _register(client).status_code == 204
|
||||
assert _register(client, token=TOKEN2).status_code == 204
|
||||
entries = _doc(db, A)["expo_push_tokens"]
|
||||
assert [e["token"] for e in entries] == [TOKEN2]
|
||||
assert entries[0]["device_id"] == "dev-1" and entries[0]["platform"] == "ios"
|
||||
|
||||
def test_second_device_adds_entry(self, client, db):
|
||||
_register(client)
|
||||
_register(client, token=TOKEN2, device_id="dev-2", platform="android")
|
||||
assert _tokens(db, A) == [TOKEN, TOKEN2]
|
||||
|
||||
def test_reregistering_same_token_keeps_one_entry(self, client, db):
|
||||
_register(client)
|
||||
_register(client)
|
||||
assert _tokens(db, A) == [TOKEN]
|
||||
|
||||
def test_register_moves_token_from_other_user(self, client, db):
|
||||
_register(client)
|
||||
client.as_user(B)
|
||||
assert _register(client, device_id="dev-b").status_code == 204
|
||||
assert _tokens(db, A) == []
|
||||
assert _doc(db, A)["expo_push_token_values"] == []
|
||||
assert _tokens(db, B) == [TOKEN]
|
||||
|
||||
def test_delete_token(self, client, db):
|
||||
_register(client)
|
||||
_register(client, token=TOKEN2, device_id="dev-2")
|
||||
r = client.request("DELETE", "/api/push/expo-token", json={"token": TOKEN})
|
||||
assert r.status_code == 204
|
||||
assert _tokens(db, A) == [TOKEN2]
|
||||
|
||||
def test_delete_cannot_remove_another_users_token(self, client, db):
|
||||
_register(client)
|
||||
client.as_user(B)
|
||||
assert client.request("DELETE", "/api/push/expo-token", json={"token": TOKEN}).status_code == 204
|
||||
assert _tokens(db, A) == [TOKEN]
|
||||
|
||||
def test_delete_unknown_token_is_noop(self, client):
|
||||
assert client.request("DELETE", "/api/push/expo-token", json={"token": TOKEN}).status_code == 204
|
||||
|
||||
@pytest.mark.parametrize("bad", ["not-a-token", "ExponentPushToken[]", "fcm:abc", "ExponentPushToken[a b]"])
|
||||
def test_rejects_non_expo_token(self, client, bad):
|
||||
assert _register(client, token=bad).status_code == 422
|
||||
|
||||
def test_rejects_unknown_platform(self, client):
|
||||
assert _register(client, platform="web").status_code == 422
|
||||
|
||||
|
||||
class TestPrefsRoute:
|
||||
def test_prefs_patch_partial(self, client, db):
|
||||
r = client.patch("/api/users/me/push-prefs", json={"review": False})
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"ready": True, "review": False, "problems": True}
|
||||
r = client.patch("/api/users/me/push-prefs", json={"problems": False})
|
||||
assert r.json() == {"ready": True, "review": False, "problems": False}
|
||||
assert _doc(db, A)["push_prefs"] == {"ready": True, "review": False, "problems": False}
|
||||
|
||||
def test_prefs_patch_empty_returns_current(self, client):
|
||||
assert client.patch("/api/users/me/push-prefs", json={}).json() == {
|
||||
"ready": True, "review": True, "problems": True}
|
||||
|
||||
|
||||
class _Resp:
|
||||
def __init__(self, data):
|
||||
self._data = data
|
||||
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
def json(self):
|
||||
return {"data": self._data}
|
||||
|
||||
|
||||
def _seed_tokens(db, email, tokens):
|
||||
_doc(db, email)["expo_push_tokens"] = [
|
||||
{"token": t, "platform": "ios", "device_id": f"d{i}"} for i, t in enumerate(tokens)]
|
||||
_doc(db, email)["expo_push_token_values"] = list(tokens)
|
||||
|
||||
|
||||
class TestSend:
|
||||
def test_sends_message_shape(self, db, user_service):
|
||||
_seed_tokens(db, A, [TOKEN])
|
||||
calls = []
|
||||
svc = _service(db, user_service, lambda url, json, **kw: calls.append((url, json)) or _Resp([{"status": "ok"}]))
|
||||
assert svc.send(A, "ready", "T", "B", "/job/1") == 1
|
||||
url, msgs = calls[0]
|
||||
assert url == "https://exp.host/--/api/v2/push/send"
|
||||
assert msgs == [{"to": TOKEN, "title": "T", "body": "B", "sound": "default",
|
||||
"data": {"url": "/job/1", "kind": "ready"}}]
|
||||
|
||||
def test_device_not_registered_removes_token(self, db, user_service):
|
||||
_seed_tokens(db, A, [TOKEN, TOKEN2])
|
||||
resp = _Resp([{"status": "ok"},
|
||||
{"status": "error", "message": "gone", "details": {"error": "DeviceNotRegistered"}}])
|
||||
svc = _service(db, user_service, lambda *a, **k: resp)
|
||||
assert svc.send(A, "ready", "T", "B", "/job/1") == 1
|
||||
assert _tokens(db, A) == [TOKEN]
|
||||
assert _doc(db, A)["expo_push_token_values"] == [TOKEN]
|
||||
|
||||
def test_other_ticket_error_keeps_token(self, db, user_service):
|
||||
_seed_tokens(db, A, [TOKEN])
|
||||
svc = _service(db, user_service, lambda *a, **k: _Resp(
|
||||
[{"status": "error", "message": "rate", "details": {"error": "MessageRateExceeded"}}]))
|
||||
assert svc.send(A, "ready", "T", "B", "/x") == 0
|
||||
assert _tokens(db, A) == [TOKEN]
|
||||
|
||||
def test_batches_over_100(self, db, user_service):
|
||||
tokens = [f"ExponentPushToken[t{i}]" for i in range(250)]
|
||||
_seed_tokens(db, A, tokens)
|
||||
sizes = []
|
||||
|
||||
def post(url, json, **kw):
|
||||
sizes.append(len(json))
|
||||
return _Resp([{"status": "ok"}] * len(json))
|
||||
|
||||
assert _service(db, user_service, post).send(A, "ready", "T", "B", "/x") == 250
|
||||
assert sizes == [100, 100, 50]
|
||||
|
||||
def test_http_failure_never_raises(self, db, user_service):
|
||||
_seed_tokens(db, A, [TOKEN])
|
||||
|
||||
def boom(*a, **k):
|
||||
raise RuntimeError("network")
|
||||
|
||||
assert _service(db, user_service, boom).send(A, "ready", "T", "B", "/x") == 0
|
||||
assert _tokens(db, A) == [TOKEN]
|
||||
|
||||
def test_pref_off_suppresses(self, db, user_service):
|
||||
_seed_tokens(db, A, [TOKEN])
|
||||
_doc(db, A)["push_prefs"] = {"ready": False}
|
||||
post = MagicMock()
|
||||
svc = _service(db, user_service, post)
|
||||
assert svc.send(A, "ready", "T", "B", "/x") == 0
|
||||
post.assert_not_called()
|
||||
assert svc.send(A, "review", "T", "B", "/x") == 0 # on, but post returns a MagicMock: no raise
|
||||
post.assert_called_once()
|
||||
|
||||
def test_no_tokens_or_unknown_user(self, db, user_service):
|
||||
svc = _service(db, user_service, MagicMock())
|
||||
assert svc.send(A, "ready", "T", "B", "/x") == 0
|
||||
assert svc.send("nobody@example.com", "ready", "T", "B", "/x") == 0
|
||||
|
||||
def test_fake_workers_mode_records_to_outbox(self, db, user_service, monkeypatch):
|
||||
_seed_tokens(db, A, [TOKEN])
|
||||
monkeypatch.setattr(eps, "fake_workers_enabled", lambda: True)
|
||||
post = MagicMock()
|
||||
outbox.clear_pushes()
|
||||
assert _service(db, user_service, post).send(A, "problems", "T", "B", "/job/9") == 1
|
||||
post.assert_not_called()
|
||||
assert outbox.list_pushes(A)[0]["url"] == "/job/9"
|
||||
outbox.clear_pushes()
|
||||
|
||||
|
||||
class TestTestSupportOutbox:
|
||||
def test_push_outbox_endpoints(self):
|
||||
from backend.api.routes import test_support
|
||||
app = FastAPI()
|
||||
app.include_router(test_support.router, prefix="/api")
|
||||
c = TestClient(app)
|
||||
outbox.clear_pushes()
|
||||
outbox.record_push(A, "ready", "T", "B", "/job/1")
|
||||
outbox.record_push(B, "review", "T", "B", "/review/2")
|
||||
assert [p["to"] for p in c.get("/api/test/push-outbox").json()["pushes"]] == [B, A]
|
||||
assert len(c.get(f"/api/test/push-outbox?to={A}").json()["pushes"]) == 1
|
||||
assert c.delete("/api/test/push-outbox").status_code == 200
|
||||
assert c.get("/api/test/push-outbox").json()["pushes"] == []
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ job triggers
|
||||
|
||||
def _job(status, **kw):
|
||||
return Job(job_id="job1", user_email=A, artist="Test Artist", title="Test Song",
|
||||
status=status, created_at=datetime(2026, 1, 1),
|
||||
updated_at=datetime(2026, 1, 1), **kw)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def triggers(db, user_service, monkeypatch):
|
||||
"""Run JobManager._trigger_state_notifications with real Expo + Web Push services over the fake DB."""
|
||||
_seed_tokens(db, A, [TOKEN])
|
||||
monkeypatch.setattr(eps, "fake_workers_enabled", lambda: True)
|
||||
outbox.clear_pushes()
|
||||
expo = _service(db, user_service)
|
||||
|
||||
settings = SimpleNamespace(enable_push_notifications=True, max_push_subscriptions_per_user=5,
|
||||
vapid_subject="mailto:x@example.com",
|
||||
get_secret=lambda name: "k")
|
||||
with patch("backend.services.push_notification_service.get_settings", return_value=settings):
|
||||
web = PushNotificationService(db=db)
|
||||
_doc(db, A)["push_subscriptions"] = [{"endpoint": "https://push.example/1", "keys": {"p256dh": "x", "auth": "y"}}]
|
||||
webpush = MagicMock()
|
||||
monkeypatch.setattr("backend.services.push_notification_service.webpush", webpush)
|
||||
|
||||
def run(status, action=None, **job_kw):
|
||||
"""Fire notifications for ``status`` — or run ``action(mgr)`` (e.g. the real fail_job)."""
|
||||
job = _job(status, **job_kw)
|
||||
mgr = JobManager.__new__(JobManager)
|
||||
mgr.get_job = lambda job_id: job
|
||||
mgr._schedule_completion_email = lambda j: None
|
||||
mgr._schedule_idle_reminder = lambda j, s: None
|
||||
mgr._refund_credit_for_job = MagicMock()
|
||||
mgr.firestore = MagicMock()
|
||||
|
||||
def write_status(job_id, status, **kw):
|
||||
job.status = status
|
||||
if "error_details" in kw:
|
||||
job.error_details = kw["error_details"]
|
||||
mgr.firestore.update_job_status.side_effect = write_status
|
||||
|
||||
def write_fields(job_id, updates):
|
||||
for key, value in updates.items():
|
||||
if key.startswith("state_data."):
|
||||
job.state_data[key.split(".", 1)[1]] = value
|
||||
else:
|
||||
setattr(job, key, value)
|
||||
mgr.firestore.update_job.side_effect = write_fields
|
||||
threads = []
|
||||
real_thread = threading.Thread
|
||||
|
||||
class Rec(real_thread):
|
||||
def __init__(self, *a, **k):
|
||||
super().__init__(*a, **k)
|
||||
if getattr(k.get("target"), "__name__", "") == "run_in_thread":
|
||||
threads.append(self)
|
||||
|
||||
with patch("backend.services.expo_push_service.get_expo_push_service", return_value=expo), \
|
||||
patch("backend.services.push_notification_service.get_push_notification_service", return_value=web), \
|
||||
patch("threading.Thread", Rec):
|
||||
if action is None:
|
||||
mgr._trigger_state_notifications("job1", status)
|
||||
else:
|
||||
action(mgr)
|
||||
for th in threads:
|
||||
th.join(timeout=10)
|
||||
return outbox.list_pushes(A), webpush
|
||||
|
||||
yield run
|
||||
outbox.clear_pushes()
|
||||
|
||||
|
||||
class TestJobTriggers:
|
||||
@pytest.mark.parametrize("status,kind,url", [
|
||||
(JobStatus.COMPLETE, "ready", "/job/job1"),
|
||||
(JobStatus.AWAITING_REVIEW, "review", "/review/job1"),
|
||||
(JobStatus.AWAITING_DURATION_CONFIRM, "review", "/job/duration/job1"),
|
||||
(JobStatus.AWAITING_AUDIO_EDIT, "review", "/job/job1"),
|
||||
(JobStatus.AWAITING_INSTRUMENTAL_SELECTION, "review", "/job/job1"),
|
||||
(JobStatus.FAILED, "problems", "/job/job1"),
|
||||
])
|
||||
def test_status_maps_to_kind_and_url(self, triggers, status, kind, url):
|
||||
pushes, _ = triggers(status)
|
||||
assert [(p["kind"], p["url"]) for p in pushes] == [(kind, url)]
|
||||
assert "Test Song" in pushes[0]["body"] or status == JobStatus.COMPLETE
|
||||
|
||||
def test_complete_sends_ready_with_url(self, triggers):
|
||||
pushes, webpush = triggers(JobStatus.COMPLETE)
|
||||
assert pushes[0]["kind"] == "ready" and pushes[0]["url"] == "/job/job1"
|
||||
assert "Test Song" in pushes[0]["body"]
|
||||
webpush.assert_called_once()
|
||||
|
||||
def test_failed_sends_problems_and_webpush(self, triggers):
|
||||
pushes, webpush = triggers(JobStatus.FAILED)
|
||||
assert pushes[0]["kind"] == "problems"
|
||||
webpush.assert_called_once()
|
||||
assert "problem" in json.loads(webpush.call_args.kwargs["data"])["title"].lower()
|
||||
|
||||
def test_audio_selection_is_not_a_problem_push(self, triggers):
|
||||
# The normal interactive search step; stalled downloads end FAILED instead.
|
||||
pushes, webpush = triggers(JobStatus.AWAITING_AUDIO_SELECTION)
|
||||
assert pushes == []
|
||||
webpush.assert_not_called()
|
||||
|
||||
def test_stalled_download_body_offers_to_keep_trying(self, triggers):
|
||||
pushes, _ = triggers(JobStatus.FAILED, error_details={"code": "audio_download_stalled"})
|
||||
assert "keep trying" in pushes[0]["body"]
|
||||
pushes, _ = triggers(JobStatus.FAILED, error_details={"code": "other"})
|
||||
assert "keep trying" not in pushes[0]["body"]
|
||||
|
||||
def test_pref_off_suppresses_expo_and_webpush(self, triggers, db):
|
||||
_doc(db, A)["push_prefs"] = {"problems": False}
|
||||
pushes, webpush = triggers(JobStatus.FAILED)
|
||||
assert pushes == []
|
||||
webpush.assert_not_called()
|
||||
# other types unaffected
|
||||
pushes, webpush = triggers(JobStatus.COMPLETE)
|
||||
assert len(pushes) == 1
|
||||
webpush.assert_called_once()
|
||||
|
||||
def test_expo_failure_does_not_stop_web_push_or_raise(self, triggers, monkeypatch):
|
||||
monkeypatch.setattr(ExpoPushService, "send", MagicMock(side_effect=RuntimeError("boom")))
|
||||
_, webpush = triggers(JobStatus.COMPLETE)
|
||||
webpush.assert_called_once()
|
||||
|
||||
def test_expo_still_sent_when_web_push_disabled(self, triggers):
|
||||
with patch.object(PushNotificationService, "is_enabled", return_value=False):
|
||||
pushes, webpush = triggers(JobStatus.COMPLETE)
|
||||
assert len(pushes) == 1
|
||||
webpush.assert_not_called()
|
||||
|
||||
|
||||
def _fail(mgr):
|
||||
assert mgr.fail_job("job1", "Audio download failed: boom", {"stage": "audio_download"}) is True
|
||||
|
||||
|
||||
def _mark_failed(mgr):
|
||||
mgr.mark_job_failed("job1", "Render crashed", {"stage": "render"})
|
||||
|
||||
|
||||
def _pending(minutes):
|
||||
from datetime import timedelta, timezone
|
||||
expires = datetime.now(timezone.utc) + timedelta(minutes=minutes)
|
||||
return {"cloud_run_retry_pending": {"expires_at": expires.isoformat(), "expected_attempt": 1}}
|
||||
|
||||
|
||||
class TestWorkerFailurePaths:
|
||||
"""Workers fail jobs via fail_job / mark_job_failed, not transition_to_state."""
|
||||
|
||||
@pytest.mark.parametrize("action", [_fail, _mark_failed])
|
||||
def test_worker_failure_pushes_once(self, triggers, action):
|
||||
pushes, webpush = triggers(JobStatus.DOWNLOADING_AUDIO, action=action)
|
||||
assert [(p["kind"], p["url"]) for p in pushes] == [("problems", "/job/job1")]
|
||||
webpush.assert_called_once()
|
||||
|
||||
def test_fail_job_stalled_download_uses_keep_trying_body(self, triggers):
|
||||
def fail_stalled(mgr):
|
||||
mgr.fail_job("job1", "stalled", {"code": "audio_download_stalled"})
|
||||
pushes, _ = triggers(JobStatus.DOWNLOADING_AUDIO, action=fail_stalled)
|
||||
assert "keep trying" in pushes[0]["body"]
|
||||
|
||||
@pytest.mark.parametrize("action", [_fail, _mark_failed])
|
||||
def test_second_worker_failing_the_same_run_does_not_push_again(self, triggers, action):
|
||||
def fail_twice(mgr):
|
||||
action(mgr)
|
||||
action(mgr)
|
||||
pushes, webpush = triggers(JobStatus.DOWNLOADING_AUDIO, action=fail_twice)
|
||||
assert len(pushes) == 1
|
||||
webpush.assert_called_once()
|
||||
|
||||
def test_already_notified_failure_does_not_push_again(self, triggers):
|
||||
pushes, webpush = triggers(JobStatus.FAILED, action=_fail, state_data={"failure_push_sent": True})
|
||||
assert pushes == []
|
||||
webpush.assert_not_called()
|
||||
|
||||
def test_cloud_run_retry_then_final_failure_pushes_once(self, triggers):
|
||||
"""Attempt 1 fails with a retry coming (no push); attempt 2 runs while the job
|
||||
is still FAILED, clears the marker and fails for good: that one pushes."""
|
||||
def two_attempts(mgr):
|
||||
mgr.fail_job("job1", "attempt 1", {"stage": "audio_download"})
|
||||
mgr.get_job("job1").state_data["cloud_run_retry_pending"] = None
|
||||
mgr.fail_job("job1", "attempt 2", {"stage": "audio_download"})
|
||||
pushes, webpush = triggers(JobStatus.DOWNLOADING_AUDIO, action=two_attempts, state_data=_pending(10))
|
||||
assert len(pushes) == 1
|
||||
webpush.assert_called_once()
|
||||
|
||||
def test_no_push_while_cloud_run_auto_retry_pending(self, triggers):
|
||||
pushes, webpush = triggers(JobStatus.DOWNLOADING_AUDIO, action=_fail, state_data=_pending(10))
|
||||
assert pushes == []
|
||||
webpush.assert_not_called()
|
||||
|
||||
def test_expired_retry_marker_still_pushes(self, triggers):
|
||||
pushes, _ = triggers(JobStatus.DOWNLOADING_AUDIO, action=_fail, state_data=_pending(-10))
|
||||
assert len(pushes) == 1
|
||||
|
||||
@pytest.mark.parametrize("notify_customer,expected", [(False, 0), (True, 1)])
|
||||
def test_admin_rerender_failure_respects_notify_customer(self, triggers, notify_customer, expected):
|
||||
pushes, _ = triggers(
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
action=_fail, state_data={"admin_rerender": {"notify_customer": notify_customer}},
|
||||
)
|
||||
assert len(pushes) == expected
|
||||
|
||||
def test_push_failure_never_breaks_fail_job(self, triggers, monkeypatch):
|
||||
monkeypatch.setattr(JobManager, "_send_push_notification", MagicMock(side_effect=RuntimeError("boom")))
|
||||
triggers(JobStatus.DOWNLOADING_AUDIO, action=_fail) # _fail asserts fail_job returned True
|
||||
|
||||
def test_transition_to_failed_with_notify_false_stays_silent(self, triggers):
|
||||
def transition(mgr):
|
||||
mgr.validate_state_transition = lambda *a, **k: True
|
||||
mgr.transition_to_state("job1", JobStatus.FAILED, notify=False)
|
||||
pushes, webpush = triggers(JobStatus.DOWNLOADING_AUDIO, action=transition)
|
||||
assert pushes == []
|
||||
webpush.assert_not_called()
|
||||
|
||||
|
||||
class TestTenantJobs:
|
||||
def test_tenant_job_skips_expo_push(self, triggers):
|
||||
pushes, _ = triggers(JobStatus.COMPLETE, tenant_id="acme")
|
||||
assert pushes == []
|
||||
|
||||
def test_tenant_job_failure_skips_expo_push(self, triggers):
|
||||
pushes, _ = triggers(JobStatus.DOWNLOADING_AUDIO, action=_fail, tenant_id="acme")
|
||||
assert pushes == []
|
||||
@@ -534,3 +534,17 @@ class TestKjboxQuickVersion:
|
||||
jm, storage = self._run_audio({"client_id": "web"})
|
||||
jm.update_file_url.assert_not_called()
|
||||
assert not [c for c in jm.update_state_data.call_args_list if c.args[1] == "quick_version"]
|
||||
|
||||
|
||||
class TestFakeAlbumSearch:
|
||||
def test_covers_every_track_in_confidence_shape(self):
|
||||
from backend.services.fake_workers.search import build_album_response
|
||||
from backend.services.bulk_album_search import choose_batch_torrent
|
||||
|
||||
tracks = [{"key": "j1", "title": "Song A", "position": 1}, {"key": "j2", "title": "Song B", "position": 2}]
|
||||
perfect = build_album_response("Fake Artist", "Fake Album", tracks, "perfect")
|
||||
torrent = perfect["results"][0]
|
||||
assert torrent["track_files"]["j2"]["target_file"] == "02 - Song B.flac"
|
||||
assert choose_batch_torrent(perfect["results"]) is torrent
|
||||
recommended = build_album_response("Fake Artist", "Fake Album", tracks, "recommended")
|
||||
assert choose_batch_torrent(recommended["results"]) is None
|
||||
@@ -242,6 +242,56 @@ class TestFlacfetchClientSearch:
|
||||
assert result["search_id"] is None
|
||||
|
||||
|
||||
class TestFlacfetchClientSearchAlbum:
|
||||
"""search_album(): one album search for an album-mode bulk batch."""
|
||||
|
||||
def _mock_http(self, mock_client_class, response):
|
||||
mock_client = AsyncMock()
|
||||
mock_client.post = AsyncMock(return_value=response)
|
||||
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client.__aexit__ = AsyncMock(return_value=None)
|
||||
mock_client_class.return_value = mock_client
|
||||
return mock_client
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_posts_album_and_tracks(self):
|
||||
client = FlacfetchClient(base_url="http://localhost:8080", api_key="test-key")
|
||||
resp = Mock(status_code=200)
|
||||
resp.json.return_value = {"results": [{"source_id": "1", "track_files": {}}], "results_count": 1}
|
||||
resp.raise_for_status = Mock()
|
||||
tracks = [{"key": "j1", "title": "Waterloo", "position": 1}]
|
||||
with patch("httpx.AsyncClient") as cls:
|
||||
http = self._mock_http(cls, resp)
|
||||
result = await client.search_album("ABBA", "Waterloo", tracks)
|
||||
assert result["results"][0]["source_id"] == "1"
|
||||
assert http.post.call_args.args[0] == "http://localhost:8080/search/album"
|
||||
assert http.post.call_args.kwargs["json"] == {"artist": "ABBA", "album": "Waterloo", "tracks": tracks}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_404_is_empty_results(self):
|
||||
"""No torrent, or an older flacfetch without the endpoint: caller falls back."""
|
||||
client = FlacfetchClient(base_url="http://localhost:8080", api_key="test-key")
|
||||
with patch("httpx.AsyncClient") as cls:
|
||||
self._mock_http(cls, Mock(status_code=404))
|
||||
result = await client.search_album("ABBA", "Waterloo", [{"key": "j1", "title": "Waterloo"}])
|
||||
assert result["results"] == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_server_error_raises_service_error(self):
|
||||
import httpx
|
||||
client = FlacfetchClient(base_url="http://localhost:8080", api_key="test-key")
|
||||
resp = Mock(status_code=502, text="all trackers failed")
|
||||
resp.raise_for_status = Mock(side_effect=httpx.HTTPStatusError(
|
||||
"bad gateway", request=Mock(), response=resp))
|
||||
with patch("httpx.AsyncClient") as cls, \
|
||||
patch("backend.services.flacfetch_client.get_settings") as gs:
|
||||
gs.return_value = Mock(flacfetch_search_total_timeout=5.0, flacfetch_search_retry_max_attempts=1,
|
||||
flacfetch_search_retry_wait=0)
|
||||
self._mock_http(cls, resp)
|
||||
with pytest.raises(FlacfetchServiceError):
|
||||
await client.search_album("ABBA", "Waterloo", [{"key": "j1", "title": "Waterloo"}])
|
||||
|
||||
|
||||
class TestFlacfetchClientDownload:
|
||||
"""Test download() method."""
|
||||
|
||||
|
||||
@@ -444,7 +444,7 @@ class TestSearchAndStart:
|
||||
search = MagicMock()
|
||||
search.search_async = AsyncMock(return_value=[MagicMock()])
|
||||
monkeypatch.setattr(khc, "AudioSearchService", lambda: search)
|
||||
monkeypatch.setattr(khc, "pick_auto_selection", lambda results, search_title: None)
|
||||
monkeypatch.setattr(khc, "pick_auto_selection", lambda results, search_title, search_artist="": None)
|
||||
with patch("backend.workers.bulk_search_worker._prepare_theme"):
|
||||
started = await khc._search_and_start("j1", "A", "T")
|
||||
|
||||
@@ -473,7 +473,7 @@ class TestSearchAndStart:
|
||||
search.search_async = AsyncMock(return_value=[MagicMock()])
|
||||
search.last_remote_search_id = "rs1"
|
||||
monkeypatch.setattr(khc, "AudioSearchService", lambda: search)
|
||||
monkeypatch.setattr(khc, "pick_auto_selection", lambda results, search_title: 0)
|
||||
monkeypatch.setattr(khc, "pick_auto_selection", lambda results, search_title, search_artist="": 0)
|
||||
worker = MagicMock()
|
||||
worker.trigger_audio_download_worker = AsyncMock(return_value=True)
|
||||
monkeypatch.setattr(khc, "get_worker_service", lambda: worker)
|
||||
|
||||
@@ -92,7 +92,7 @@ class FakeQuery:
|
||||
def limit(self, n):
|
||||
return FakeQuery(self.coll, self.filters, n)
|
||||
|
||||
def stream(self):
|
||||
def stream(self, transaction=None):
|
||||
out = []
|
||||
for doc_id, data in list(self.coll.docs.items()):
|
||||
if all(self._match(data, f) for f in self.filters):
|
||||
@@ -104,6 +104,8 @@ class FakeQuery:
|
||||
value = data.get(f.field_path)
|
||||
if f.op_string == "==":
|
||||
return value == f.value
|
||||
if f.op_string == "array_contains":
|
||||
return isinstance(value, list) and f.value in value
|
||||
if f.op_string == ">=":
|
||||
return value is not None and value >= f.value
|
||||
raise NotImplementedError(f.op_string)
|
||||
|
||||
@@ -54,6 +54,8 @@ def settings():
|
||||
admin_tokens="",
|
||||
login_codes_per_email_per_hour=5,
|
||||
login_codes_per_ip_per_hour=20,
|
||||
app_review_demo_email="",
|
||||
app_review_demo_code="",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -156,13 +156,20 @@ def _rows_response(fields, rows):
|
||||
|
||||
|
||||
class TestNormalizeAndDecode:
|
||||
def test_normalize_matches_decide_norm(self):
|
||||
from backend.services.musicbrainz_service import normalize_name
|
||||
assert normalize_name("AC/DC") == "ac dc"
|
||||
assert normalize_name(" Britney Spears ") == "britney spears"
|
||||
# Not accent-folded, like mb_artists.name_normalized.
|
||||
assert normalize_name("Beyoncé") == "beyonc"
|
||||
assert normalize_name("!!!") == ""
|
||||
def test_search_key_folds_accents_and_keeps_other_scripts(self):
|
||||
from backend.services.musicbrainz_service import search_key
|
||||
assert search_key("Maxïmo Park") == search_key("maximo park") == "maximo park"
|
||||
assert search_key("Beyoncé") == "beyonce"
|
||||
assert search_key("Motörhead") == "motorhead"
|
||||
assert search_key("Røyksopp") == "royksopp"
|
||||
assert search_key("Ægis Straße") == "aegis strasse"
|
||||
assert search_key("AC/DC") == "ac dc"
|
||||
assert search_key(" Britney Spears ") == "britney spears"
|
||||
# Non-Latin names keep their letters (decide's norm() blanks them).
|
||||
# (й loses its breve like any other combining mark; both sides fold the same.)
|
||||
assert search_key("Мумий Тролль") == search_key("мумии тролль") == "мумии тролль"
|
||||
assert search_key("宇多田ヒカル") == "宇多田ヒカル"
|
||||
assert search_key("!!!") == ""
|
||||
|
||||
def test_decode_rows_types(self):
|
||||
from backend.services.musicbrainz_service import _decode_rows
|
||||
@@ -190,19 +197,29 @@ class TestServiceCalls:
|
||||
monkeypatch.setattr(svc, "_query", fake_query)
|
||||
return svc, calls
|
||||
|
||||
async def test_search_artists_normalizes_and_ranks(self, monkeypatch):
|
||||
async def test_search_artists_matches_folded_names_and_aliases(self, monkeypatch):
|
||||
svc, calls = self._svc_with(monkeypatch, lambda sql, p: [
|
||||
{"artist_mbid": "abc", "artist_name": "AC/DC", "disambiguation": None,
|
||||
"artist_type": "Group", "area_name": "Australia", "match_rank": 0},
|
||||
"artist_type": "Group", "area_name": "Australia", "match_rank": 0, "alias": None},
|
||||
{"artist_mbid": "def", "artist_name": "AC/DC Jam", "disambiguation": "",
|
||||
"artist_type": None, "area_name": None, "match_rank": 1},
|
||||
"artist_type": None, "area_name": None, "match_rank": 1, "alias": "ACDC Jam"},
|
||||
])
|
||||
out = await svc.search_artists("AC/DC")
|
||||
assert calls[0][1] == {"q": "ac dc"}
|
||||
assert "mb_artists_normalized" in calls[0][0]
|
||||
out = await svc.search_artists(" AC/DC ")
|
||||
sql, params = calls[0]
|
||||
# Raw query goes to BigQuery; search_key() folds both sides there.
|
||||
assert params == {"q": "AC/DC"}
|
||||
assert "CREATE TEMP FUNCTION search_key" in sql
|
||||
assert "search_key(artist_name)" in sql and "search_key(@q)" in sql
|
||||
assert "mb_artists_normalized" in sql and "artist_alias" in sql
|
||||
assert out[0] == {"mbid": "abc", "name": "AC/DC", "disambiguation": "", "type": "Group",
|
||||
"country": "Australia", "score": 100}
|
||||
"country": "Australia", "alias": None, "score": 100}
|
||||
assert out[1]["score"] == 90
|
||||
assert out[1]["alias"] == "ACDC Jam"
|
||||
|
||||
async def test_search_artists_non_latin_query_hits_bigquery(self, monkeypatch):
|
||||
svc, calls = self._svc_with(monkeypatch, lambda sql, p: [])
|
||||
assert await svc.search_artists("宇多田") == []
|
||||
assert calls[0][1] == {"q": "宇多田"}
|
||||
|
||||
async def test_search_artists_blank_query_skips_bigquery(self, monkeypatch):
|
||||
svc, calls = self._svc_with(monkeypatch, lambda sql, p: [])
|
||||
|
||||
@@ -115,7 +115,7 @@ class TestSendPush:
|
||||
result = await push_service.send_push("a@b.com", "T", "B", "/x", "tag", "singa")
|
||||
assert result == 3
|
||||
assert seen["thread"] != loop_thread
|
||||
m.assert_called_once_with("a@b.com", "T", "B", "/x", "tag", "singa")
|
||||
m.assert_called_once_with("a@b.com", "T", "B", "/x", "tag", "singa", None)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_push_no_user(self, push_service):
|
||||
|
||||
@@ -355,7 +355,7 @@ class TestRecordEarning:
|
||||
|
||||
result = service.record_earning(
|
||||
referred_email="referred@example.com",
|
||||
stripe_session_id="cs_test_123",
|
||||
source_key="cs_test_123",
|
||||
purchase_amount_cents=1575,
|
||||
)
|
||||
assert result is not None
|
||||
@@ -399,7 +399,7 @@ class TestRecordEarning:
|
||||
|
||||
result = service.record_earning(
|
||||
referred_email="referred@example.com",
|
||||
stripe_session_id="cs_test_456",
|
||||
source_key="cs_test_456",
|
||||
purchase_amount_cents=1575,
|
||||
)
|
||||
assert result is None
|
||||
@@ -414,7 +414,7 @@ class TestRecordEarning:
|
||||
|
||||
result = service.record_earning(
|
||||
referred_email="user@example.com",
|
||||
stripe_session_id="cs_test_789",
|
||||
source_key="cs_test_789",
|
||||
purchase_amount_cents=1750,
|
||||
)
|
||||
assert result is None
|
||||
@@ -459,7 +459,7 @@ class TestRecordEarning:
|
||||
|
||||
result = service.record_earning(
|
||||
referred_email="referred@example.com",
|
||||
stripe_session_id="cs_test_tz",
|
||||
source_key="cs_test_tz",
|
||||
purchase_amount_cents=2800,
|
||||
)
|
||||
assert result is not None
|
||||
@@ -504,7 +504,7 @@ class TestRecordEarning:
|
||||
|
||||
result = service.record_earning(
|
||||
referred_email="referred@example.com",
|
||||
stripe_session_id="cs_test_tz_expired",
|
||||
source_key="cs_test_tz_expired",
|
||||
purchase_amount_cents=2800,
|
||||
)
|
||||
assert result is None
|
||||
@@ -894,7 +894,7 @@ class TestEarningCalculationEdgeCases:
|
||||
# 1999 * 20 / 100 = 399.8 -> should truncate to 399
|
||||
result = service.record_earning(
|
||||
referred_email="referred@example.com",
|
||||
stripe_session_id="cs_edge_1",
|
||||
source_key="cs_edge_1",
|
||||
purchase_amount_cents=1999,
|
||||
)
|
||||
assert result is not None
|
||||
@@ -938,7 +938,7 @@ class TestEarningCalculationEdgeCases:
|
||||
|
||||
result = service.record_earning(
|
||||
referred_email="referred@example.com",
|
||||
stripe_session_id="cs_edge_2",
|
||||
source_key="cs_edge_2",
|
||||
purchase_amount_cents=0,
|
||||
)
|
||||
assert result is None
|
||||
@@ -0,0 +1,508 @@
|
||||
"""Tests for in-app purchases: POST /api/users/webhooks/revenuecat + IapService.
|
||||
|
||||
Composed over the in-memory Firestore fake from test_kjbox_partner_api: the real
|
||||
users router, real IapService and real UserService. Only the referral service is
|
||||
a mock where a test asserts on what it receives.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes import users as users_routes
|
||||
from backend.config import get_settings
|
||||
from backend.services import iap_service as iap
|
||||
from backend.services.referral_service import REFERRAL_EARNINGS_COLLECTION, REFERRAL_LINKS_COLLECTION, ReferralService
|
||||
from backend.services.stripe_service import CREDIT_PACKAGES
|
||||
from backend.services.user_service import UserService
|
||||
from backend.tests.test_kjbox_partner_api import FakeDb, FakeTransaction
|
||||
|
||||
AUTH = "Bearer rc-test-secret"
|
||||
EMAIL = "buyer@example.com"
|
||||
APP_ID = "6f1c1b7e-1f0a-4d8e-9a39-0c4f7a1d2b3c"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
return FakeDb()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_service(db):
|
||||
svc = UserService.__new__(UserService)
|
||||
svc.db = db
|
||||
svc.settings = MagicMock()
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def referral():
|
||||
ref = MagicMock()
|
||||
ref.record_earning.return_value = None
|
||||
return ref
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def service(db, user_service, referral):
|
||||
return iap.IapService(
|
||||
db, user_service, referral_service=referral,
|
||||
transaction_runner=lambda fn: fn(FakeTransaction(db.txn_writes)),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch, service):
|
||||
monkeypatch.setattr(get_settings(), "revenuecat_webhook_auth", AUTH)
|
||||
app = FastAPI()
|
||||
app.include_router(users_routes.router, prefix="/api")
|
||||
app.dependency_overrides[iap.get_iap_service] = lambda: service
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _seed_user(db, credits=0, **extra):
|
||||
db.collection("gen_users").document(EMAIL).set({
|
||||
"email": EMAIL, "credits": credits, "app_user_id": APP_ID, "credit_transactions": [], **extra,
|
||||
})
|
||||
|
||||
|
||||
def _user(db):
|
||||
return db.collection("gen_users").docs[EMAIL]
|
||||
|
||||
|
||||
def _event(**over):
|
||||
event = {
|
||||
"type": "NON_RENEWING_PURCHASE",
|
||||
"app_user_id": APP_ID,
|
||||
"product_id": "nomad_credits_3",
|
||||
"transaction_id": "2000000123456789",
|
||||
"store": "APP_STORE",
|
||||
"price": 23.99,
|
||||
"currency": "USD",
|
||||
"country_code": "US",
|
||||
"takehome_percentage": 0.85,
|
||||
"environment": "PRODUCTION",
|
||||
}
|
||||
event.update(over)
|
||||
return {"event": event, "api_version": "1.0"}
|
||||
|
||||
|
||||
def _post(client, body, auth=AUTH):
|
||||
headers = {"Authorization": auth} if auth is not None else {}
|
||||
return client.post("/api/users/webhooks/revenuecat", json=body, headers=headers)
|
||||
|
||||
|
||||
class TestAuth:
|
||||
def test_rejects_bad_auth(self, client, db):
|
||||
_seed_user(db)
|
||||
assert _post(client, _event(), auth=None).status_code == 401
|
||||
assert _post(client, _event(), auth="Bearer wrong").status_code == 401
|
||||
assert _user(db)["credits"] == 0
|
||||
|
||||
def test_503_when_secret_unset(self, client, db, monkeypatch):
|
||||
monkeypatch.setattr(get_settings(), "revenuecat_webhook_auth", "")
|
||||
_seed_user(db)
|
||||
assert _post(client, _event(), auth="").status_code == 503
|
||||
assert _post(client, _event()).status_code == 503
|
||||
assert _user(db)["credits"] == 0
|
||||
|
||||
|
||||
class TestGrant:
|
||||
def test_grants_package_credits(self, client, db):
|
||||
_seed_user(db, credits=1)
|
||||
resp = _post(client, _event())
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["action"] == "granted"
|
||||
user = _user(db)
|
||||
assert user["credits"] == 4
|
||||
assert user["credit_transactions"][-1]["reason"] == "iap_purchase"
|
||||
assert user["credit_transactions"][-1]["amount"] == 3
|
||||
payment = db.collection("store_payments").docs["APP_STORE:2000000123456789"]
|
||||
assert payment["source"] == "app_store"
|
||||
assert payment["amount_total"] == 2399
|
||||
assert payment["net_amount"] == 2039 # 2399 × 0.85 = 2039.15, rounded down
|
||||
assert payment["unmatched"] is False
|
||||
assert payment["customer_email"] == EMAIL
|
||||
assert "APP_STORE:2000000123456789" in db.collection("processed_revenuecat_transactions").docs
|
||||
|
||||
def test_replay_is_noop(self, client, db):
|
||||
_seed_user(db)
|
||||
assert _post(client, _event()).json()["action"] == "granted"
|
||||
resp = _post(client, _event())
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["action"] == "duplicate"
|
||||
assert _user(db)["credits"] == 3
|
||||
assert len(_user(db)["credit_transactions"]) == 1
|
||||
|
||||
def test_play_store_is_a_separate_namespace(self, client, db):
|
||||
_seed_user(db)
|
||||
_post(client, _event(store="PLAY_STORE", transaction_id="GPA.1234-5678"))
|
||||
assert _user(db)["credits"] == 3
|
||||
assert db.collection("store_payments").docs["PLAY_STORE:GPA.1234-5678"]["source"] == "play_store"
|
||||
|
||||
def test_commit_race_already_exists_is_duplicate(self, service, db):
|
||||
"""A concurrent delivery creating the marker between read and commit → duplicate, no grant."""
|
||||
_seed_user(db)
|
||||
|
||||
def racing_runner(fn):
|
||||
from google.api_core import exceptions as google_exceptions
|
||||
raise google_exceptions.AlreadyExists("marker")
|
||||
|
||||
service._transaction_runner = racing_runner
|
||||
result = service.handle_event(_event()["event"])
|
||||
assert result.action == "duplicate"
|
||||
assert _user(db)["credits"] == 0
|
||||
assert "APP_STORE:2000000123456789" not in db.collection("store_payments").docs
|
||||
|
||||
def test_contention_is_503_so_revenuecat_retries(self, client, db, service, monkeypatch):
|
||||
from google.api_core import exceptions as google_exceptions
|
||||
|
||||
_seed_user(db)
|
||||
|
||||
def lock_timeout(_db, _fn):
|
||||
raise google_exceptions.Aborted("Transaction lock timeout.")
|
||||
|
||||
service._transaction_runner = None
|
||||
monkeypatch.setattr(iap, "run_firestore_transaction", lock_timeout)
|
||||
assert _post(client, _event()).status_code == 503
|
||||
assert _user(db)["credits"] == 0
|
||||
assert db.collection("store_payments").docs == {}
|
||||
|
||||
def test_sandbox_grants_but_is_test_and_no_referral(self, client, db, referral):
|
||||
_seed_user(db, total_spent=500)
|
||||
_post(client, _event(environment="SANDBOX"))
|
||||
assert _user(db)["credits"] == 3
|
||||
assert _user(db)["total_spent"] == 500 # sandbox is not real spend
|
||||
assert db.collection("store_payments").docs["APP_STORE:2000000123456789"]["is_test"] is True
|
||||
referral.record_earning.assert_not_called()
|
||||
|
||||
def test_total_spent_up_on_purchase_down_on_refund(self, client, db):
|
||||
_seed_user(db, total_spent=500)
|
||||
_post(client, _event())
|
||||
assert _user(db)["total_spent"] == 500 + 2399
|
||||
_post(client, _event(type="CANCELLATION", cancel_reason="CUSTOMER_SUPPORT", price=-23.99))
|
||||
assert _user(db)["total_spent"] == 500
|
||||
|
||||
def test_user_deleted_mid_transaction_is_unknown_user(self, service, db, user_service, caplog):
|
||||
"""The doc vanishes between lookup and transaction: 200 unknown_user, unmatched, ERROR."""
|
||||
_seed_user(db)
|
||||
ref = user_service.get_user_doc_ref(EMAIL)
|
||||
service.user_service = MagicMock(wraps=user_service)
|
||||
service.user_service.find_by_app_user_id.side_effect = user_service.find_by_app_user_id
|
||||
|
||||
def lookup_then_delete(email):
|
||||
db.collection("gen_users").document(EMAIL).delete()
|
||||
return ref
|
||||
|
||||
service.user_service.get_user_doc_ref.side_effect = lookup_then_delete
|
||||
with caplog.at_level(logging.ERROR, logger="backend.services.iap_service"):
|
||||
result = service.handle_event(_event()["event"])
|
||||
assert result.action == "unknown_user"
|
||||
assert db.collection("store_payments").docs["APP_STORE:2000000123456789"]["unmatched"] is True
|
||||
assert "APP_STORE:2000000123456789" not in db.collection("processed_revenuecat_transactions").docs
|
||||
assert any(r.levelno == logging.ERROR for r in caplog.records)
|
||||
|
||||
def test_anonymous_app_user_id_falls_back_to_alias(self, client, db):
|
||||
_seed_user(db)
|
||||
resp = _post(client, _event(app_user_id="$RCAnonymousID:abc", aliases=["$RCAnonymousID:abc", APP_ID]))
|
||||
assert resp.json()["action"] == "granted"
|
||||
assert _user(db)["credits"] == 3
|
||||
|
||||
|
||||
class TestRefund:
|
||||
def test_refund_debits_and_can_go_negative(self, client, db):
|
||||
_seed_user(db)
|
||||
_post(client, _event(product_id="nomad_credits_1", price=9.99))
|
||||
assert _user(db)["credits"] == 1
|
||||
db.collection("gen_users").document(EMAIL).update({"credits": 0}) # the credit is spent on a job
|
||||
|
||||
refund = _event(type="CANCELLATION", cancel_reason="CUSTOMER_SUPPORT",
|
||||
product_id="nomad_credits_1", price=-9.99)
|
||||
resp = _post(client, refund)
|
||||
assert resp.status_code == 200 and resp.json()["action"] == "debited"
|
||||
user = _user(db)
|
||||
assert user["credits"] == -1
|
||||
assert user["credit_transactions"][-1]["reason"] == "iap_refund"
|
||||
assert user["credit_transactions"][-1]["amount"] == -1
|
||||
payment = db.collection("store_payments").docs["APP_STORE:2000000123456789"]
|
||||
assert payment["status"] == "refunded" and payment["refund_amount"] == 999
|
||||
|
||||
replay = _post(client, refund)
|
||||
assert replay.json()["action"] == "duplicate"
|
||||
assert _user(db)["credits"] == -1
|
||||
|
||||
def test_refund_alias_type(self, client, db):
|
||||
_seed_user(db)
|
||||
_post(client, _event())
|
||||
resp = _post(client, _event(type="REFUND", price=-23.99))
|
||||
assert resp.json()["action"] == "debited"
|
||||
assert _user(db)["credits"] == 0
|
||||
|
||||
def test_refund_without_granted_purchase_debits_nothing(self, client, db):
|
||||
_seed_user(db, credits=2)
|
||||
resp = _post(client, _event(type="CANCELLATION", price=-23.99))
|
||||
assert resp.status_code == 200 and resp.json()["action"] == "ignored"
|
||||
assert _user(db)["credits"] == 2
|
||||
# No payment on record: none is invented.
|
||||
assert db.collection("store_payments").docs == {}
|
||||
|
||||
def test_refund_before_purchase_blocks_the_late_grant(self, client, db):
|
||||
_seed_user(db)
|
||||
refund = _event(type="CANCELLATION", cancel_reason="CUSTOMER_SUPPORT", price=-23.99)
|
||||
assert _post(client, refund).json()["action"] == "ignored"
|
||||
assert _post(client, refund).json()["action"] == "duplicate"
|
||||
late = _post(client, _event())
|
||||
assert late.status_code == 200 and late.json()["action"] == "ignored"
|
||||
assert _user(db)["credits"] == 0
|
||||
assert _user(db)["credit_transactions"] == []
|
||||
|
||||
def test_purchase_then_refund_order_still_debits(self, client, db):
|
||||
_seed_user(db)
|
||||
assert _post(client, _event()).json()["action"] == "granted"
|
||||
refund = _event(type="CANCELLATION", cancel_reason="CUSTOMER_SUPPORT", price=-23.99)
|
||||
assert _post(client, refund).json()["action"] == "debited"
|
||||
assert _post(client, _event()).json()["action"] == "duplicate"
|
||||
assert _user(db)["credits"] == 0
|
||||
|
||||
def test_non_refund_cancellation_changes_nothing(self, client, db, caplog):
|
||||
_seed_user(db)
|
||||
_post(client, _event())
|
||||
with caplog.at_level(logging.WARNING, logger="backend.services.iap_service"):
|
||||
resp = _post(client, _event(type="CANCELLATION", cancel_reason="BILLING_ERROR", price=23.99))
|
||||
assert resp.status_code == 200 and resp.json()["action"] == "ignored"
|
||||
assert _user(db)["credits"] == 3
|
||||
assert db.collection("store_payments").docs["APP_STORE:2000000123456789"]["status"] == "succeeded"
|
||||
assert "APP_STORE:2000000123456789:refund" not in db.collection("processed_revenuecat_transactions").docs
|
||||
assert any("BILLING_ERROR" in r.getMessage() for r in caplog.records if r.levelno == logging.WARNING)
|
||||
# A real refund afterwards still works.
|
||||
refund = _event(type="CANCELLATION", cancel_reason="CUSTOMER_SUPPORT", price=-23.99)
|
||||
assert _post(client, refund).json()["action"] == "debited"
|
||||
|
||||
def test_refund_detection(self):
|
||||
assert iap.is_refund({"type": "REFUND"})
|
||||
assert iap.is_refund({"type": "CANCELLATION", "price": -9.99})
|
||||
assert iap.is_refund({"type": "CANCELLATION", "cancel_reason": "CUSTOMER_SUPPORT", "price": 9.99})
|
||||
assert not iap.is_refund({"type": "CANCELLATION", "cancel_reason": "UNSUBSCRIBE", "price": 9.99})
|
||||
assert not iap.is_refund({"type": "CANCELLATION"})
|
||||
|
||||
def test_refund_after_account_deleted_is_200_noop(self, client, db):
|
||||
_seed_user(db)
|
||||
_post(client, _event())
|
||||
db.collection("gen_users").document(EMAIL).delete()
|
||||
resp = _post(client, _event(type="CANCELLATION", price=-23.99))
|
||||
assert resp.status_code == 200 and resp.json()["action"] == "ignored"
|
||||
assert db.collection("store_payments").docs["APP_STORE:2000000123456789"]["status"] == "refunded"
|
||||
|
||||
def test_refund_debits_the_account_that_was_granted(self, client, db):
|
||||
"""The debit follows the purchase marker's email, not the refund event's app_user_id."""
|
||||
_seed_user(db)
|
||||
_post(client, _event())
|
||||
resp = _post(client, _event(type="CANCELLATION", price=-23.99, app_user_id="someone-else"))
|
||||
assert resp.json()["action"] == "debited"
|
||||
assert _user(db)["credits"] == 0
|
||||
|
||||
|
||||
class TestUnmatched:
|
||||
def test_unknown_user_records_and_200(self, client, db, caplog):
|
||||
_seed_user(db)
|
||||
with caplog.at_level(logging.WARNING, logger="backend.services.iap_service"):
|
||||
resp = _post(client, _event(app_user_id="not-a-known-id"))
|
||||
assert resp.status_code == 200 and resp.json()["action"] == "unknown_user"
|
||||
assert _user(db)["credits"] == 0
|
||||
errors = [r.getMessage() for r in caplog.records if r.levelno == logging.ERROR]
|
||||
assert len(errors) == 1
|
||||
assert "not-a-known-id" in errors[0] and "APP_STORE" in errors[0] and "2000000123456789" in errors[0]
|
||||
payment = db.collection("store_payments").docs["APP_STORE:2000000123456789"]
|
||||
assert payment["unmatched"] is True
|
||||
assert payment["credits_granted"] == 0
|
||||
assert "APP_STORE:2000000123456789" not in db.collection("processed_revenuecat_transactions").docs
|
||||
|
||||
def test_unknown_product_200_no_grant(self, client, db):
|
||||
_seed_user(db)
|
||||
resp = _post(client, _event(product_id="nomad_credits_999"))
|
||||
assert resp.status_code == 200 and resp.json()["action"] == "unknown_product"
|
||||
assert _user(db)["credits"] == 0
|
||||
assert db.collection("store_payments").docs == {}
|
||||
|
||||
def test_other_event_types_ignored(self, client, db):
|
||||
_seed_user(db)
|
||||
assert _post(client, _event(type="TEST")).json()["action"] == "ignored"
|
||||
assert _post(client, _event(store="PROMOTIONAL")).json()["action"] == "ignored"
|
||||
assert _user(db)["credits"] == 0
|
||||
|
||||
def test_malformed_body_400(self, client):
|
||||
resp = client.post("/api/users/webhooks/revenuecat", content=b"not json",
|
||||
headers={"Authorization": AUTH, "Content-Type": "application/json"})
|
||||
assert resp.status_code == 400
|
||||
assert _post(client, {"api_version": "1.0"}).status_code == 400
|
||||
|
||||
|
||||
class TestReferral:
|
||||
def test_referral_earning_on_net(self, client, db, referral):
|
||||
_seed_user(db)
|
||||
_post(client, _event(product_id="nomad_credits_10", price=59.99, takehome_percentage=0.85))
|
||||
referral.record_earning.assert_called_once_with(
|
||||
referred_email=EMAIL,
|
||||
source_key="APP_STORE:2000000123456789",
|
||||
purchase_amount_cents=5099,
|
||||
source="app_store",
|
||||
)
|
||||
|
||||
def test_referral_earning_defaults_takehome(self, client, db, referral):
|
||||
_seed_user(db)
|
||||
event = _event(product_id="nomad_credits_10", price=59.99)
|
||||
del event["event"]["takehome_percentage"]
|
||||
_post(client, event)
|
||||
assert referral.record_earning.call_args.kwargs["purchase_amount_cents"] == 5099
|
||||
|
||||
def test_replay_records_no_second_earning(self, client, db, referral):
|
||||
_seed_user(db)
|
||||
_post(client, _event())
|
||||
_post(client, _event())
|
||||
assert referral.record_earning.call_count == 1
|
||||
|
||||
def test_record_earning_stores_store_source(self, db):
|
||||
"""Real ReferralService: store rows get source + store_transaction_id, Stripe rows keep stripe_session_id."""
|
||||
from datetime import datetime
|
||||
|
||||
db.collection("gen_users").document(EMAIL).set({
|
||||
"email": EMAIL, "referred_by_code": "abc12345", "referred_at": datetime.utcnow(),
|
||||
})
|
||||
db.collection(REFERRAL_LINKS_COLLECTION).document("abc12345").set({
|
||||
"code": "abc12345", "owner_email": "referrer@example.com", "kickback_percent": 20,
|
||||
"stats": {"purchases": 0, "total_earned_cents": 0},
|
||||
})
|
||||
svc = ReferralService(db=db)
|
||||
store = svc.record_earning(EMAIL, source_key="APP_STORE:1", purchase_amount_cents=5099, source="app_store")
|
||||
stripe_row = svc.record_earning(EMAIL, source_key="cs_test_1", purchase_amount_cents=1000)
|
||||
earnings = db.collection(REFERRAL_EARNINGS_COLLECTION).docs
|
||||
s = earnings[store["earning_id"]]
|
||||
assert s["source"] == "app_store" and s["store_transaction_id"] == "APP_STORE:1"
|
||||
assert s["stripe_session_id"] is None and s["earning_amount_cents"] == 1019
|
||||
p = earnings[stripe_row["earning_id"]]
|
||||
assert p["source"] == "stripe" and p["stripe_session_id"] == "cs_test_1"
|
||||
|
||||
|
||||
class TestPackages:
|
||||
def test_packages_include_store_ids_and_web_link(self, client):
|
||||
body = client.get("/api/users/credits/packages").json()
|
||||
by_id = {p["id"]: p for p in body["packages"]}
|
||||
assert by_id["1_credit"]["store_product_id"] == "nomad_credits_1"
|
||||
assert by_id["3_credits"]["store_product_id"] == "nomad_credits_3"
|
||||
assert by_id["5_credits"]["store_product_id"] == "nomad_credits_5"
|
||||
assert by_id["10_credits"]["store_product_id"] == "nomad_credits_10"
|
||||
assert body["web_link"] == {
|
||||
"show_for": {"ios": ["USA"], "android": []},
|
||||
"copy_key": "credits.webLink.default",
|
||||
}
|
||||
|
||||
def test_every_store_product_maps_to_one_package(self):
|
||||
ids = [p["store_product_id"] for p in CREDIT_PACKAGES.values()]
|
||||
assert sorted(ids) == ["nomad_credits_1", "nomad_credits_10", "nomad_credits_3", "nomad_credits_5"]
|
||||
assert iap.package_for_product("nomad_credits_5") == ("5_credits", CREDIT_PACKAGES["5_credits"])
|
||||
|
||||
|
||||
class TestFindByAppUserId:
|
||||
def test_finds_and_misses(self, db, user_service):
|
||||
_seed_user(db)
|
||||
assert user_service.find_by_app_user_id(APP_ID).email == EMAIL
|
||||
assert user_service.find_by_app_user_id("nope") is None
|
||||
assert user_service.find_by_app_user_id("") is None
|
||||
|
||||
|
||||
class TestNegativeBalance:
|
||||
def test_make_refused_when_negative(self, db, user_service):
|
||||
"""A refunded-after-spend account (credits < 0) gets 402 on job create."""
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.main import insufficient_credits_exception_handler
|
||||
from backend.models.job import JobCreate
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
_seed_user(db, credits=-1)
|
||||
with patch("backend.services.job_manager.FirestoreService") as fs, \
|
||||
patch("backend.services.job_manager.StorageService"), \
|
||||
patch("backend.services.user_service.get_user_service", return_value=user_service):
|
||||
manager = JobManager()
|
||||
app = FastAPI()
|
||||
app.add_exception_handler(InsufficientCreditsError, insufficient_credits_exception_handler)
|
||||
|
||||
@app.post("/make")
|
||||
def make():
|
||||
manager.create_job(
|
||||
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email=EMAIL), is_admin=False,
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
resp = TestClient(app).post("/make")
|
||||
assert resp.status_code == 402
|
||||
assert resp.json()["credits_available"] == -1
|
||||
fs.return_value.create_job.assert_not_called()
|
||||
assert _user(db)["credits"] == -1
|
||||
|
||||
|
||||
class TestFakeIapRoutes:
|
||||
@pytest.fixture
|
||||
def fake_client(self, monkeypatch, service, user_service):
|
||||
from backend.api.routes import test_support
|
||||
|
||||
monkeypatch.setattr(iap, "get_iap_service", lambda: service)
|
||||
monkeypatch.setattr("backend.services.user_service.get_user_service", lambda: user_service)
|
||||
monkeypatch.setattr(user_service, "ensure_app_user_id", lambda email: APP_ID)
|
||||
app = FastAPI()
|
||||
app.include_router(test_support.router, prefix="/api")
|
||||
return TestClient(app)
|
||||
|
||||
def test_purchase_then_refund(self, fake_client, db):
|
||||
_seed_user(db)
|
||||
bought = fake_client.post("/api/test/fake-iap/purchase",
|
||||
json={"email": EMAIL, "product_id": "nomad_credits_5"}).json()
|
||||
assert bought["action"] == "granted" and bought["credits"] == 5
|
||||
payment = db.collection("store_payments").docs[f"APP_STORE:{bought['transaction_id']}"]
|
||||
assert payment["amount_total"] == 3499 and payment["is_test"] is True
|
||||
|
||||
refunded = fake_client.post("/api/test/fake-iap/refund", json={
|
||||
"transaction_id": bought["transaction_id"], "product_id": "nomad_credits_5",
|
||||
}).json()
|
||||
assert refunded["action"] == "debited" and refunded["credits"] == 0
|
||||
|
||||
def test_purchase_needs_a_user(self, fake_client):
|
||||
resp = fake_client.post("/api/test/fake-iap/purchase", json={"product_id": "nomad_credits_1"})
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
class TestAdminRevenue:
|
||||
def test_revenue_summary_includes_store_payments(self, client, db, monkeypatch):
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.services import stripe_admin_service as sas
|
||||
from backend.services.stripe_admin_service import StripeAdminService
|
||||
|
||||
# Other test modules can leave google.cloud.firestore_v1 mocked when this
|
||||
# module is first imported; give the Firestore fake a real-shaped filter.
|
||||
monkeypatch.setattr(sas, "FieldFilter", lambda f, op, v: SimpleNamespace(field_path=f, op_string=op, value=v))
|
||||
|
||||
_seed_user(db)
|
||||
_post(client, _event()) # $23.99 store purchase, 85% takehome
|
||||
db.collection("stripe_payments").document("cs_1").set({
|
||||
"amount_total": 1000, "stripe_fee": 59, "net_amount": 941, "refund_amount": 0,
|
||||
"order_type": "credit_purchase", "is_test": False, "created_at": datetime.utcnow(),
|
||||
})
|
||||
admin = StripeAdminService.__new__(StripeAdminService)
|
||||
admin.db = db
|
||||
admin._revenue_cache = None
|
||||
admin._revenue_cache_time = 0
|
||||
admin._revenue_cache_ttl = 300
|
||||
|
||||
summary = admin.get_revenue_summary(days=30)
|
||||
assert summary["total_gross"] == 1000 + 2399
|
||||
assert summary["total_fees"] == 59 + (2399 - 2039)
|
||||
assert summary["total_net"] == 941 + 2039
|
||||
assert summary["transaction_count"] == 2
|
||||
assert summary["revenue_by_type"]["app_store_credit_purchase"] == 2399
|
||||
|
||||
by_day = admin.get_revenue_by_period(days=30)
|
||||
assert sum(b["gross"] for b in by_day) == 3399
|
||||
@@ -0,0 +1,64 @@
|
||||
"""App Review demo sign-in: one configured email signs in with a fixed code."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.api.routes import login_code
|
||||
from backend.tests.test_login_code_api import ( # noqa: F401 (fixtures)
|
||||
EMAIL,
|
||||
_verify,
|
||||
client,
|
||||
db,
|
||||
email_service,
|
||||
precompute,
|
||||
settings,
|
||||
signup_limited,
|
||||
user_service,
|
||||
validation,
|
||||
)
|
||||
|
||||
DEMO_EMAIL = "reviewer@example.com"
|
||||
DEMO_CODE = "424242"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def demo(settings):
|
||||
settings.app_review_demo_email = DEMO_EMAIL
|
||||
settings.app_review_demo_code = DEMO_CODE
|
||||
return settings
|
||||
|
||||
|
||||
def test_demo_code_inert_when_unset(client, settings):
|
||||
# Neither field configured on the settings object at all.
|
||||
assert _verify(client, DEMO_CODE, email=DEMO_EMAIL).status_code == 401
|
||||
settings.app_review_demo_email = DEMO_EMAIL
|
||||
settings.app_review_demo_code = ""
|
||||
assert _verify(client, "", email=DEMO_EMAIL).status_code == 401
|
||||
settings.app_review_demo_email = ""
|
||||
settings.app_review_demo_code = DEMO_CODE
|
||||
assert _verify(client, DEMO_CODE, email="").status_code in (401, 422)
|
||||
|
||||
|
||||
def test_demo_code_only_for_demo_email(client, demo):
|
||||
resp = _verify(client, DEMO_CODE, email="someone-else@example.com")
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
def test_demo_code_signs_in(client, demo, caplog):
|
||||
with caplog.at_level(logging.INFO, logger=login_code.logger.name):
|
||||
resp = _verify(client, DEMO_CODE, email=DEMO_EMAIL.upper())
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["session_token"]
|
||||
assert "app review demo login" in caplog.text
|
||||
# Reusable, and wrong codes for the demo email are rejected.
|
||||
assert _verify(client, DEMO_CODE, email=DEMO_EMAIL).status_code == 200
|
||||
assert _verify(client, "111111", email=DEMO_EMAIL).status_code == 401
|
||||
|
||||
|
||||
def test_attempt_limit_still_applies(client, demo):
|
||||
for _ in range(5):
|
||||
assert _verify(client, "111111", email=DEMO_EMAIL).status_code == 401
|
||||
# Even the right code is refused once locked out.
|
||||
assert _verify(client, DEMO_CODE, email=DEMO_EMAIL).status_code == 429
|
||||
@@ -71,6 +71,8 @@ def settings():
|
||||
admin_tokens="",
|
||||
login_codes_per_email_per_hour=5,
|
||||
login_codes_per_ip_per_hour=20,
|
||||
app_review_demo_email="",
|
||||
app_review_demo_code="",
|
||||
google_oauth_client_ids=f"{GOOGLE_AUD}, ios-client.apps.googleusercontent.com",
|
||||
apple_signin_audiences=APPLE_AUD,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Tests for the mobile-app fields on GET /api/users/me (app_user_id, capabilities, push_prefs)."""
|
||||
import sys
|
||||
import uuid
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
from backend.main import app
|
||||
from backend.models.user import ExpoPushToken, User
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.services.user_service import UserService, get_user_service
|
||||
|
||||
EMAIL = "singer@example.com"
|
||||
|
||||
|
||||
class FakeUserService:
|
||||
"""Mints like the real service: once, then returns the stored id."""
|
||||
|
||||
def __init__(self, user):
|
||||
self.user = user
|
||||
|
||||
def get_or_create_user(self, email, **kwargs):
|
||||
return self.user
|
||||
|
||||
def ensure_app_user_id(self, email):
|
||||
if not self.user.app_user_id:
|
||||
self.user.app_user_id = str(uuid.uuid4())
|
||||
return self.user.app_user_id
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user():
|
||||
return User(email=EMAIL)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(user):
|
||||
svc = FakeUserService(user)
|
||||
app.dependency_overrides[get_user_service] = lambda: svc
|
||||
auth = MagicMock()
|
||||
auth.validate_token_full.return_value = AuthResult(
|
||||
is_valid=True, user_type=UserType.UNLIMITED, remaining_uses=-1,
|
||||
message="ok", user_email=EMAIL, is_admin=False,
|
||||
)
|
||||
with patch("backend.services.auth_service.get_auth_service", return_value=auth):
|
||||
yield TestClient(app)
|
||||
app.dependency_overrides.pop(get_user_service, None)
|
||||
|
||||
|
||||
def _me(client):
|
||||
r = client.get("/api/users/me", headers={"Authorization": "Bearer tok"})
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def test_me_mints_app_user_id_once(client):
|
||||
first = _me(client)["app_user_id"]
|
||||
second = _me(client)["app_user_id"]
|
||||
assert first == second
|
||||
assert uuid.UUID(first).version == 4
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [False, True])
|
||||
def test_me_capabilities_reflect_flag(client, enabled):
|
||||
with patch("backend.api.routes.users.get_settings") as gs:
|
||||
gs.return_value.account_deletion_enabled = enabled
|
||||
assert _me(client)["capabilities"] == {"account_deletion": enabled}
|
||||
|
||||
|
||||
def test_me_push_prefs_default_true(client, user):
|
||||
assert _me(client)["push_prefs"] == {"ready": True, "review": True, "problems": True}
|
||||
user.push_prefs = {"review": False, "bogus": False}
|
||||
assert _me(client)["push_prefs"] == {"ready": True, "review": False, "problems": True}
|
||||
|
||||
|
||||
def test_expo_push_token_model_validates_platform():
|
||||
t = ExpoPushToken(token="ExponentPushToken[x]", platform="ios", device_id="d1")
|
||||
assert t.last_used_at is None
|
||||
with pytest.raises(ValueError):
|
||||
ExpoPushToken(token="t", platform="web", device_id="d")
|
||||
|
||||
|
||||
class _Snap:
|
||||
def __init__(self, data):
|
||||
self.exists = data is not None
|
||||
self._d = data
|
||||
|
||||
def to_dict(self):
|
||||
return self._d
|
||||
|
||||
|
||||
def _service(stored):
|
||||
svc = UserService.__new__(UserService)
|
||||
svc.db = MagicMock()
|
||||
ref = MagicMock()
|
||||
ref.get.return_value = _Snap(stored)
|
||||
txn = MagicMock()
|
||||
svc.db.transaction.return_value = txn
|
||||
svc.get_user_doc_ref = lambda email: ref
|
||||
return svc, ref, txn
|
||||
|
||||
|
||||
def test_ensure_app_user_id_sets_when_absent_and_keeps_when_present():
|
||||
with patch("backend.services.user_service.firestore.transactional", lambda f: f):
|
||||
svc, ref, txn = _service({"email": EMAIL})
|
||||
minted = svc.ensure_app_user_id(EMAIL)
|
||||
assert uuid.UUID(minted).version == 4
|
||||
txn.set.assert_called_once_with(ref, {"app_user_id": minted}, merge=True)
|
||||
|
||||
svc, ref, txn = _service({"email": EMAIL, "app_user_id": "existing-id"})
|
||||
assert svc.ensure_app_user_id(EMAIL) == "existing-id"
|
||||
txn.set.assert_not_called()
|
||||
|
||||
|
||||
def test_me_skips_minting_when_user_already_has_app_user_id(client, user):
|
||||
user.app_user_id = "stored-id"
|
||||
with patch.object(FakeUserService, "ensure_app_user_id", side_effect=AssertionError("no txn")):
|
||||
assert _me(client)["app_user_id"] == "stored-id"
|
||||
|
||||
|
||||
def test_me_returns_null_app_user_id_when_minting_fails(client, caplog):
|
||||
with patch.object(FakeUserService, "ensure_app_user_id", side_effect=RuntimeError("contention")):
|
||||
with caplog.at_level("WARNING", logger="backend.api.routes.users"):
|
||||
body = _me(client)
|
||||
assert body["app_user_id"] is None
|
||||
assert body["user"]["email"] == EMAIL
|
||||
assert any("app_user_id" in r.message and r.levelname == "WARNING" for r in caplog.records)
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Tests for the voice-pool separate-only worker (synthetic data only)."""
|
||||
import json
|
||||
import os
|
||||
|
||||
from backend.workers import voice_pool_separate_worker as w
|
||||
|
||||
BUCKET = "karaoke-gen-storage-nomadkaraoke"
|
||||
MANIFEST = "gs://karaoke-gen-storage-nomadkaraoke/voice-pool/manifests/run1.jsonl"
|
||||
|
||||
|
||||
class FakeStorage:
|
||||
def __init__(self, ids, existing=()):
|
||||
lines = "".join(
|
||||
json.dumps({"id": i, "audio": f"gs://{BUCKET}/voice-pool/audio/{i}/original.flac"}) + "\n" for i in ids
|
||||
)
|
||||
self.blobs = {"voice-pool/manifests/run1.jsonl": lines.encode()}
|
||||
for i in existing:
|
||||
self.blobs[f"voice-pool/stems/{i}/vocals.flac"] = b"x"
|
||||
self.downloads = []
|
||||
|
||||
def download_bytes(self, p):
|
||||
return self.blobs[p]
|
||||
|
||||
def file_exists(self, p):
|
||||
return p in self.blobs
|
||||
|
||||
def download_file(self, src, dest):
|
||||
self.downloads.append(src)
|
||||
open(dest, "wb").write(b"audio")
|
||||
return dest
|
||||
|
||||
def upload_file(self, local, dest):
|
||||
self.blobs[dest] = open(local, "rb").read()
|
||||
return dest
|
||||
|
||||
def upload_text(self, dest, text, content_type="text/plain"):
|
||||
self.blobs[dest] = text.encode()
|
||||
return dest
|
||||
|
||||
|
||||
class FakeSeparator:
|
||||
def __init__(self, out_dir, fail_ids=()):
|
||||
self.out_dir, self.fail_ids, self.calls = out_dir, fail_ids, 0
|
||||
|
||||
def separate(self, path):
|
||||
self.calls += 1
|
||||
if any(f in str(self.calls) for f in self.fail_ids):
|
||||
raise RuntimeError("boom")
|
||||
paths = []
|
||||
for tag in ("Vocals", "Instrumental"):
|
||||
p = os.path.join(self.out_dir, f"{self.calls}_({tag})_preset_instrumental_clean.flac")
|
||||
open(p, "wb").write(tag.encode())
|
||||
paths.append(p)
|
||||
return paths
|
||||
|
||||
|
||||
def _results(storage, idx=0):
|
||||
raw = storage.blobs[f"voice-pool/manifests/run1.results/part-{idx}.jsonl"].decode()
|
||||
return [json.loads(x) for x in raw.splitlines()]
|
||||
|
||||
|
||||
def test_shard_complete_and_disjoint():
|
||||
lines = [{"id": str(i)} for i in range(23)]
|
||||
parts = [w.shard(lines, i, 4) for i in range(4)]
|
||||
flat = [x["id"] for p in parts for x in p]
|
||||
assert sorted(flat) == sorted(x["id"] for x in lines)
|
||||
assert len(set(flat)) == 23
|
||||
assert [x["id"] for x in parts[1]] == ["1", "5", "9", "13", "17", "21"]
|
||||
|
||||
|
||||
def test_vocals_path_from_outputs():
|
||||
paths = [
|
||||
"/o/x_(Instrumental)_preset_instrumental_clean.flac",
|
||||
"/o/x_(Vocals)_preset_instrumental_clean.flac",
|
||||
]
|
||||
assert w.vocals_path_from_outputs(paths) == paths[1]
|
||||
assert w.vocals_path_from_outputs(paths[:1]) is None
|
||||
assert w.vocals_path_from_outputs(["/o/x_(No Vocal)_preset_instrumental_clean.flac"]) is None
|
||||
|
||||
|
||||
def test_run_manifest_skips_existing_and_records_failures(tmp_path):
|
||||
storage = FakeStorage(["a", "b", "c"], existing=["a"])
|
||||
sep = FakeSeparator(str(tmp_path), fail_ids=("1",)) # first real separation raises
|
||||
built = []
|
||||
|
||||
def factory():
|
||||
built.append(1)
|
||||
return sep
|
||||
|
||||
results = w.run_manifest(storage, factory, MANIFEST, 0, 1, bucket=BUCKET)
|
||||
by_id = {r["id"]: r for r in results}
|
||||
assert by_id["a"]["ok"] and by_id["a"]["seconds"] == 0
|
||||
assert not by_id["b"]["ok"] and "boom" in by_id["b"]["error"]
|
||||
assert by_id["c"]["ok"] and by_id["c"]["vocals"] == "voice-pool/stems/c/vocals.flac"
|
||||
assert storage.blobs["voice-pool/stems/c/vocals.flac"] == b"Vocals"
|
||||
assert "voice-pool/stems/b/vocals.flac" not in storage.blobs
|
||||
assert "voice-pool/audio/a/original.flac" not in storage.downloads
|
||||
assert len(built) == 1 # one separator reused
|
||||
assert _results(storage) == results
|
||||
assert os.listdir(tmp_path) == [] # stems cleaned up
|
||||
|
||||
|
||||
def test_results_written_every_10(tmp_path, monkeypatch):
|
||||
ids = [str(i) for i in range(12)]
|
||||
storage = FakeStorage(ids)
|
||||
writes = []
|
||||
orig = w._write_results
|
||||
monkeypatch.setattr(w, "_write_results", lambda s, m, i, r: (writes.append(len(r)), orig(s, m, i, r)))
|
||||
w.run_manifest(storage, lambda: FakeSeparator(str(tmp_path)), MANIFEST, 0, 1, bucket=BUCKET)
|
||||
assert writes == [10, 12]
|
||||
|
||||
|
||||
def test_sharded_task_only_processes_its_share(tmp_path):
|
||||
storage = FakeStorage([str(i) for i in range(6)])
|
||||
w.run_manifest(storage, lambda: FakeSeparator(str(tmp_path)), MANIFEST, 1, 3, bucket=BUCKET)
|
||||
assert [r["id"] for r in _results(storage, 1)] == ["1", "4"]
|
||||
|
||||
|
||||
def test_separator_load_failure_fails_fast(tmp_path):
|
||||
import pytest
|
||||
|
||||
storage = FakeStorage(["a", "b"])
|
||||
calls = []
|
||||
|
||||
def factory():
|
||||
calls.append(1)
|
||||
raise RuntimeError("no gpu")
|
||||
|
||||
with pytest.raises(w.SeparatorLoadError):
|
||||
w.run_manifest(storage, factory, MANIFEST, 0, 1, bucket=BUCKET)
|
||||
assert len(calls) == 1 # no per-song retry of the model load
|
||||
|
||||
|
||||
def _patch_main(monkeypatch, run):
|
||||
import backend.services.storage_service as ss
|
||||
|
||||
monkeypatch.setattr(ss, "StorageService", lambda: object())
|
||||
monkeypatch.setattr(w, "run_manifest", run)
|
||||
|
||||
|
||||
def test_main_all_failed_logs_one_error_and_exits_nonzero(monkeypatch, caplog):
|
||||
fail = {"id": "a", "ok": False, "vocals": None, "seconds": 0, "error": "oom"}
|
||||
_patch_main(monkeypatch, lambda *a, **k: [fail, dict(fail, id="b")])
|
||||
assert w.main(["--manifest", MANIFEST]) == 1
|
||||
assert len([r for r in caplog.records if r.levelname == "ERROR"]) == 1
|
||||
|
||||
|
||||
def test_main_partial_failure_exits_zero_without_error(monkeypatch, caplog):
|
||||
ok = {"id": "a", "ok": True, "vocals": "v", "seconds": 1, "error": None}
|
||||
_patch_main(monkeypatch, lambda *a, **k: [ok, dict(ok, id="b", ok=False, error="x")])
|
||||
assert w.main(["--manifest", MANIFEST]) == 0
|
||||
assert not [r for r in caplog.records if r.levelname == "ERROR"]
|
||||
|
||||
|
||||
def test_main_load_failure_exits_nonzero_with_one_error(monkeypatch, caplog):
|
||||
def boom(*a, **k):
|
||||
raise w.SeparatorLoadError("x")
|
||||
|
||||
_patch_main(monkeypatch, boom)
|
||||
assert w.main(["--manifest", MANIFEST]) == 1
|
||||
assert len([r for r in caplog.records if r.levelname == "ERROR"]) == 1
|
||||
|
||||
|
||||
def test_periodic_flush_failure_is_tolerated_final_is_strict(tmp_path, monkeypatch):
|
||||
import pytest
|
||||
|
||||
storage = FakeStorage([str(i) for i in range(11)])
|
||||
orig = w._write_results
|
||||
n = []
|
||||
|
||||
def flaky(s, m, i, r):
|
||||
n.append(len(r))
|
||||
if len(n) == 1:
|
||||
raise OSError("transient gcs")
|
||||
return orig(s, m, i, r)
|
||||
|
||||
monkeypatch.setattr(w, "_write_results", flaky)
|
||||
results = w.run_manifest(storage, lambda: FakeSeparator(str(tmp_path)), MANIFEST, 0, 1, bucket=BUCKET)
|
||||
assert len(results) == 11 and n == [10, 11]
|
||||
|
||||
monkeypatch.setattr(w, "_write_results", lambda *a: (_ for _ in ()).throw(OSError("down")))
|
||||
with pytest.raises(OSError):
|
||||
w.run_manifest(FakeStorage(["a"]), lambda: FakeSeparator(str(tmp_path)), MANIFEST, 0, 1, bucket=BUCKET)
|
||||
|
||||
|
||||
def test_wrong_bucket_song_recorded_and_manifest_fails(tmp_path):
|
||||
import pytest
|
||||
|
||||
storage = FakeStorage(["a", "b"])
|
||||
storage.blobs["voice-pool/manifests/run1.jsonl"] = (
|
||||
json.dumps({"id": "a", "audio": "gs://other-bucket/voice-pool/audio/a/original.flac"}) + "\n"
|
||||
+ json.dumps({"id": "b", "audio": f"gs://{BUCKET}/voice-pool/audio/b/original.flac"}) + "\n"
|
||||
).encode()
|
||||
results = w.run_manifest(storage, lambda: FakeSeparator(str(tmp_path)), MANIFEST, 0, 1, bucket=BUCKET)
|
||||
assert results[0]["ok"] is False and results[0]["error"] == "wrong_bucket"
|
||||
assert results[1]["ok"] is True
|
||||
|
||||
with pytest.raises(w.SystemicTaskError):
|
||||
w.run_manifest(storage, lambda: FakeSeparator(str(tmp_path)),
|
||||
"gs://other-bucket/voice-pool/manifests/run1.jsonl", 0, 1, bucket=BUCKET)
|
||||
|
||||
|
||||
def test_systemic_error_messages_are_task_independent(monkeypatch, caplog):
|
||||
fail = {"id": "a", "ok": False, "vocals": None, "seconds": 0, "error": "oom"}
|
||||
_patch_main(monkeypatch, lambda *a, **k: [fail])
|
||||
monkeypatch.setenv("CLOUD_RUN_TASK_INDEX", "3")
|
||||
w.main(["--manifest", MANIFEST])
|
||||
errs = [r for r in caplog.records if r.levelname == "ERROR"]
|
||||
assert len(errs) == 1 and "3" not in errs[0].getMessage().split("(first")[0]
|
||||
@@ -81,7 +81,8 @@
|
||||
"waveformGenerationError": "Error generating waveform data: {error}",
|
||||
"waveformNoAudio": "No audio available for waveform",
|
||||
"sessionSaveError": "Correction data is required",
|
||||
"invalidIsDuetFlag": "is_duet must be a boolean (true or false)"
|
||||
"invalidIsDuetFlag": "is_duet must be a boolean (true or false)",
|
||||
"previewMissingTimings": "The line \"{line}\" has a word with no timing. Sync that line, then try the preview again."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Audio search is not enabled for this tenant",
|
||||
@@ -177,7 +178,10 @@
|
||||
"videoReadyTitle": "Video Ready!",
|
||||
"videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download",
|
||||
"confirmDurationTitle": "Confirm job cost",
|
||||
"confirmDurationBody": "\"{title}\" by {artist} needs a cost confirmation to continue"
|
||||
"confirmDurationBody": "\"{title}\" by {artist} needs a cost confirmation to continue",
|
||||
"jobProblemTitle": "There's a problem with your video",
|
||||
"jobProblemBody": "\"{title}\" by {artist} hit a problem. Open the app to see what happened",
|
||||
"jobStalledBody": "The audio download for \"{title}\" by {artist} is stuck. We can keep trying if you open the app"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Invalid domain format",
|
||||
@@ -225,6 +229,16 @@
|
||||
"expiry": "This code expires in {minutes} minutes and can only be used once.",
|
||||
"ignoreNote": "If you didn't request this code, you can safely ignore this email."
|
||||
},
|
||||
"loginCode": {
|
||||
"subject": "Your {brand_name} sign-in code: {code}",
|
||||
"greeting": "Hi there,",
|
||||
"intro": "Enter this code on the sign-in page to continue:",
|
||||
"expiry": "This code expires in {minutes} minutes and can only be used once.",
|
||||
"orLink": "Or skip the code and sign in with one click:",
|
||||
"signInButton": "Sign In",
|
||||
"linkExpiry": "The sign-in link works for 24 hours and can only be used once.",
|
||||
"ignoreNote": "If you didn't request this email, you can safely ignore it."
|
||||
},
|
||||
"welcome": {
|
||||
"subject": "Welcome to Nomad Karaoke!",
|
||||
"welcomeGreeting": "Welcome to Nomad Karaoke!",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "لا يوجد صوت متاح للشكل الموجي",
|
||||
"sessionSaveError": "بيانات التصحيح مطلوبة",
|
||||
"invalidIsDuetFlag": "يجب أن يكون is_duet قيمة منطقية (true أو false)",
|
||||
"previewMissingTimings": "يحتوي السطر \"{line}\" على كلمة بلا توقيت. قم بمزامنة هذا السطر، ثم حاول المعاينة مرة أخرى."
|
||||
"previewMissingTimings": "يتضمن السطر \"{line}\" كلمة بدون توقيت. اضبط توقيت هذا السطر، ثم جرب المعاينة مرة أخرى."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "البحث الصوتي غير مفعل لهذا المستأجر",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "الفيديو جاهز!",
|
||||
"videoReadyBody": "فيديو الكاريوكي الخاص بك لأغنية \"{title}\" للفنان {artist} جاهز للتنزيل",
|
||||
"confirmDurationTitle": "تأكيد تكلفة المهمة",
|
||||
"confirmDurationBody": "تحتاج \"{title}\" للفنان {artist} إلى تأكيد التكلفة للمتابعة"
|
||||
"confirmDurationBody": "تحتاج \"{title}\" للفنان {artist} إلى تأكيد التكلفة للمتابعة",
|
||||
"jobProblemTitle": "توجد مشكلة في الفيديو الخاص بك",
|
||||
"jobProblemBody": "واجهت أغنية \"{title}\" لـ {artist} مشكلة. افتح التطبيق لمعرفة ما حدث",
|
||||
"jobStalledBody": "تنزيل الملف الصوتي لأغنية \"{title}\" لـ {artist} متوقف. يمكننا متابعة المحاولة إذا فتحت التطبيق"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "تنسيق النطاق غير صالح",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "رمز Nomad Karaoke الخاص بك: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "تنتهي صلاحية هذا الرمز خلال {minutes} دقائق ولا يمكن استخدامه إلا مرة واحدة.",
|
||||
"greeting": "مرحبًا،",
|
||||
"expiry": "تنتهي صلاحية هذا الرمز خلال {minutes} دقيقة ويمكن استخدامه مرة واحدة فقط.",
|
||||
"greeting": "مرحباً،",
|
||||
"ignoreNote": "إذا لم تطلب هذا البريد الإلكتروني، يمكنك تجاهله بأمان.",
|
||||
"intro": "أدخل هذا الرمز في صفحة تسجيل الدخول للمتابعة:",
|
||||
"linkExpiry": "يعمل رابط تسجيل الدخول لمدة 24 ساعة ولا يمكن استخدامه إلا مرة واحدة.",
|
||||
"linkExpiry": "يعمل رابط تسجيل الدخول لمدة 24 ساعة ويمكن استخدامه مرة واحدة فقط.",
|
||||
"orLink": "أو تخطَّ الرمز وسجّل الدخول بنقرة واحدة:",
|
||||
"signInButton": "تسجيل الدخول",
|
||||
"subject": "رمز تسجيل الدخول إلى {brand_name}: {code}"
|
||||
"subject": "رمز تسجيل الدخول الخاص بك في {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "تفضّل ألا تراجع الكلمات بنفسك؟ اختر Made For You وسأصنع الفيديو كاملاً من أجلك، ليكون جاهزاً خلال 24 ساعة:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "No hi ha àudio disponible per a la forma d'ona",
|
||||
"sessionSaveError": "Es requereixen dades de correcció",
|
||||
"invalidIsDuetFlag": "is_duet ha de ser un booleà (cert o fals)",
|
||||
"previewMissingTimings": "La línia \"{line}\" té una paraula sense temporització. Sincronitza aquesta línia i torna a provar la previsualització."
|
||||
"previewMissingTimings": "La línia \"{line}\" té una paraula sense temporització. Sincronitza aquesta línia i torna a provar la vista prèvia."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "La cerca d'àudio no està activada per a aquest tenant",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Vídeo llest!",
|
||||
"videoReadyBody": "El teu vídeo de karaoke per a \"{title}\" de {artist} està llest per descarregar",
|
||||
"confirmDurationTitle": "Confirma el cost de la tasca",
|
||||
"confirmDurationBody": "\"{title}\" de {artist} necessita una confirmació de cost per continuar"
|
||||
"confirmDurationBody": "\"{title}\" de {artist} necessita una confirmació de cost per continuar",
|
||||
"jobProblemTitle": "Hi ha un problema amb el teu vídeo",
|
||||
"jobProblemBody": "Hi ha hagut un problema amb \"{title}\" de {artist}. Obre l'aplicació per veure què ha passat",
|
||||
"jobStalledBody": "La descàrrega de l'àudio de \"{title}\" de {artist} s'ha encallat. Podem continuar intentant-ho si obres l'aplicació"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Format de domini no vàlid",
|
||||
@@ -406,13 +409,13 @@
|
||||
"subject": "El teu codi de Nomad Karaoke: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Aquest codi caduca d'aquí a {minutes} minuts i només es pot fer servir una vegada.",
|
||||
"expiry": "Aquest codi caduca en {minutes} minuts i només es pot utilitzar una vegada.",
|
||||
"greeting": "Hola,",
|
||||
"ignoreNote": "Si no has sol·licitat aquest correu, el pots ignorar sense problemes.",
|
||||
"ignoreNote": "Si no has demanat aquest correu, pots ignorar-lo tranquil·lament.",
|
||||
"intro": "Introdueix aquest codi a la pàgina d'inici de sessió per continuar:",
|
||||
"linkExpiry": "L'enllaç d'inici de sessió funciona durant 24 hores i només es pot fer servir una vegada.",
|
||||
"orLink": "O salta't el codi i inicia la sessió amb un clic:",
|
||||
"signInButton": "Inicia la sessió",
|
||||
"linkExpiry": "L'enllaç d'inici de sessió és vàlid durant 24 hores i només es pot fer servir una vegada.",
|
||||
"orLink": "O salta't el codi i inicia sessió amb un sol clic:",
|
||||
"signInButton": "Inicia sessió",
|
||||
"subject": "El teu codi d'inici de sessió de {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Pro křivku není k dispozici žádný zvuk",
|
||||
"sessionSaveError": "Jsou vyžadována data oprav",
|
||||
"invalidIsDuetFlag": "is_duet musí být typu boolean (true nebo false)",
|
||||
"previewMissingTimings": "Řádek „{line}“ obsahuje slovo bez časování. Synchronizuj tento řádek a zkus náhled znovu."
|
||||
"previewMissingTimings": "Řádek „{line}“ obsahuje slovo bez časování. Synchronizuj tento řádek a pak zkus náhled znovu."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Vyhledávání zvuku není pro tohoto tenanta povoleno",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video je připraveno!",
|
||||
"videoReadyBody": "Tvoje karaoke video pro \"{title}\" od {artist} je připraveno ke stažení",
|
||||
"confirmDurationTitle": "Potvrď cenu úlohy",
|
||||
"confirmDurationBody": "\"{title}\" od {artist} vyžaduje potvrzení ceny pro pokračování"
|
||||
"confirmDurationBody": "\"{title}\" od {artist} vyžaduje potvrzení ceny pro pokračování",
|
||||
"jobProblemTitle": "U tvého videa se vyskytl problém",
|
||||
"jobProblemBody": "U skladby „{title}“ od {artist} došlo k problému. Otevři aplikaci a zjisti, co se stalo",
|
||||
"jobStalledBody": "Stahování zvuku pro „{title}“ od {artist} se zaseklo. Když otevřeš aplikaci, můžeme to zkusit znovu"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Neplatný formát domény",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "Tvůj kód pro Nomad Karaoke: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Platnost tohoto kódu vyprší za {minutes} minut a lze jej použít pouze jednou.",
|
||||
"greeting": "Dobrý den,",
|
||||
"ignoreNote": "Pokud jste o tento e-mail nežádali, můžete jej klidně ignorovat.",
|
||||
"intro": "Pro pokračování zadejte tento kód na přihlašovací stránce:",
|
||||
"linkExpiry": "Přihlašovací odkaz platí 24 hodin a lze jej použít pouze jednou.",
|
||||
"orLink": "Nebo kód přeskočte a přihlaste se jedním kliknutím:",
|
||||
"expiry": "Tento kód vyprší za {minutes} minut a lze jej použít pouze jednou.",
|
||||
"greeting": "Ahoj,",
|
||||
"ignoreNote": "Pokud jsi o tento e-mail nežádal/a, můžeš ho s klidem ignorovat.",
|
||||
"intro": "Pro pokračování zadej tento kód na přihlašovací stránce:",
|
||||
"linkExpiry": "Přihlašovací odkaz je platný 24 hodin a lze jej použít pouze jednou.",
|
||||
"orLink": "Nebo kód přeskoč a přihlas se jedním kliknutím:",
|
||||
"signInButton": "Přihlásit se",
|
||||
"subject": "Váš přihlašovací kód pro {brand_name}: {code}"
|
||||
"subject": "Tvůj přihlašovací kód pro {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Nechce se ti kontrolovat text osobně? Zvol možnost Made For You a já pro tebe vytvořím celé video s doručením do 24 hodin:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Ingen lyd tilgængelig til bølgeform",
|
||||
"sessionSaveError": "Rettelsesdata er påkrævet",
|
||||
"invalidIsDuetFlag": "is_duet skal være en boolsk værdi (sand eller falsk)",
|
||||
"previewMissingTimings": "Linjen \"{line}\" har et ord uden timing. Synkroniser den linje, og prøv derefter forhåndsvisningen igen."
|
||||
"previewMissingTimings": "Linjen \"{line}\" indeholder et ord uden timing. Synkronisér linjen, og prøv forhåndsvisningen igen."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Lydsøgning er ikke aktiveret for denne lejer",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Videoen er klar!",
|
||||
"videoReadyBody": "Din karaokevideo til \"{title}\" af {artist} er klar til download",
|
||||
"confirmDurationTitle": "Bekræft opgavepris",
|
||||
"confirmDurationBody": "\"{title}\" af {artist} kræver en prisbekræftelse for at fortsætte"
|
||||
"confirmDurationBody": "\"{title}\" af {artist} kræver en prisbekræftelse for at fortsætte",
|
||||
"jobProblemTitle": "Der er et problem med din video",
|
||||
"jobProblemBody": "Der opstod et problem med \"{title}\" af {artist}. Åbn appen for at se, hvad der skete",
|
||||
"jobStalledBody": "Downloadingen af lyd til \"{title}\" af {artist} er gået i stå. Vi kan prøve igen, hvis du åbner appen"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Ugyldigt domæneformat",
|
||||
@@ -408,12 +411,12 @@
|
||||
"loginCode": {
|
||||
"expiry": "Denne kode udløber om {minutes} minutter og kan kun bruges én gang.",
|
||||
"greeting": "Hej,",
|
||||
"ignoreNote": "Hvis du ikke har anmodet om denne e-mail, kan du roligt ignorere den.",
|
||||
"ignoreNote": "Hvis du ikke har anmodet om denne e-mail, kan du bare ignorere den.",
|
||||
"intro": "Indtast denne kode på login-siden for at fortsætte:",
|
||||
"linkExpiry": "Login-linket virker i 24 timer og kan kun bruges én gang.",
|
||||
"orLink": "Eller spring koden over og log ind med ét klik:",
|
||||
"linkExpiry": "Login-linket er gyldigt i 24 timer og kan kun bruges én gang.",
|
||||
"orLink": "Eller spring koden over og log ind med et enkelt klik:",
|
||||
"signInButton": "Log ind",
|
||||
"subject": "Din login-kode til {brand_name}: {code}"
|
||||
"subject": "Din {brand_name}-loginkode: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Vil du helst slippe for selv at gennemgå teksten? Vælg Made For You, så laver jeg hele videoen for dig, leveret inden for 24 timer:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Kein Audio für Wellenform verfügbar",
|
||||
"sessionSaveError": "Korrekturdaten sind erforderlich",
|
||||
"invalidIsDuetFlag": "is_duet muss ein Boolean sein (true oder false)",
|
||||
"previewMissingTimings": "Die Zeile \"{line}\" enthält ein Wort ohne Timing. Synchronisiere diese Zeile und versuche die Vorschau dann erneut."
|
||||
"previewMissingTimings": "Die Zeile „{line}“ enthält ein Wort ohne Timing. Synchronisiere diese Zeile und versuche die Vorschau dann erneut."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Die Audiosuche ist für diesen Mandanten nicht aktiviert",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video fertig!",
|
||||
"videoReadyBody": "Dein Karaoke-Video für \"{title}\" von {artist} ist bereit zum Herunterladen",
|
||||
"confirmDurationTitle": "Auftragskosten bestätigen",
|
||||
"confirmDurationBody": "\"{title}\" von {artist} benötigt eine Kostenbestätigung, um fortzufahren"
|
||||
"confirmDurationBody": "\"{title}\" von {artist} benötigt eine Kostenbestätigung, um fortzufahren",
|
||||
"jobProblemTitle": "Es gibt ein Problem mit deinem Video",
|
||||
"jobProblemBody": "Bei „{title}“ von {artist} ist ein Problem aufgetreten. Öffne die App, um zu sehen, was passiert ist",
|
||||
"jobStalledBody": "Der Audio-Download für „{title}“ von {artist} hängt fest. Wir können es weiter versuchen, wenn du die App öffnest"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Ungültiges Domain-Format",
|
||||
@@ -410,10 +413,10 @@
|
||||
"greeting": "Hallo,",
|
||||
"ignoreNote": "Wenn du diese E-Mail nicht angefordert hast, kannst du sie einfach ignorieren.",
|
||||
"intro": "Gib diesen Code auf der Anmeldeseite ein, um fortzufahren:",
|
||||
"linkExpiry": "Der Anmeldelink ist 24 Stunden gültig und kann nur einmal verwendet werden.",
|
||||
"linkExpiry": "Der Anmeldelink ist 24 Stunden lang gültig und kann nur einmal verwendet werden.",
|
||||
"orLink": "Oder überspringe den Code und melde dich mit einem Klick an:",
|
||||
"signInButton": "Anmelden",
|
||||
"subject": "Dein {brand_name} Anmeldecode: {code}"
|
||||
"subject": "Dein {brand_name}-Anmeldecode: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Möchtest du die Textüberprüfung lieber nicht selbst machen? Wähle „Made For You“ und ich erstelle das komplette Video für dich – geliefert innerhalb von 24 Stunden:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Δεν υπάρχει διαθέσιμος ήχος για την κυματομορφή",
|
||||
"sessionSaveError": "Απαιτούνται δεδομένα διόρθωσης",
|
||||
"invalidIsDuetFlag": "Το is_duet πρέπει να είναι boolean (true ή false)",
|
||||
"previewMissingTimings": "Η γραμμή «{line}» περιέχει μια λέξη χωρίς συγχρονισμό. Συγχρόνισε αυτή τη γραμμή και δοκίμασε ξανά την προεπισκόπηση."
|
||||
"previewMissingTimings": "Ο στίχος \"{line}\" έχει μια λέξη χωρίς χρονισμό. Συγχρόνισε αυτόν τον στίχο και μετά δοκίμασε ξανά την προεπισκόπηση."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Η αναζήτηση ήχου δεν είναι ενεργοποιημένη για αυτόν τον μισθωτή",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Το Βίντεο Είναι Έτοιμο!",
|
||||
"videoReadyBody": "Το καραόκε βίντεό σου για το \"{title}\" από {artist} είναι έτοιμο για λήψη",
|
||||
"confirmDurationTitle": "Επιβεβαίωσε το κόστος εργασίας",
|
||||
"confirmDurationBody": "Το \"{title}\" από {artist} χρειάζεται επιβεβαίωση κόστους για να συνεχίσει"
|
||||
"confirmDurationBody": "Το \"{title}\" από {artist} χρειάζεται επιβεβαίωση κόστους για να συνεχίσει",
|
||||
"jobProblemTitle": "Υπάρχει πρόβλημα με το βίντεό σου",
|
||||
"jobProblemBody": "Παρουσιάστηκε πρόβλημα με το \"{title}\" από {artist}. Άνοιξε την εφαρμογή για να δεις τι συνέβη",
|
||||
"jobStalledBody": "Η λήψη ήχου για το \"{title}\" από {artist} έχει κολλήσει. Μπορούμε να συνεχίσουμε την προσπάθεια αν ανοίξεις την εφαρμογή"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Μη έγκυρη μορφή τομέα",
|
||||
@@ -407,13 +410,13 @@
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Αυτός ο κωδικός λήγει σε {minutes} λεπτά και μπορεί να χρησιμοποιηθεί μόνο μία φορά.",
|
||||
"greeting": "Γεια σας,",
|
||||
"ignoreNote": "Αν δεν ζητήσατε αυτό το email, μπορείτε να το αγνοήσετε με ασφάλεια.",
|
||||
"intro": "Εισαγάγετε αυτόν τον κωδικό στη σελίδα σύνδεσης για να συνεχίσετε:",
|
||||
"greeting": "Γεια σου,",
|
||||
"ignoreNote": "Αν δεν ζήτησες αυτό το email, μπορείς απλά να το αγνοήσεις.",
|
||||
"intro": "Καταχώρισε αυτόν τον κωδικό στη σελίδα σύνδεσης για να συνεχίσεις:",
|
||||
"linkExpiry": "Ο σύνδεσμος σύνδεσης ισχύει για 24 ώρες και μπορεί να χρησιμοποιηθεί μόνο μία φορά.",
|
||||
"orLink": "Ή παραλείψτε τον κωδικό και συνδεθείτε με ένα κλικ:",
|
||||
"orLink": "Ή παράκαμψε τον κωδικό και συνδέσου με ένα κλικ:",
|
||||
"signInButton": "Σύνδεση",
|
||||
"subject": "Ο κωδικός σύνδεσής σας στο {brand_name}: {code}"
|
||||
"subject": "Ο κωδικός σύνδεσής σου στο {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Προτιμάς να μην κάνεις εσύ τον έλεγχο των στίχων; Επίλεξε το Made For You και θα σου ετοιμάσω ολόκληρο το βίντεο, με παράδοση εντός 24 ωρών:",
|
||||
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video Ready!",
|
||||
"videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download",
|
||||
"confirmDurationTitle": "Confirm job cost",
|
||||
"confirmDurationBody": "\"{title}\" by {artist} needs a cost confirmation to continue"
|
||||
"confirmDurationBody": "\"{title}\" by {artist} needs a cost confirmation to continue",
|
||||
"jobProblemTitle": "There's a problem with your video",
|
||||
"jobProblemBody": "\"{title}\" by {artist} hit a problem. Open the app to see what happened",
|
||||
"jobStalledBody": "The audio download for \"{title}\" by {artist} is stuck. We can keep trying if you open the app"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Invalid domain format",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "No hay audio disponible para la forma de onda",
|
||||
"sessionSaveError": "Se requieren datos de corrección",
|
||||
"invalidIsDuetFlag": "is_duet debe ser un booleano (true o false)",
|
||||
"previewMissingTimings": "La línea \"{line}\" tiene una palabra sin sincronizar. Sincroniza esa línea y vuelve a intentar la vista previa."
|
||||
"previewMissingTimings": "La línea \"{line}\" tiene una palabra sin sincronización. Sincroniza esa línea y luego vuelve a probar la vista previa."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "La búsqueda de audio no está habilitada para este inquilino",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "¡Video listo!",
|
||||
"videoReadyBody": "Tu video de karaoke para \"{title}\" de {artist} está listo para descargar",
|
||||
"confirmDurationTitle": "Confirmar costo del trabajo",
|
||||
"confirmDurationBody": "\"{title}\" de {artist} necesita una confirmación de costo para continuar"
|
||||
"confirmDurationBody": "\"{title}\" de {artist} necesita una confirmación de costo para continuar",
|
||||
"jobProblemTitle": "Hay un problema con tu video",
|
||||
"jobProblemBody": "\"{title}\" de {artist} tuvo un problema. Abre la aplicación para ver qué ocurrió",
|
||||
"jobStalledBody": "La descarga de audio de \"{title}\" de {artist} está atascada. Podemos seguir intentándolo si abres la aplicación"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Formato de dominio inválido",
|
||||
@@ -408,10 +411,10 @@
|
||||
"loginCode": {
|
||||
"expiry": "Este código caduca en {minutes} minutos y solo se puede usar una vez.",
|
||||
"greeting": "Hola,",
|
||||
"ignoreNote": "Si no solicitaste este correo electrónico, puedes ignorarlo de forma segura.",
|
||||
"ignoreNote": "Si no solicitaste este correo, puedes ignorarlo sin problema.",
|
||||
"intro": "Introduce este código en la página de inicio de sesión para continuar:",
|
||||
"linkExpiry": "El enlace de inicio de sesión funciona durante 24 horas y solo se puede usar una vez.",
|
||||
"orLink": "O sáltate el código e inicia sesión con un clic:",
|
||||
"orLink": "O sáltate el código e inicia sesión con un solo clic:",
|
||||
"signInButton": "Iniciar sesión",
|
||||
"subject": "Tu código de inicio de sesión de {brand_name}: {code}"
|
||||
},
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Ääntä ei ole saatavilla aaltomuotoa varten",
|
||||
"sessionSaveError": "Korjaustiedot vaaditaan",
|
||||
"invalidIsDuetFlag": "is_duet täytyy olla totuusarvo (true tai false)",
|
||||
"previewMissingTimings": "Rivillä \"{line}\" on sana, jolla ei ole ajoitusta. Synkronoi kyseinen rivi ja yritä esikatselua uudelleen."
|
||||
"previewMissingTimings": "Rivillä \"{line}\" on sana, jolta puuttuu ajoitus. Synkronoi kyseinen rivi ja kokeile esikatselua uudelleen."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Äänihaku ei ole käytössä tälle asiakkaalle",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video on valmis!",
|
||||
"videoReadyBody": "Karaokevideosi kappaleelle \"{title}\" esittäjältä {artist} on valmis ladattavaksi",
|
||||
"confirmDurationTitle": "Vahvista työn hinta",
|
||||
"confirmDurationBody": "\"{title}\" esittäjältä {artist} vaatii hinnan vahvistuksen jatkamista varten"
|
||||
"confirmDurationBody": "\"{title}\" esittäjältä {artist} vaatii hinnan vahvistuksen jatkamista varten",
|
||||
"jobProblemTitle": "Videossasi on ongelma",
|
||||
"jobProblemBody": "Kappaleen \"{title}\" ({artist}) kohdalla ilmeni ongelma. Avaa sovellus nähdäksesi, mitä tapahtui",
|
||||
"jobStalledBody": "Kappaleen \"{title}\" ({artist}) äänitiedoston lataus on jumissa. Voimme jatkaa yrittämistä, jos avaat sovelluksen"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Virheellinen verkkotunnuksen muoto",
|
||||
@@ -406,12 +409,12 @@
|
||||
"subject": "Nomad Karaoke -koodisi: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Tämä koodi vanhenee {minutes} minuutissa, ja sitä voi käyttää vain kerran.",
|
||||
"greeting": "Hei,",
|
||||
"expiry": "Tämä koodi vanhenee {minutes} minuutissa ja sen voi käyttää vain kerran.",
|
||||
"greeting": "Moi!",
|
||||
"ignoreNote": "Jos et pyytänyt tätä sähköpostia, voit turvallisesti jättää sen huomiotta.",
|
||||
"intro": "Jatka syöttämällä tämä koodi kirjautumissivulle:",
|
||||
"linkExpiry": "Kirjautumislinkki toimii 24 tuntia, ja sitä voi käyttää vain kerran.",
|
||||
"orLink": "Tai ohita koodi ja kirjaudu sisään yhdellä napsautuksella:",
|
||||
"linkExpiry": "Kirjautumislinkki on voimassa 24 tuntia ja sen voi käyttää vain kerran.",
|
||||
"orLink": "Tai ohita koodi ja kirjaudu sisään yhdellä klikkauksella:",
|
||||
"signInButton": "Kirjaudu sisään",
|
||||
"subject": "{brand_name}-kirjautumiskoodisi: {code}"
|
||||
},
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Aucun audio disponible pour la forme d'onde",
|
||||
"sessionSaveError": "Les données de correction sont requises",
|
||||
"invalidIsDuetFlag": "is_duet doit être un booléen (true ou false)",
|
||||
"previewMissingTimings": "La ligne « {line} » contient un mot sans synchronisation. Synchronise cette ligne, puis réessaie l'aperçu."
|
||||
"previewMissingTimings": "La ligne \"{line}\" contient un mot sans timing. Synchronise cette ligne, puis réessaie l'aperçu."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "La recherche audio n'est pas activée pour ce compte",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Vidéo prête !",
|
||||
"videoReadyBody": "Ta vidéo karaoké pour \"{title}\" de {artist} est prête à être téléchargée",
|
||||
"confirmDurationTitle": "Confirme le coût de la tâche",
|
||||
"confirmDurationBody": "\"{title}\" de {artist} nécessite une confirmation de coût pour continuer"
|
||||
"confirmDurationBody": "\"{title}\" de {artist} nécessite une confirmation de coût pour continuer",
|
||||
"jobProblemTitle": "Il y a un problème avec ta vidéo",
|
||||
"jobProblemBody": "\"{title}\" de {artist} a rencontré un problème. Ouvre l'application pour voir ce qui s'est passé",
|
||||
"jobStalledBody": "Le téléchargement audio pour \"{title}\" de {artist} est bloqué. Nous pouvons réessayer si tu ouvres l'application"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Format de domaine invalide",
|
||||
@@ -407,13 +410,13 @@
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Ce code expire dans {minutes} minutes et ne peut être utilisé qu'une seule fois.",
|
||||
"greeting": "Bonjour,",
|
||||
"ignoreNote": "Si vous n'avez pas demandé cet e-mail, vous pouvez l'ignorer en toute sécurité.",
|
||||
"intro": "Saisissez ce code sur la page de connexion pour continuer :",
|
||||
"linkExpiry": "Le lien de connexion est valable 24 heures et ne peut être utilisé qu'une seule fois.",
|
||||
"orLink": "Ou passez le code et connectez-vous en un clic :",
|
||||
"greeting": "Salut,",
|
||||
"ignoreNote": "Si tu n'as pas demandé cet email, tu peux l'ignorer en toute sécurité.",
|
||||
"intro": "Saisis ce code sur la page de connexion pour continuer :",
|
||||
"linkExpiry": "Le lien de connexion est valide pendant 24 heures et ne peut être utilisé qu'une seule fois.",
|
||||
"orLink": "Ou ignore le code et connecte-toi en un clic :",
|
||||
"signInButton": "Se connecter",
|
||||
"subject": "Votre code de connexion {brand_name} : {code}"
|
||||
"subject": "Ton code de connexion {brand_name} : {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Tu préfères ne pas vérifier les paroles toi-même ? Choisis Made For You et je m'occupe de créer toute la vidéo pour toi, livrée sous 24 heures :",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "אין אודיו זמין עבור גל הקול",
|
||||
"sessionSaveError": "נדרשים נתוני תיקון",
|
||||
"invalidIsDuetFlag": "is_duet חייב להיות ערך בוליאני (true או false)",
|
||||
"previewMissingTimings": "בשורה \"{line}\" יש מילה ללא תזמון. סנכרנו את השורה הזו ונסו שוב את התצוגה המקדימה."
|
||||
"previewMissingTimings": "בשורה \"{line}\" יש מילה ללא תזמון. יש לסנכרן את השורה הזו ואז להפעיל שוב את התצוגה המקדימה."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "חיפוש אודיו אינו מופעל עבור חשבון זה",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "הווידאו מוכן!",
|
||||
"videoReadyBody": "סרטון הקריוקי שלכם עבור \"{title}\" מאת {artist} מוכן להורדה",
|
||||
"confirmDurationTitle": "אישור עלות המשימה",
|
||||
"confirmDurationBody": "\"{title}\" של {artist} דורש אישור עלות כדי להמשיך"
|
||||
"confirmDurationBody": "\"{title}\" של {artist} דורש אישור עלות כדי להמשיך",
|
||||
"jobProblemTitle": "יש בעיה בסרטון שלך",
|
||||
"jobProblemBody": "נתקלנו בבעיה עם \"{title}\" מאת {artist}. יש לפתוח את האפליקציה כדי לראות מה קרה",
|
||||
"jobStalledBody": "הורדת השמע עבור \"{title}\" מאת {artist} נתקעה. נוכל להמשיך לנסות אם ייפתח היישום"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "פורמט דומיין לא חוקי",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "קוד ה-Nomad Karaoke שלך: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "תוקף הקוד יפוג בעוד {minutes} דקות, וניתן להשתמש בו פעם אחת בלבד.",
|
||||
"greeting": "שלום,",
|
||||
"ignoreNote": "אם לא ביקשת את המייל הזה, אפשר פשוט להתעלם ממנו.",
|
||||
"intro": "הזינו את הקוד הזה בדף הכניסה כדי להמשיך:",
|
||||
"linkExpiry": "קישור הכניסה תקף למשך 24 שעות, וניתן להשתמש בו פעם אחת בלבד.",
|
||||
"orLink": "או דלגו על הקוד והיכנסו בלחיצה אחת:",
|
||||
"signInButton": "כניסה",
|
||||
"subject": "קוד הכניסה שלך ל-{brand_name}: {code}"
|
||||
"expiry": "הקוד יפוג בעוד {minutes} דקות וניתן להשתמש בו פעם אחת בלבד.",
|
||||
"greeting": "היי,",
|
||||
"ignoreNote": "אם לא ביקשת את האימייל הזה, אתה יכול להתעלם ממנו בבטחה.",
|
||||
"intro": "יש להזין את הקוד הזה בעמוד ההתחברות כדי להמשיך:",
|
||||
"linkExpiry": "קישור ההתחברות תקף ל-24 שעות וניתן להשתמש בו פעם אחת בלבד.",
|
||||
"orLink": "או לדלג על הקוד ולהתחבר בלחיצה אחת:",
|
||||
"signInButton": "התחבר",
|
||||
"subject": "קוד ההתחברות שלך ל-{brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "מעדיפים לא לעבור על המילים בעצמכם? בחרו ב-Made For You ואני אכין את כל הסרטון עבורכם, מוכן תוך 24 שעות:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "वेवफ़ॉर्म के लिए कोई ऑडियो उपलब्ध नहीं है",
|
||||
"sessionSaveError": "करेक्शन डेटा आवश्यक है",
|
||||
"invalidIsDuetFlag": "is_duet एक boolean (true या false) होना चाहिए",
|
||||
"previewMissingTimings": "पंक्ति \"{line}\" में एक ऐसा शब्द है जिसकी टाइमिंग नहीं है। उस पंक्ति को सिंक करो, फिर प्रीव्यू दोबारा आज़माओ।"
|
||||
"previewMissingTimings": "लाइन \"{line}\" में एक ऐसा शब्द है जिसकी कोई टाइमिंग नहीं है। उस लाइन को सिंक करो, फिर प्रीव्यू दोबारा चलाकर देखो।"
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "इस टेनेंट के लिए ऑडियो सर्च सक्षम नहीं है",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "वीडियो तैयार है!",
|
||||
"videoReadyBody": "{artist} का तुम्हारा कराओके वीडियो \"{title}\" डाउनलोड के लिए तैयार है",
|
||||
"confirmDurationTitle": "जॉब की लागत की पुष्टि करो",
|
||||
"confirmDurationBody": "जारी रखने के लिए {artist} के \"{title}\" को लागत की पुष्टि की ज़रूरत है"
|
||||
"confirmDurationBody": "जारी रखने के लिए {artist} के \"{title}\" को लागत की पुष्टि की ज़रूरत है",
|
||||
"jobProblemTitle": "तुम्हारे वीडियो में एक समस्या आई है",
|
||||
"jobProblemBody": "{artist} का \"{title}\" प्रोसेस करने में समस्या आई। क्या हुआ, यह देखने के लिए ऐप खोलो",
|
||||
"jobStalledBody": "{artist} के \"{title}\" का ऑडियो डाउनलोड अटक गया है। अगर तुम ऐप खोलो, तो हम कोशिश जारी रख सकते हैं"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "अमान्य डोमेन फ़ॉर्मैट",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "तुम्हारा Nomad Karaoke कोड: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "यह कोड {minutes} मिनट में समाप्त हो जाएगा और इसे केवल एक बार उपयोग किया जा सकता है।",
|
||||
"expiry": "यह कोड {minutes} मिनट में समाप्त हो जाएगा और इसका उपयोग केवल एक बार किया जा सकता है।",
|
||||
"greeting": "नमस्ते,",
|
||||
"ignoreNote": "अगर आपने यह ईमेल नहीं मांगा था, तो आप इसे सुरक्षित रूप से अनदेखा कर सकते हैं।",
|
||||
"intro": "जारी रखने के लिए साइन-इन पेज पर यह कोड दर्ज करें:",
|
||||
"linkExpiry": "साइन-इन लिंक 24 घंटे तक काम करता है और इसे केवल एक बार उपयोग किया जा सकता है।",
|
||||
"orLink": "या कोड छोड़ें और एक क्लिक में साइन इन करें:",
|
||||
"signInButton": "साइन इन करें",
|
||||
"subject": "आपका {brand_name} साइन-इन कोड: {code}"
|
||||
"ignoreNote": "अगर तुमने इस ईमेल की रिक्वेस्ट नहीं की थी, तो तुम इसे सुरक्षित रूप से इग्नोर कर सकते हो।",
|
||||
"intro": "आगे बढ़ने के लिए साइन-इन पेज पर यह कोड दर्ज करो:",
|
||||
"linkExpiry": "साइन-इन लिंक 24 घंटों तक काम करता है और इसे केवल एक बार इस्तेमाल किया जा सकता है।",
|
||||
"orLink": "या कोड छोड़ो और बस एक क्लिक में साइन इन करो:",
|
||||
"signInButton": "साइन इन करो",
|
||||
"subject": "तुम्हारा {brand_name} साइन-इन कोड: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "क्या तुम खुद लिरिक्स रिव्यू नहीं करना चाहते? Made For You चुनो और मैं तुम्हारे लिए पूरा वीडियो बना दूंगा, जो 24 घंटे के अंदर डिलीवर हो जाएगा:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Nema dostupnog zvuka za valni oblik",
|
||||
"sessionSaveError": "Podaci o ispravcima su obavezni",
|
||||
"invalidIsDuetFlag": "is_duet mora biti boolean (true ili false)",
|
||||
"previewMissingTimings": "Redak \"{line}\" sadrži riječ bez vremenskog označavanja. Sinkroniziraj taj redak, a zatim ponovno pokušaj pregled."
|
||||
"previewMissingTimings": "U retku \"{line}\" nalazi se riječ bez vremenske oznake. Sinkroniziraj taj redak, a zatim ponovno pokreni pretpregled."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Pretraživanje zvuka nije omogućeno za ovog zakupca",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video je spreman!",
|
||||
"videoReadyBody": "Tvoj karaoke video za \"{title}\" od {artist} je spreman za preuzimanje",
|
||||
"confirmDurationTitle": "Potvrdi trošak posla",
|
||||
"confirmDurationBody": "\"{title}\" od {artist} zahtijeva potvrdu troška za nastavak"
|
||||
"confirmDurationBody": "\"{title}\" od {artist} zahtijeva potvrdu troška za nastavak",
|
||||
"jobProblemTitle": "Došlo je do problema s tvojim videom",
|
||||
"jobProblemBody": "Došlo je do problema s pjesmom \"{title}\" izvođača {artist}. Otvori aplikaciju da vidiš što se dogodilo",
|
||||
"jobStalledBody": "Preuzimanje zvuka za pjesmu \"{title}\" izvođača {artist} je zapelo. Možemo nastaviti s pokušajima ako otvoriš aplikaciju"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Nevažeći format domene",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "Tvoj Nomad Karaoke kod: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Ovaj kod istječe za {minutes} minuta i može se upotrijebiti samo jednom.",
|
||||
"expiry": "Ovaj kod istječe za {minutes} minuta i može se iskoristiti samo jednom.",
|
||||
"greeting": "Pozdrav,",
|
||||
"ignoreNote": "Ako niste zatražili ovu e-poruku, možete je slobodno zanemariti.",
|
||||
"intro": "Unesite ovaj kod na stranici za prijavu da biste nastavili:",
|
||||
"linkExpiry": "Poveznica za prijavu vrijedi 24 sata i može se upotrijebiti samo jednom.",
|
||||
"orLink": "Ili preskočite kod i prijavite se jednim klikom:",
|
||||
"signInButton": "Prijava",
|
||||
"subject": "Vaš kod za prijavu u {brand_name}: {code}"
|
||||
"ignoreNote": "Ako nisi zatražio ovaj e-mail, možeš ga slobodno zanemariti.",
|
||||
"intro": "Unesi ovaj kôd na stranici za prijavu za nastavak:",
|
||||
"linkExpiry": "Poveznica za prijavu vrijedi 24 sata i može se iskoristiti samo jednom.",
|
||||
"orLink": "Ili preskoči kôd i prijavi se jednim klikom:",
|
||||
"signInButton": "Prijavi se",
|
||||
"subject": "Tvoj {brand_name} kôd za prijavu: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Ne želiš samostalno pregledavati tekst? Odaberi Made For You i napravit ću cijeli video za tebe, uz isporuku unutar 24 sata:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Nincs elérhető hang a hullámformához",
|
||||
"sessionSaveError": "Javítási adatok szükségesek",
|
||||
"invalidIsDuetFlag": "Az is_duet értékének logikai (boolean) típusúnak kell lennie (true vagy false)",
|
||||
"previewMissingTimings": "A(z) „{line}” sorban van egy időzítés nélküli szó. Szinkronizáld azt a sort, majd próbáld újra az előnézetet."
|
||||
"previewMissingTimings": "A(z) \"{line}\" sorban van egy időzítés nélküli szó. Szinkronizáld a sort, majd próbáld meg újra az előnézetet."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "A hangkeresés nincs engedélyezve ehhez a bérlőhöz",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "A videó kész!",
|
||||
"videoReadyBody": "A(z) \"{title}\" ({artist}) karaoke videód készen áll a letöltésre",
|
||||
"confirmDurationTitle": "Feladat költségének jóváhagyása",
|
||||
"confirmDurationBody": "{artist} \"{title}\" című számának folytatásához jóvá kell hagynod a költségeket."
|
||||
"confirmDurationBody": "{artist} \"{title}\" című számának folytatásához jóvá kell hagynod a költségeket.",
|
||||
"jobProblemTitle": "Probléma történt a videóddal",
|
||||
"jobProblemBody": "Probléma történt a(z) \"{title}\" számmal ({artist}). Nyisd meg az alkalmazást, és nézd meg, mi történt",
|
||||
"jobStalledBody": "A(z) \"{title}\" ({artist}) hangsávjának letöltése elakadt. Ha megnyitod az alkalmazást, újra megpróbáljuk"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Érvénytelen domain formátum",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "A Nomad Karaoke kódod: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Ez a kód {minutes} perc múlva lejár, és csak egyszer használható.",
|
||||
"expiry": "Ez a kód {minutes} perc múlva lejár, és csak egyszer használható fel.",
|
||||
"greeting": "Szia,",
|
||||
"ignoreNote": "Ha nem te kérted ezt az e-mailt, nyugodtan figyelmen kívül hagyhatod.",
|
||||
"intro": "A folytatáshoz írd be ezt a kódot a bejelentkezési oldalon:",
|
||||
"linkExpiry": "A bejelentkezési link 24 óráig érvényes, és csak egyszer használható.",
|
||||
"orLink": "Vagy hagyd ki a kódot, és jelentkezz be egy kattintással:",
|
||||
"ignoreNote": "Ha nem te kérted ezt az e-mailt, nyugodtan hagyd figyelmen kívül.",
|
||||
"intro": "A folytatáshoz add meg ezt a kódot a bejelentkezési oldalon:",
|
||||
"linkExpiry": "A bejelentkezési link 24 órán át érvényes, és csak egyszer használható fel.",
|
||||
"orLink": "Vagy hagyd ki a kódot, és jelentkezz be egyetlen kattintással:",
|
||||
"signInButton": "Bejelentkezés",
|
||||
"subject": "{brand_name} bejelentkezési kódod: {code}"
|
||||
"subject": "A(z) {brand_name} bejelentkezési kódod: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Inkább nem bajlódnál a dalszöveg ellenőrzésével? Válaszd a Made For You lehetőséget, és az egész videót elkészítem neked 24 órán belül:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Tidak ada audio yang tersedia untuk bentuk gelombang",
|
||||
"sessionSaveError": "Data koreksi diperlukan",
|
||||
"invalidIsDuetFlag": "is_duet harus berupa boolean (true atau false)",
|
||||
"previewMissingTimings": "Baris \"{line}\" memiliki kata tanpa waktu. Sinkronkan baris tersebut, lalu coba pratinjau lagi."
|
||||
"previewMissingTimings": "Baris \"{line}\" memiliki kata yang belum diatur waktunya. Sinkronkan baris tersebut, lalu coba pratinjau lagi."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Pencarian audio tidak diaktifkan untuk tenant ini",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video Siap!",
|
||||
"videoReadyBody": "Video karaoke Anda untuk \"{title}\" oleh {artist} siap diunduh",
|
||||
"confirmDurationTitle": "Konfirmasi biaya pekerjaan",
|
||||
"confirmDurationBody": "\"{title}\" oleh {artist} memerlukan konfirmasi biaya untuk melanjutkan"
|
||||
"confirmDurationBody": "\"{title}\" oleh {artist} memerlukan konfirmasi biaya untuk melanjutkan",
|
||||
"jobProblemTitle": "Ada masalah dengan video Anda",
|
||||
"jobProblemBody": "\"{title}\" oleh {artist} mengalami masalah. Buka aplikasi untuk melihat apa yang terjadi",
|
||||
"jobStalledBody": "Pengunduhan audio untuk \"{title}\" oleh {artist} terhenti. Kami bisa terus mencoba jika Anda membuka aplikasi"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Format domain tidak valid",
|
||||
@@ -406,12 +409,12 @@
|
||||
"subject": "Kode Nomad Karaoke Anda: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Kode ini kedaluwarsa dalam {minutes} menit dan hanya dapat digunakan satu kali.",
|
||||
"expiry": "Kode ini akan kedaluwarsa dalam {minutes} menit dan hanya dapat digunakan satu kali.",
|
||||
"greeting": "Halo,",
|
||||
"ignoreNote": "Jika Anda tidak meminta email ini, Anda dapat mengabaikannya dengan aman.",
|
||||
"ignoreNote": "Jika Anda tidak meminta email ini, Anda dapat mengabaikannya.",
|
||||
"intro": "Masukkan kode ini di halaman masuk untuk melanjutkan:",
|
||||
"linkExpiry": "Tautan masuk berlaku selama 24 jam dan hanya dapat digunakan satu kali.",
|
||||
"orLink": "Atau lewati kode dan masuk dengan satu klik:",
|
||||
"orLink": "Atau lewati kode dan masuk cukup dengan sekali klik:",
|
||||
"signInButton": "Masuk",
|
||||
"subject": "Kode masuk {brand_name} Anda: {code}"
|
||||
},
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Nessun audio disponibile per la forma d'onda",
|
||||
"sessionSaveError": "I dati di correzione sono richiesti",
|
||||
"invalidIsDuetFlag": "is_duet deve essere un booleano (true o false)",
|
||||
"previewMissingTimings": "La riga \"{line}\" contiene una parola senza tempo. Sincronizza quella riga, poi riprova l'anteprima."
|
||||
"previewMissingTimings": "Il verso \"{line}\" contiene una parola non sincronizzata. Sincronizza questo verso e riprova l'anteprima."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "La ricerca audio non è abilitata per questo tenant",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video pronto!",
|
||||
"videoReadyBody": "Il tuo video karaoke per \"{title}\" di {artist} è pronto per il download",
|
||||
"confirmDurationTitle": "Conferma il costo del lavoro",
|
||||
"confirmDurationBody": "\"{title}\" di {artist} richiede una conferma del costo per continuare"
|
||||
"confirmDurationBody": "\"{title}\" di {artist} richiede una conferma del costo per continuare",
|
||||
"jobProblemTitle": "C'è un problema con il tuo video",
|
||||
"jobProblemBody": "Si è verificato un problema con \"{title}\" di {artist}. Apri l'app per vedere cosa è successo",
|
||||
"jobStalledBody": "Il download dell'audio di \"{title}\" di {artist} è bloccato. Apri l'app per permetterci di riprovare"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Formato del dominio non valido",
|
||||
@@ -406,11 +409,11 @@
|
||||
"subject": "Il tuo codice Nomad Karaoke: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Questo codice scade tra {minutes} minuti e può essere usato una sola volta.",
|
||||
"expiry": "Questo codice scade in {minutes} minuti e può essere utilizzato una sola volta.",
|
||||
"greeting": "Ciao,",
|
||||
"ignoreNote": "Se non hai richiesto questa email, puoi ignorarla tranquillamente.",
|
||||
"ignoreNote": "Se non hai richiesto questa email, puoi tranquillamente ignorarla.",
|
||||
"intro": "Inserisci questo codice nella pagina di accesso per continuare:",
|
||||
"linkExpiry": "Il link di accesso è valido per 24 ore e può essere usato una sola volta.",
|
||||
"linkExpiry": "Il link di accesso è valido per 24 ore e può essere utilizzato una sola volta.",
|
||||
"orLink": "Oppure salta il codice e accedi con un clic:",
|
||||
"signInButton": "Accedi",
|
||||
"subject": "Il tuo codice di accesso a {brand_name}: {code}"
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "波形用のオーディオがありません",
|
||||
"sessionSaveError": "修正データが必要です",
|
||||
"invalidIsDuetFlag": "is_duet はブール値 (true または false) である必要があります",
|
||||
"previewMissingTimings": "「{line}」の行にタイミングが設定されていない単語があります。その行を同期してから、もう一度プレビューしてください。"
|
||||
"previewMissingTimings": "「{line}」の行にタイミングが設定されていない単語があります。その行のタイミングを同期してから、もう一度プレビューをお試しください。"
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "このテナントではオーディオ検索が有効になっていません",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "動画の準備ができました!",
|
||||
"videoReadyBody": "{artist} の「{title}」のカラオケ動画がダウンロード可能になりました",
|
||||
"confirmDurationTitle": "料金の確認",
|
||||
"confirmDurationBody": "{artist}の「{title}」の処理を続けるには、料金の確認が必要です"
|
||||
"confirmDurationBody": "{artist}の「{title}」の処理を続けるには、料金の確認が必要です",
|
||||
"jobProblemTitle": "動画の処理中に問題が発生しました",
|
||||
"jobProblemBody": "{artist}の「{title}」で問題が発生しました。アプリを開いて状況をご確認ください",
|
||||
"jobStalledBody": "{artist}の「{title}」の音声ダウンロードが途中で止まっています。アプリを開くと再試行できます"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "無効なドメイン形式です",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "Nomad Karaokeのコード: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "このコードの有効期限は {minutes} 分で、1 回のみ使用できます。",
|
||||
"greeting": "こんにちは。",
|
||||
"ignoreNote": "このメールに心当たりがない場合は、無視していただいて問題ありません。",
|
||||
"intro": "続行するには、サインインページでこのコードを入力してください:",
|
||||
"linkExpiry": "サインインリンクの有効期間は 24 時間で、1 回のみ使用できます。",
|
||||
"orLink": "または、コードを使わずにワンクリックでサインイン:",
|
||||
"expiry": "このコードの有効期限は{minutes}分で、1回のみ使用可能です。",
|
||||
"greeting": "こんにちは、",
|
||||
"ignoreNote": "このメールに心当たりがない場合は、そのまま無視していただいて構いません。",
|
||||
"intro": "サインインページでこのコードを入力して続行してください:",
|
||||
"linkExpiry": "サインインリンクの有効期限は24時間で、1回のみ使用できます。",
|
||||
"orLink": "または、コードを入力せずにワンクリックでサインイン:",
|
||||
"signInButton": "サインイン",
|
||||
"subject": "{brand_name} のサインインコード: {code}"
|
||||
"subject": "【{brand_name}】サインインコード:{code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "ご自身での歌詞チェックをお手軽に済ませたいですか?「Made For You」をお選びいただければ、動画をまるごと作成して24時間以内にお届けします:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "파형에 사용할 오디오가 없습니다",
|
||||
"sessionSaveError": "수정 데이터가 필요합니다",
|
||||
"invalidIsDuetFlag": "is_duet은 불리언(true 또는 false)이어야 합니다.",
|
||||
"previewMissingTimings": "\"{line}\" 줄에 타이밍이 없는 단어가 있습니다. 해당 줄을 동기화한 후 미리보기를 다시 시도해 주세요."
|
||||
"previewMissingTimings": "\"{line}\" 소절에 타이밍이 지정되지 않은 단어가 있습니다. 해당 소절의 싱크를 맞춘 후 다시 미리보기를 시도해 주세요."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "이 테넌트에서는 오디오 검색이 활성화되어 있지 않습니다",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "비디오 준비 완료!",
|
||||
"videoReadyBody": "{artist}의 \"{title}\" 노래방 비디오를 다운로드할 준비가 되었습니다",
|
||||
"confirmDurationTitle": "작업 비용 확인",
|
||||
"confirmDurationBody": "{artist}의 \"{title}\" 작업을 계속 진행하려면 비용 확인이 필요합니다"
|
||||
"confirmDurationBody": "{artist}의 \"{title}\" 작업을 계속 진행하려면 비용 확인이 필요합니다",
|
||||
"jobProblemTitle": "동영상에 문제가 발생했습니다",
|
||||
"jobProblemBody": "{artist}의 \"{title}\" 작업 중 문제가 발생했습니다. 앱을 열어 확인해 보세요",
|
||||
"jobStalledBody": "{artist}의 \"{title}\" 오디오 다운로드가 지연되고 있습니다. 앱을 열어 계속 진행해 보세요"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "잘못된 도메인 형식",
|
||||
@@ -409,11 +412,11 @@
|
||||
"expiry": "이 코드는 {minutes}분 후에 만료되며 한 번만 사용할 수 있습니다.",
|
||||
"greeting": "안녕하세요,",
|
||||
"ignoreNote": "이 이메일을 요청하지 않으셨다면 무시하셔도 됩니다.",
|
||||
"intro": "계속하려면 로그인 페이지에 이 코드를 입력하세요:",
|
||||
"intro": "로그인 페이지에 아래 코드를 입력하여 계속 진행해 주세요:",
|
||||
"linkExpiry": "로그인 링크는 24시간 동안 유효하며 한 번만 사용할 수 있습니다.",
|
||||
"orLink": "또는 코드 없이 클릭 한 번으로 로그인하세요:",
|
||||
"orLink": "또는 코드 입력 없이 클릭 한 번으로 로그인하세요:",
|
||||
"signInButton": "로그인",
|
||||
"subject": "{brand_name} 로그인 코드: {code}"
|
||||
"subject": "[{brand_name}] 로그인 코드: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "가사를 직접 검토하기 번거로우신가요? Made For You를 선택하시면 24시간 이내에 전체 비디오를 대신 제작해 전달해 드립니다:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Tiada audio tersedia untuk bentuk gelombang",
|
||||
"sessionSaveError": "Data pembetulan diperlukan",
|
||||
"invalidIsDuetFlag": "is_duet mestilah boolean (benar atau salah)",
|
||||
"previewMissingTimings": "Baris \"{line}\" mempunyai perkataan tanpa pemasaan. Segerakkan baris itu, kemudian cuba pratonton semula."
|
||||
"previewMissingTimings": "Baris \"{line}\" mempunyai perkataan tanpa pemasaan. Segerakkan baris tersebut, kemudian cuba pratonton sekali lagi."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Carian audio tidak didayakan untuk penyewa ini",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video Sedia!",
|
||||
"videoReadyBody": "Video karaoke anda untuk \"{title}\" oleh {artist} sedia untuk dimuat turun",
|
||||
"confirmDurationTitle": "Sahkan kos kerja",
|
||||
"confirmDurationBody": "\"{title}\" oleh {artist} memerlukan pengesahan kos untuk diteruskan"
|
||||
"confirmDurationBody": "\"{title}\" oleh {artist} memerlukan pengesahan kos untuk diteruskan",
|
||||
"jobProblemTitle": "Terdapat masalah dengan video anda",
|
||||
"jobProblemBody": "\"{title}\" oleh {artist} menghadapi masalah. Buka aplikasi untuk melihat apa yang berlaku",
|
||||
"jobStalledBody": "Muat turun audio untuk \"{title}\" oleh {artist} tersekat. Kami boleh terus mencuba jika anda membuka aplikasi"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Format domain tidak sah",
|
||||
@@ -406,12 +409,12 @@
|
||||
"subject": "Kod Nomad Karaoke anda: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Kod ini tamat tempoh dalam {minutes} minit dan hanya boleh digunakan sekali.",
|
||||
"expiry": "Kod ini akan tamat tempoh dalam masa {minutes} minit dan hanya boleh digunakan sekali.",
|
||||
"greeting": "Hai,",
|
||||
"ignoreNote": "Jika anda tidak meminta e-mel ini, anda boleh mengabaikannya dengan selamat.",
|
||||
"intro": "Masukkan kod ini di halaman log masuk untuk meneruskan:",
|
||||
"linkExpiry": "Pautan log masuk berfungsi selama 24 jam dan hanya boleh digunakan sekali.",
|
||||
"orLink": "Atau langkau kod dan log masuk dengan satu klik:",
|
||||
"linkExpiry": "Pautan log masuk ini sah selama 24 jam dan hanya boleh digunakan sekali sahaja.",
|
||||
"orLink": "Atau langkau kod ini dan log masuk dengan satu klik:",
|
||||
"signInButton": "Log Masuk",
|
||||
"subject": "Kod log masuk {brand_name} anda: {code}"
|
||||
},
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Ingen lyd tilgjengelig for bølgeform",
|
||||
"sessionSaveError": "Korreksjonsdata er påkrevd",
|
||||
"invalidIsDuetFlag": "is_duet må være en boolean (true eller false)",
|
||||
"previewMissingTimings": "Linjen «{line}» har et ord uten timing. Synkroniser den linjen, og prøv forhåndsvisningen på nytt."
|
||||
"previewMissingTimings": "Linjen «{line}» har et ord uten timing. Synkroniser linjen, og prøv forhåndsvisningen på nytt."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Lydsøk er ikke aktivert for denne kontoen",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video klar!",
|
||||
"videoReadyBody": "Karaokevideoen din for \"{title}\" av {artist} er klar for nedlasting",
|
||||
"confirmDurationTitle": "Bekreft jobbkostnad",
|
||||
"confirmDurationBody": "\"{title}\" av {artist} trenger en kostnadsbekreftelse for å fortsette"
|
||||
"confirmDurationBody": "\"{title}\" av {artist} trenger en kostnadsbekreftelse for å fortsette",
|
||||
"jobProblemTitle": "Det er et problem med videoen din",
|
||||
"jobProblemBody": "Det oppsto et problem med «{title}» av {artist}. Åpne appen for å se hva som skjedde",
|
||||
"jobStalledBody": "Nedlastingen av lyd for «{title}» av {artist} har stoppet opp. Vi kan fortsette å prøve hvis du åpner appen"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Ugyldig domeneformat",
|
||||
@@ -408,12 +411,12 @@
|
||||
"loginCode": {
|
||||
"expiry": "Denne koden utløper om {minutes} minutter og kan bare brukes én gang.",
|
||||
"greeting": "Hei,",
|
||||
"ignoreNote": "Hvis du ikke ba om denne e-posten, kan du trygt se bort fra den.",
|
||||
"intro": "Skriv inn denne koden på påloggingssiden for å fortsette:",
|
||||
"linkExpiry": "Påloggingslenken virker i 24 timer og kan bare brukes én gang.",
|
||||
"orLink": "Eller hopp over koden og logg på med ett klikk:",
|
||||
"signInButton": "Logg på",
|
||||
"subject": "Din påloggingskode for {brand_name}: {code}"
|
||||
"ignoreNote": "Hvis du ikke ba om denne e-posten, kan du trygt ignorere den.",
|
||||
"intro": "Skriv inn denne koden på innloggingssiden for å fortsette:",
|
||||
"linkExpiry": "Innloggingslenken er gyldig i 24 timer og kan bare brukes én gang.",
|
||||
"orLink": "Eller hopp over koden og logg inn med ett klikk:",
|
||||
"signInButton": "Logg inn",
|
||||
"subject": "Din innloggingskode for {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Vil du helst slippe å gå gjennom teksten selv? Velg Made For You, så lager jeg hele videoen for deg, levert innen 24 timer:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Geen audio beschikbaar voor golfvorm",
|
||||
"sessionSaveError": "Correctiegegevens zijn vereist",
|
||||
"invalidIsDuetFlag": "is_duet moet een boolean (true of false) zijn",
|
||||
"previewMissingTimings": "De regel \"{line}\" bevat een woord zonder timing. Synchroniseer die regel en probeer de preview opnieuw."
|
||||
"previewMissingTimings": "De regel \"{line}\" bevat een woord zonder timing. Synchroniseer die regel en bekijk het voorbeeld opnieuw."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Audio zoeken is niet ingeschakeld voor deze tenant",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video klaar!",
|
||||
"videoReadyBody": "Je karaokevideo voor \"{title}\" van {artist} is klaar om te downloaden",
|
||||
"confirmDurationTitle": "Bevestig kosten",
|
||||
"confirmDurationBody": "Voor \"{title}\" van {artist} moet je de kosten bevestigen om door te gaan"
|
||||
"confirmDurationBody": "Voor \"{title}\" van {artist} moet je de kosten bevestigen om door te gaan",
|
||||
"jobProblemTitle": "Er is een probleem met je video",
|
||||
"jobProblemBody": "Er is een probleem opgetreden bij \"{title}\" van {artist}. Open de app om te zien wat er aan de hand is",
|
||||
"jobStalledBody": "Het downloaden van de audio voor \"{title}\" van {artist} is vastgelopen. We kunnen het blijven proberen als je de app opent"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Ongeldig domeinformaat",
|
||||
@@ -406,11 +409,11 @@
|
||||
"subject": "Je Nomad Karaoke code: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Deze code verloopt over {minutes} minuten en kan maar één keer worden gebruikt.",
|
||||
"expiry": "Deze code verloopt over {minutes} minuten en kan slechts één keer worden gebruikt.",
|
||||
"greeting": "Hallo,",
|
||||
"ignoreNote": "Als je deze e-mail niet hebt aangevraagd, kun je hem gerust negeren.",
|
||||
"intro": "Voer deze code in op de inlogpagina om verder te gaan:",
|
||||
"linkExpiry": "De inloglink werkt 24 uur en kan maar één keer worden gebruikt.",
|
||||
"ignoreNote": "Als je deze e-mail niet hebt aangevraagd, kun je deze veilig negeren.",
|
||||
"intro": "Voer deze code in op de inlogpagina om door te gaan:",
|
||||
"linkExpiry": "De inloglink is 24 uur geldig en kan maar één keer worden gebruikt.",
|
||||
"orLink": "Of sla de code over en log in met één klik:",
|
||||
"signInButton": "Inloggen",
|
||||
"subject": "Je {brand_name}-inlogcode: {code}"
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Brak dostępnego dźwięku dla fali dźwiękowej",
|
||||
"sessionSaveError": "Dane poprawek są wymagane",
|
||||
"invalidIsDuetFlag": "is_duet musi być wartością logiczną (true lub false)",
|
||||
"previewMissingTimings": "Wiersz „{line}” zawiera słowo bez synchronizacji. Zsynchronizuj ten wiersz, a następnie spróbuj ponownie wyświetlić podgląd."
|
||||
"previewMissingTimings": "W wersie „{line}” brakuje synchronizacji dla jednego ze słów. Zsynchronizuj ten wers i spróbuj ponownie włączyć podgląd."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Wyszukiwanie audio nie jest włączone dla tego konta",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Wideo gotowe!",
|
||||
"videoReadyBody": "Twoje wideo karaoke dla \"{title}\" wykonawcy {artist} jest gotowe do pobrania",
|
||||
"confirmDurationTitle": "Potwierdź koszt zadania",
|
||||
"confirmDurationBody": "\"{title}\" wykonawcy {artist} wymaga potwierdzenia kosztów, aby kontynuować"
|
||||
"confirmDurationBody": "\"{title}\" wykonawcy {artist} wymaga potwierdzenia kosztów, aby kontynuować",
|
||||
"jobProblemTitle": "Problem z Twoim wideo",
|
||||
"jobProblemBody": "Wystąpił problem z utworem „{title}” wykonawcy {artist}. Otwórz aplikację, aby zobaczyć szczegóły",
|
||||
"jobStalledBody": "Pobieranie dźwięku dla utworu „{title}” ({artist}) utknęło. Możemy próbować dalej, jeśli otworzysz aplikację"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Nieprawidłowy format domeny",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "Twój kod Nomad Karaoke: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Ten kod wygaśnie za {minutes} min i można go użyć tylko raz.",
|
||||
"expiry": "Ten kod wygasa za {minutes} minut i może zostać użyty tylko raz.",
|
||||
"greeting": "Cześć,",
|
||||
"ignoreNote": "Jeśli nie prosiłeś(-aś) o tę wiadomość, możesz ją bezpiecznie zignorować.",
|
||||
"ignoreNote": "Jeśli nie prosiłeś o ten email, możesz go bezpiecznie zignorować.",
|
||||
"intro": "Wpisz ten kod na stronie logowania, aby kontynuować:",
|
||||
"linkExpiry": "Link do logowania działa przez 24 godziny i można go użyć tylko raz.",
|
||||
"orLink": "Albo pomiń kod i zaloguj się jednym kliknięciem:",
|
||||
"linkExpiry": "Link do logowania jest ważny przez 24 godziny i można go użyć tylko raz.",
|
||||
"orLink": "Możesz też pominąć kod i zalogować się jednym kliknięciem:",
|
||||
"signInButton": "Zaloguj się",
|
||||
"subject": "Twój kod logowania do {brand_name}: {code}"
|
||||
"subject": "Twój kod do logowania w {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Wolisz nie sprawdzać tekstu samodzielnie? Wybierz Made For You, a przygotuję całe wideo za Ciebie – gotowe w ciągu 24 godzin:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Nenhum áudio disponível para a forma de onda",
|
||||
"sessionSaveError": "Dados de correção são obrigatórios",
|
||||
"invalidIsDuetFlag": "is_duet deve ser um booleano (verdadeiro ou falso)",
|
||||
"previewMissingTimings": "A linha \"{line}\" tem uma palavra sem tempo definido. Sincronize essa linha e tente a pré-visualização novamente."
|
||||
"previewMissingTimings": "O verso \"{line}\" tem uma palavra sem sincronização. Sincronize essa linha e tente ver a prévia novamente."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "A pesquisa de áudio não está ativada para este locatário",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Vídeo Pronto!",
|
||||
"videoReadyBody": "Seu vídeo de karaokê para \"{title}\" de {artist} está pronto para baixar",
|
||||
"confirmDurationTitle": "Confirmar custo do serviço",
|
||||
"confirmDurationBody": "\"{title}\" de {artist} precisa de uma confirmação de custo para continuar"
|
||||
"confirmDurationBody": "\"{title}\" de {artist} precisa de uma confirmação de custo para continuar",
|
||||
"jobProblemTitle": "Houve um problema com o seu vídeo",
|
||||
"jobProblemBody": "Houve um problema com \"{title}\", de {artist}. Abra o app para ver o que aconteceu",
|
||||
"jobStalledBody": "O download do áudio de \"{title}\", de {artist}, travou. Abra o app para continuarmos tentando"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Formato de domínio inválido",
|
||||
@@ -410,10 +413,10 @@
|
||||
"greeting": "Olá,",
|
||||
"ignoreNote": "Se você não solicitou este e-mail, pode ignorá-lo com segurança.",
|
||||
"intro": "Digite este código na página de login para continuar:",
|
||||
"linkExpiry": "O link de acesso funciona por 24 horas e só pode ser usado uma vez.",
|
||||
"orLink": "Ou pule o código e entre com um clique:",
|
||||
"linkExpiry": "O link de login é válido por 24 horas e só pode ser usado uma vez.",
|
||||
"orLink": "Ou pule o código e faça login com apenas um clique:",
|
||||
"signInButton": "Entrar",
|
||||
"subject": "Seu código de acesso ao {brand_name}: {code}"
|
||||
"subject": "Seu código de login do {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Prefere não revisar a letra você mesmo? Escolha o Feito Para Você e eu farei o vídeo inteiro para você, entregue em até 24 horas:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Niciun fișier audio disponibil pentru forma de undă",
|
||||
"sessionSaveError": "Datele de corecție sunt obligatorii",
|
||||
"invalidIsDuetFlag": "is_duet trebuie să fie un boolean (true sau false)",
|
||||
"previewMissingTimings": "Rândul „{line}” conține un cuvânt fără sincronizare. Sincronizează acel rând, apoi încearcă din nou previzualizarea."
|
||||
"previewMissingTimings": "Versul „{line}” conține un cuvânt fără sincronizare. Sincronizează acel vers, apoi încearcă din nou previzualizarea."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Căutarea audio nu este activată pentru acest tenant",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Videoclipul este gata!",
|
||||
"videoReadyBody": "Videoclipul tău de karaoke pentru \"{title}\" de {artist} este gata de descărcare",
|
||||
"confirmDurationTitle": "Confirmă costul lucrării",
|
||||
"confirmDurationBody": "\"{title}\" de {artist} necesită o confirmare a costului pentru a continua"
|
||||
"confirmDurationBody": "\"{title}\" de {artist} necesită o confirmare a costului pentru a continua",
|
||||
"jobProblemTitle": "Există o problemă cu videoclipul tău",
|
||||
"jobProblemBody": "A apărut o problemă cu piesa „{title}” de {artist}. Deschide aplicația pentru a vedea ce s-a întâmplat",
|
||||
"jobStalledBody": "Descărcarea audio pentru piesa „{title}” de {artist} s-a blocat. Putem încerca în continuare dacă deschizi aplicația"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Format de domeniu invalid",
|
||||
@@ -407,13 +410,13 @@
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Acest cod expiră în {minutes} minute și poate fi folosit o singură dată.",
|
||||
"greeting": "Bună,",
|
||||
"ignoreNote": "Dacă nu ai solicitat acest e-mail, îl poți ignora în siguranță.",
|
||||
"greeting": "Salut,",
|
||||
"ignoreNote": "Dacă nu ai solicitat acest email, îl poți ignora în siguranță.",
|
||||
"intro": "Introdu acest cod pe pagina de conectare pentru a continua:",
|
||||
"linkExpiry": "Linkul de conectare funcționează timp de 24 de ore și poate fi folosit o singură dată.",
|
||||
"linkExpiry": "Linkul de conectare este valabil timp de 24 de ore și poate fi folosit o singură dată.",
|
||||
"orLink": "Sau sari peste cod și conectează-te cu un singur clic:",
|
||||
"signInButton": "Conectare",
|
||||
"subject": "Codul tău de conectare la {brand_name}: {code}"
|
||||
"signInButton": "Conectează-te",
|
||||
"subject": "Codul tău de conectare {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Preferi să nu verifici tu versurile? Alege Made For You și voi face eu întregul videoclip pentru tine, livrat în 24 de ore:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Нет аудио для осциллограммы",
|
||||
"sessionSaveError": "Требуются данные исправлений",
|
||||
"invalidIsDuetFlag": "is_duet должно быть булевым значением (true или false)",
|
||||
"previewMissingTimings": "В строке «{line}» есть слово без тайминга. Синхронизируй эту строку и попробуй предпросмотр ещё раз."
|
||||
"previewMissingTimings": "В строке «{line}» есть слово без тайминга. Синхронизируй эту строку и попробуй снова включить предпросмотр."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Поиск аудио не включен для этого аккаунта",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Видео готово!",
|
||||
"videoReadyBody": "Твое караоке-видео для \"{title}\" от {artist} готово к скачиванию",
|
||||
"confirmDurationTitle": "Подтверди стоимость работы",
|
||||
"confirmDurationBody": "Для продолжения работы над \"{title}\" исполнителя {artist} необходимо подтвердить стоимость"
|
||||
"confirmDurationBody": "Для продолжения работы над \"{title}\" исполнителя {artist} необходимо подтвердить стоимость",
|
||||
"jobProblemTitle": "С твоим видео возникла проблема",
|
||||
"jobProblemBody": "С треком «{title}» ({artist}) возникла проблема. Открой приложение, чтобы узнать, что случилось",
|
||||
"jobStalledBody": "Скачивание аудио для «{title}» ({artist}) зависло. Мы можем продолжить попытки, если ты откроешь приложение"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Неверный формат домена",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "Твой код Nomad Karaoke: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Срок действия кода истекает через {minutes} мин., и его можно использовать только один раз.",
|
||||
"greeting": "Здравствуйте!",
|
||||
"ignoreNote": "Если вы не запрашивали это письмо, просто проигнорируйте его.",
|
||||
"intro": "Введите этот код на странице входа, чтобы продолжить:",
|
||||
"linkExpiry": "Ссылка для входа действует 24 часа, и её можно использовать только один раз.",
|
||||
"orLink": "Или пропустите ввод кода и войдите одним нажатием:",
|
||||
"expiry": "Срок действия этого кода истекает через {minutes} минут, и его можно использовать только один раз.",
|
||||
"greeting": "Привет,",
|
||||
"ignoreNote": "Если ты не запрашивал это письмо, можешь смело его проигнорировать.",
|
||||
"intro": "Введи этот код на странице входа, чтобы продолжить:",
|
||||
"linkExpiry": "Ссылка для входа действует 24 часа и может быть использована только один раз.",
|
||||
"orLink": "Или пропусти ввод кода и войди в один клик:",
|
||||
"signInButton": "Войти",
|
||||
"subject": "Ваш код для входа в {brand_name}: {code}"
|
||||
"subject": "Твой код для входа в {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Не хочешь проверять текст самостоятельно? Выбери Made For You, и я сделаю всё видео за тебя и пришлю в течение 24 часов:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Nie je k dispozícii žiadny zvuk pre zvukovú vlnu",
|
||||
"sessionSaveError": "Vyžadujú sa údaje o opravách",
|
||||
"invalidIsDuetFlag": "is_duet musí byť boolean (true alebo false)",
|
||||
"previewMissingTimings": "Riadok „{line}“ obsahuje slovo bez časovania. Synchronizuj tento riadok a skús náhľad znova."
|
||||
"previewMissingTimings": "Riadok „{line}“ obsahuje slovo bez časovania. Synchronizuj tento riadok a potom skús náhľad znova."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Vyhľadávanie zvuku nie je pre tohto nájomcu povolené",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video je pripravené!",
|
||||
"videoReadyBody": "Tvoje karaoke video pre \"{title}\" od {artist} je pripravené na stiahnutie",
|
||||
"confirmDurationTitle": "Potvrď cenu úlohy",
|
||||
"confirmDurationBody": "\"{title}\" od {artist} vyžaduje potvrdenie ceny pre pokračovanie"
|
||||
"confirmDurationBody": "\"{title}\" od {artist} vyžaduje potvrdenie ceny pre pokračovanie",
|
||||
"jobProblemTitle": "Nastal problém s tvojím videom",
|
||||
"jobProblemBody": "Pri skladbe „{title}“ od {artist} sa vyskytol problém. Otvor aplikáciu a zisti, čo sa stalo",
|
||||
"jobStalledBody": "Sťahovanie zvuku pre skladbu „{title}“ od {artist} sa zaseklo. Ak otvoríš aplikáciu, môžeme to skúšať ďalej"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Neplatný formát domény",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "Tvoj kód pre Nomad Karaoke: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Platnosť tohto kódu vyprší o {minutes} minút a možno ho použiť iba raz.",
|
||||
"greeting": "Dobrý deň,",
|
||||
"ignoreNote": "Ak ste o tento e-mail nežiadali, môžete ho pokojne ignorovať.",
|
||||
"intro": "Ak chcete pokračovať, zadajte tento kód na prihlasovacej stránke:",
|
||||
"linkExpiry": "Prihlasovací odkaz platí 24 hodín a možno ho použiť iba raz.",
|
||||
"orLink": "Alebo kód preskočte a prihláste sa jedným kliknutím:",
|
||||
"expiry": "Tento kód vyprší o {minutes} minút a dá sa použiť len raz.",
|
||||
"greeting": "Ahoj,",
|
||||
"ignoreNote": "Ak si tento email nevyžiadal, môžeš ho bezpečne ignorovať.",
|
||||
"intro": "Ak chceš pokračovať, zadaj tento kód na prihlasovacej stránke:",
|
||||
"linkExpiry": "Prihlasovací odkaz je platný 24 hodín a možno ho použiť len raz.",
|
||||
"orLink": "Alebo preskoč kód a prihlás sa jedným kliknutím:",
|
||||
"signInButton": "Prihlásiť sa",
|
||||
"subject": "Váš prihlasovací kód pre {brand_name}: {code}"
|
||||
"subject": "Tvoj prihlasovací kód pre {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Nechce sa ti kontrolovať text piesne? Vyber si možnosť Made For You a celé video ti vytvorím ja, s doručením do 24 hodín:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Inget ljud tillgängligt för vågform",
|
||||
"sessionSaveError": "Korrigeringsdata krävs",
|
||||
"invalidIsDuetFlag": "is_duet måste vara ett booleskt värde (true eller false)",
|
||||
"previewMissingTimings": "Raden \"{line}\" har ett ord utan timing. Synka den raden och försök sedan förhandsgranska igen."
|
||||
"previewMissingTimings": "Raden \"{line}\" innehåller ett ord som saknar tidsangivelse. Synka raden och prova att förhandsgranska igen."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Ljudsökning är inte aktiverad för denna klient",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Videon är klar!",
|
||||
"videoReadyBody": "Din karaokevideo för \"{title}\" av {artist} är redo att laddas ner",
|
||||
"confirmDurationTitle": "Bekräfta jobbkostnad",
|
||||
"confirmDurationBody": "\"{title}\" av {artist} kräver att du bekräftar kostnaden för att fortsätta"
|
||||
"confirmDurationBody": "\"{title}\" av {artist} kräver att du bekräftar kostnaden för att fortsätta",
|
||||
"jobProblemTitle": "Det har uppstått ett problem med din video",
|
||||
"jobProblemBody": "Det uppstod ett problem med \"{title}\" av {artist}. Öppna appen för att se vad som hände",
|
||||
"jobStalledBody": "Nedladdningen av ljudet för \"{title}\" av {artist} har fastnat. Vi kan fortsätta försöka om du öppnar appen"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Ogiltigt domänformat",
|
||||
@@ -406,11 +409,11 @@
|
||||
"subject": "Din Nomad Karaoke-kod: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Koden går ut om {minutes} minuter och kan bara användas en gång.",
|
||||
"expiry": "Den här koden går ut om {minutes} minuter och kan bara användas en gång.",
|
||||
"greeting": "Hej,",
|
||||
"ignoreNote": "Om du inte har begärt det här mejlet kan du lugnt ignorera det.",
|
||||
"ignoreNote": "Om du inte begärde detta e-postmeddelande kan du säkert ignorera det.",
|
||||
"intro": "Ange den här koden på inloggningssidan för att fortsätta:",
|
||||
"linkExpiry": "Inloggningslänken fungerar i 24 timmar och kan bara användas en gång.",
|
||||
"linkExpiry": "Inloggningslänken är giltig i 24 timmar och kan bara användas en gång.",
|
||||
"orLink": "Eller hoppa över koden och logga in med ett klick:",
|
||||
"signInButton": "Logga in",
|
||||
"subject": "Din inloggningskod för {brand_name}: {code}"
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "ไม่มีเสียงสำหรับรูปคลื่นเสียง",
|
||||
"sessionSaveError": "จำเป็นต้องมีข้อมูลการแก้ไข",
|
||||
"invalidIsDuetFlag": "is_duet ต้องเป็นค่าบูลีน (true หรือ false)",
|
||||
"previewMissingTimings": "บรรทัด \"{line}\" มีคำที่ไม่มีการตั้งเวลา ซิงค์บรรทัดนั้นแล้วลองแสดงตัวอย่างอีกครั้ง"
|
||||
"previewMissingTimings": "ท่อน \"{line}\" มีคำที่ยังไม่ได้กำหนดจังหวะเวลา ซิงค์ท่อนนี้แล้วลองดูตัวอย่างอีกครั้ง"
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "ไม่ได้เปิดใช้งานการค้นหาเสียงสำหรับผู้เช่ารายนี้",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "วิดีโอพร้อมแล้ว!",
|
||||
"videoReadyBody": "วิดีโอคาราโอเกะเพลง \"{title}\" โดย {artist} พร้อมให้ดาวน์โหลดแล้ว",
|
||||
"confirmDurationTitle": "ยืนยันค่าใช้จ่ายของงาน",
|
||||
"confirmDurationBody": "\"{title}\" โดย {artist} ต้องการการยืนยันค่าใช้จ่ายเพื่อดำเนินการต่อ"
|
||||
"confirmDurationBody": "\"{title}\" โดย {artist} ต้องการการยืนยันค่าใช้จ่ายเพื่อดำเนินการต่อ",
|
||||
"jobProblemTitle": "เกิดปัญหากับวิดีโอของคุณ",
|
||||
"jobProblemBody": "เกิดปัญหากับเพลง \"{title}\" ของ {artist} เปิดแอปเพื่อดูรายละเอียด",
|
||||
"jobStalledBody": "การดาวน์โหลดเสียงสำหรับเพลง \"{title}\" ของ {artist} ค้างอยู่ เปิดแอปเพื่อให้ระบบดำเนินการต่อได้เลย"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "รูปแบบโดเมนไม่ถูกต้อง",
|
||||
@@ -406,13 +409,13 @@
|
||||
"subject": "รหัส Nomad Karaoke ของคุณ: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "รหัสนี้จะหมดอายุใน {minutes} นาทีและใช้ได้เพียงครั้งเดียว",
|
||||
"greeting": "สวัสดี",
|
||||
"ignoreNote": "หากคุณไม่ได้ขออีเมลนี้ คุณสามารถเพิกเฉยได้อย่างปลอดภัย",
|
||||
"intro": "ป้อนรหัสนี้ในหน้าลงชื่อเข้าใช้เพื่อดำเนินการต่อ:",
|
||||
"linkExpiry": "ลิงก์ลงชื่อเข้าใช้ใช้งานได้ 24 ชั่วโมงและใช้ได้เพียงครั้งเดียว",
|
||||
"orLink": "หรือข้ามรหัสแล้วลงชื่อเข้าใช้ด้วยการคลิกเดียว:",
|
||||
"signInButton": "ลงชื่อเข้าใช้",
|
||||
"expiry": "รหัสนี้จะหมดอายุใน {minutes} นาที และสามารถใช้ได้เพียงครั้งเดียวเท่านั้น",
|
||||
"greeting": "สวัสดี,",
|
||||
"ignoreNote": "หากคุณไม่ได้ร้องขออีเมลฉบับนี้ คุณสามารถเพิกเฉยต่ออีเมลนี้ได้เลย",
|
||||
"intro": "กรอกรหัสนี้ในหน้าลงชื่อเข้าใช้เพื่อดำเนินการต่อ:",
|
||||
"linkExpiry": "ลิงก์ลงชื่อเข้าใช้นี้ใช้งานได้ 24 ชั่วโมง และใช้ได้เพียงครั้งเดียวเท่านั้น",
|
||||
"orLink": "หรือข้ามการกรอกรหัส แล้วลงชื่อเข้าใช้ด้วยการคลิกเพียงครั้งเดียว:",
|
||||
"signInButton": "เข้าสู่ระบบ",
|
||||
"subject": "รหัสลงชื่อเข้าใช้ {brand_name} ของคุณ: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Walang available na audio para sa waveform",
|
||||
"sessionSaveError": "Kailangan ng correction data",
|
||||
"invalidIsDuetFlag": "Ang is_duet ay dapat isang boolean (true o false)",
|
||||
"previewMissingTimings": "Ang linyang \"{line}\" ay may salitang walang timing. I-sync ang linyang iyon, saka subukang muli ang preview."
|
||||
"previewMissingTimings": "May salitang walang timing sa linyang \"{line}\". I-sync ang linyang iyon, tapos subukan ulit ang preview."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Hindi naka-enable ang audio search para sa tenant na ito",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Handa na ang Video!",
|
||||
"videoReadyBody": "Handa nang i-download ang iyong karaoke video para sa \"{title}\" ni {artist}",
|
||||
"confirmDurationTitle": "Kumpirmahin ang gastos ng gawain",
|
||||
"confirmDurationBody": "Kailangan ng kumpirmasyon sa gastos ng \"{title}\" ni {artist} para makapagpatuloy"
|
||||
"confirmDurationBody": "Kailangan ng kumpirmasyon sa gastos ng \"{title}\" ni {artist} para makapagpatuloy",
|
||||
"jobProblemTitle": "May problema sa iyong video",
|
||||
"jobProblemBody": "Nagkaproblema ang \"{title}\" ni {artist}. Buksan ang app para makita ang nangyari",
|
||||
"jobStalledBody": "Na-stuck ang pag-download ng audio para sa \"{title}\" ni {artist}. Puwede naming ituloy ang pagsubok kung bubuksan mo ang app"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Mali ang format ng domain",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "Ang iyong Nomad Karaoke code: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Mag-e-expire ang code na ito sa loob ng {minutes} minuto at isang beses lang magagamit.",
|
||||
"expiry": "Mage-expire ang code na ito sa loob ng {minutes} minuto at isang beses lang pwedeng gamitin.",
|
||||
"greeting": "Kumusta,",
|
||||
"ignoreNote": "Kung hindi mo hiniling ang email na ito, puwede mo itong balewalain.",
|
||||
"ignoreNote": "Kung hindi mo ni-request ang email na ito, maaari mo itong balewalain.",
|
||||
"intro": "Ilagay ang code na ito sa sign-in page para magpatuloy:",
|
||||
"linkExpiry": "Gumagana ang sign-in link nang 24 oras at isang beses lang magagamit.",
|
||||
"orLink": "O laktawan ang code at mag-sign in sa isang click:",
|
||||
"linkExpiry": "Gagana ang sign-in link sa loob ng 24 na oras at maaari lamang itong gamitin nang isang beses.",
|
||||
"orLink": "O laktawan ang code at mag-sign in sa isang click lang:",
|
||||
"signInButton": "Mag-sign In",
|
||||
"subject": "Ang iyong sign-in code sa {brand_name}: {code}"
|
||||
"subject": "Ang iyong {brand_name} sign-in code: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Ayaw mo bang mag-review ng lyrics nang mag-isa? Piliin ang Made For You at ako na ang gagawa ng buong video para sa iyo, ihahatid sa loob ng 24 oras:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Dalga formu için ses mevcut değil",
|
||||
"sessionSaveError": "Düzeltme verisi gereklidir",
|
||||
"invalidIsDuetFlag": "is_duet bir boolean (true veya false) olmalı",
|
||||
"previewMissingTimings": "\"{line}\" satırında zamanlaması olmayan bir kelime var. O satırı senkronize et, ardından önizlemeyi tekrar dene."
|
||||
"previewMissingTimings": "\"{line}\" satırında zamanlaması eksik bir kelime var. Bu satırı senkronize et, ardından önizlemeyi tekrar dene."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Bu kiracı için ses arama etkin değil",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video Hazır!",
|
||||
"videoReadyBody": "{artist} - \"{title}\" karaoke videon indirilmeye hazır",
|
||||
"confirmDurationTitle": "İş maliyetini onayla",
|
||||
"confirmDurationBody": "Devam etmek için {artist} - \"{title}\" şarkısının maliyetini onaylaman gerekiyor"
|
||||
"confirmDurationBody": "Devam etmek için {artist} - \"{title}\" şarkısının maliyetini onaylaman gerekiyor",
|
||||
"jobProblemTitle": "Videonda bir sorun var",
|
||||
"jobProblemBody": "{artist} - \"{title}\" parçasında bir sorun oluştu. Ne olduğunu görmek için uygulamayı aç",
|
||||
"jobStalledBody": "{artist} - \"{title}\" parçasının ses indirmesi takıldı. Uygulamayı açarsan denemeye devam edebiliriz"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Geçersiz alan adı formatı",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "Nomad Karaoke kodun: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Bu kodun süresi {minutes} dakika içinde dolar ve yalnızca bir kez kullanılabilir.",
|
||||
"expiry": "Bu kod {minutes} dakika içinde sona erer ve sadece bir kez kullanılabilir.",
|
||||
"greeting": "Merhaba,",
|
||||
"ignoreNote": "Bu e-postayı siz istemediyseniz, güvenle yok sayabilirsiniz.",
|
||||
"intro": "Devam etmek için bu kodu giriş sayfasına girin:",
|
||||
"ignoreNote": "Bu e-postayı sen talep etmediysen, güvenle görmezden gelebilirsin.",
|
||||
"intro": "Devam etmek için bu kodu giriş sayfasına gir:",
|
||||
"linkExpiry": "Giriş bağlantısı 24 saat geçerlidir ve yalnızca bir kez kullanılabilir.",
|
||||
"orLink": "Ya da kodu atlayıp tek tıkla giriş yapın:",
|
||||
"orLink": "Veya kodu atlayıp tek tıkla giriş yap:",
|
||||
"signInButton": "Giriş Yap",
|
||||
"subject": "{brand_name} giriş kodunuz: {code}"
|
||||
"subject": "{brand_name} giriş kodun: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Şarkı sözü incelemesini kendin yapmak istemiyor musun? Made For You'yu seç, tüm videoyu senin için hazırlayıp 24 saat içinde teslim edeyim:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Немає аудіо для хвильової форми",
|
||||
"sessionSaveError": "Потрібні дані виправлень",
|
||||
"invalidIsDuetFlag": "is_duet має бути булевим значенням (true або false)",
|
||||
"previewMissingTimings": "У рядку «{line}» є слово без таймінгу. Синхронізуй цей рядок і спробуй попередній перегляд ще раз."
|
||||
"previewMissingTimings": "Рядок «{line}» містить слово без таймінгу. Синхронізуй цей рядок, а потім знову спробуй попередній перегляд."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Пошук аудіо не ввімкнено для цього орендаря",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Відео готове!",
|
||||
"videoReadyBody": "Твоє караоке-відео для \"{title}\" від {artist} готове до завантаження",
|
||||
"confirmDurationTitle": "Підтвердь вартість завдання",
|
||||
"confirmDurationBody": "\"{title}\" від {artist} потребує підтвердження вартості для продовження"
|
||||
"confirmDurationBody": "\"{title}\" від {artist} потребує підтвердження вартості для продовження",
|
||||
"jobProblemTitle": "Виникла проблема з твоїм відео",
|
||||
"jobProblemBody": "Виникла проблема з «{title}» ({artist}). Відкрий застосунок, щоб дізнатися, що сталося",
|
||||
"jobStalledBody": "Завантаження аудіо для «{title}» ({artist}) зависло. Ми можемо спробувати знову, якщо ти відкриєш застосунок"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Недійсний формат домену",
|
||||
@@ -406,14 +409,14 @@
|
||||
"subject": "Твій код Nomad Karaoke: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Термін дії коду спливає через {minutes} хв, і його можна використати лише один раз.",
|
||||
"greeting": "Вітаємо!",
|
||||
"ignoreNote": "Якщо ви не запитували цей лист, просто проігноруйте його.",
|
||||
"intro": "Введіть цей код на сторінці входу, щоб продовжити:",
|
||||
"linkExpiry": "Посилання для входу діє 24 години, і його можна використати лише один раз.",
|
||||
"orLink": "Або пропустіть код і увійдіть одним натисканням:",
|
||||
"expiry": "Цей код діє протягом {minutes} хвилин і може бути використаний лише один раз.",
|
||||
"greeting": "Привіт,",
|
||||
"ignoreNote": "Якщо ти не запитував цей email, можеш сміливо його проігнорувати.",
|
||||
"intro": "Введи цей код на сторінці входу, щоб продовжити:",
|
||||
"linkExpiry": "Посилання для входу діє протягом 24 годин і може бути використане лише один раз.",
|
||||
"orLink": "Або пропусти введення коду та увійди в один клік:",
|
||||
"signInButton": "Увійти",
|
||||
"subject": "Ваш код для входу в {brand_name}: {code}"
|
||||
"subject": "Твій код для входу в {brand_name}: {code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "Не хочеш перевіряти текст самостійно? Обери Made For You, і я зроблю все відео за тебе з доставкою протягом 24 годин:",
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "Không có âm thanh cho dạng sóng",
|
||||
"sessionSaveError": "Yêu cầu dữ liệu chỉnh sửa",
|
||||
"invalidIsDuetFlag": "is_duet phải là kiểu boolean (true hoặc false)",
|
||||
"previewMissingTimings": "Dòng \"{line}\" có một từ chưa được căn thời gian. Hãy đồng bộ dòng đó rồi thử xem trước lại."
|
||||
"previewMissingTimings": "Dòng \"{line}\" có từ chưa khớp thời gian. Hãy đồng bộ dòng đó rồi thử xem trước lại nhé."
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "Tìm kiếm âm thanh không được bật cho tenant này",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "Video đã sẵn sàng!",
|
||||
"videoReadyBody": "Video karaoke của bạn cho bài hát \"{title}\" của {artist} đã sẵn sàng để tải xuống",
|
||||
"confirmDurationTitle": "Xác nhận chi phí công việc",
|
||||
"confirmDurationBody": "\"{title}\" của {artist} cần xác nhận chi phí để tiếp tục"
|
||||
"confirmDurationBody": "\"{title}\" của {artist} cần xác nhận chi phí để tiếp tục",
|
||||
"jobProblemTitle": "Đã xảy ra sự cố với video của bạn",
|
||||
"jobProblemBody": "\"{title}\" của {artist} đã gặp sự cố. Mở ứng dụng để xem chi tiết nhé",
|
||||
"jobStalledBody": "Quá trình tải âm thanh cho \"{title}\" của {artist} đang bị kẹt. Chúng tôi có thể tiếp tục thử lại nếu bạn mở ứng dụng"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "Định dạng tên miền không hợp lệ",
|
||||
@@ -406,12 +409,12 @@
|
||||
"subject": "Mã Nomad Karaoke của bạn: {code}"
|
||||
},
|
||||
"loginCode": {
|
||||
"expiry": "Mã này sẽ hết hạn sau {minutes} phút và chỉ dùng được một lần.",
|
||||
"greeting": "Xin chào,",
|
||||
"ignoreNote": "Nếu bạn không yêu cầu email này, bạn có thể yên tâm bỏ qua.",
|
||||
"expiry": "Mã này sẽ hết hạn trong {minutes} phút và chỉ có thể sử dụng một lần.",
|
||||
"greeting": "Chào bạn,",
|
||||
"ignoreNote": "Nếu bạn không yêu cầu email này, bạn có thể bỏ qua nó một cách an toàn.",
|
||||
"intro": "Nhập mã này trên trang đăng nhập để tiếp tục:",
|
||||
"linkExpiry": "Liên kết đăng nhập có hiệu lực trong 24 giờ và chỉ dùng được một lần.",
|
||||
"orLink": "Hoặc bỏ qua mã và đăng nhập chỉ với một lần nhấp:",
|
||||
"linkExpiry": "Liên kết đăng nhập có hiệu lực trong 24 giờ và chỉ có thể sử dụng một lần.",
|
||||
"orLink": "Hoặc bỏ qua mã và đăng nhập chỉ với một cú nhấp chuột:",
|
||||
"signInButton": "Đăng nhập",
|
||||
"subject": "Mã đăng nhập {brand_name} của bạn: {code}"
|
||||
},
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
"waveformNoAudio": "没有可生成波形的音频",
|
||||
"sessionSaveError": "需要校对数据",
|
||||
"invalidIsDuetFlag": "is_duet 必须是布尔值(true 或 false)",
|
||||
"previewMissingTimings": "“{line}”这一行有一个没有时间轴的单词。请先同步该行,然后再次尝试预览。"
|
||||
"previewMissingTimings": "“{line}”这一行有未设置时间轴的字词。请先同步该行时间轴,然后再尝试预览。"
|
||||
},
|
||||
"audioSearch": {
|
||||
"notEnabled": "此租户未启用音频搜索",
|
||||
@@ -178,7 +178,10 @@
|
||||
"videoReadyTitle": "视频已就绪!",
|
||||
"videoReadyBody": "您制作的卡拉OK视频({artist} - {title})已准备好下载",
|
||||
"confirmDurationTitle": "确认任务费用",
|
||||
"confirmDurationBody": "{artist} 的 \"{title}\" 需要确认费用后才能继续"
|
||||
"confirmDurationBody": "{artist} 的 \"{title}\" 需要确认费用后才能继续",
|
||||
"jobProblemTitle": "您的视频制作遇到问题",
|
||||
"jobProblemBody": "{artist} 的《{title}》遇到问题。打开 App 查看具体情况",
|
||||
"jobStalledBody": "{artist} 的《{title}》音频下载已卡住。打开 App 即可继续尝试"
|
||||
},
|
||||
"admin": {
|
||||
"invalidDomainFormat": "无效的域名格式",
|
||||
@@ -408,12 +411,12 @@
|
||||
"loginCode": {
|
||||
"expiry": "此验证码将在 {minutes} 分钟后过期,且只能使用一次。",
|
||||
"greeting": "你好,",
|
||||
"ignoreNote": "如果你没有请求此邮件,可以放心忽略。",
|
||||
"intro": "请在登录页面输入此验证码以继续:",
|
||||
"linkExpiry": "登录链接 24 小时内有效,且只能使用一次。",
|
||||
"ignoreNote": "如果您没有请求此邮件,请放心忽略。",
|
||||
"intro": "在登录页面输入此验证码以继续:",
|
||||
"linkExpiry": "登录链接有效期为 24 小时,且只能使用一次。",
|
||||
"orLink": "或者跳过验证码,一键登录:",
|
||||
"signInButton": "登录",
|
||||
"subject": "你的 {brand_name} 登录验证码:{code}"
|
||||
"subject": "您的 {brand_name} 登录验证码:{code}"
|
||||
},
|
||||
"conversion": {
|
||||
"madeForYouLine": "不想自己校对歌词?选择“为您定制”,我将为您制作整支视频,24小时内交付:",
|
||||
|
||||
@@ -4,6 +4,10 @@ Processes every job in a batch (state_data.batch_id == batch_id): runs the audio
|
||||
search, auto-selects a confident lossless ("tier 1") match when the batch enabled
|
||||
it, and otherwise parks the job in AWAITING_AUDIO_SELECTION for the review queue.
|
||||
|
||||
Album-mode batches (picked in Bulk "By album") make ONE flacfetch album search:
|
||||
each track's file is resolved inside the album's torrents and the whole album is
|
||||
taken from one torrent. Only tracks no torrent covers are searched per track.
|
||||
|
||||
Runs as a Cloud Run Job (one execution per batch) so it survives API instance
|
||||
scale-down and the user can close the tab. Mirrors the single-job search flow in
|
||||
backend/api/routes/audio_search.py:search_audio.
|
||||
@@ -14,6 +18,7 @@ Usage:
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.audio_search_service import (
|
||||
@@ -29,8 +34,15 @@ from backend.services.worker_service import get_worker_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# How many per-song searches to run concurrently within a batch.
|
||||
SEARCH_CONCURRENCY = 4
|
||||
# Per-track searches in flight at once within a batch. flacfetch runs searches on
|
||||
# a single worker, so more than one just queues there and the queued ones run out
|
||||
# their 95s budget and fail (4/12 of a 12-track album did, 2026-10-22).
|
||||
SEARCH_CONCURRENCY = 1
|
||||
|
||||
# Searching one track at a time, a big batch can outlast the Cloud Run Job's
|
||||
# 3600s task timeout, which would strand the rest with bulk_pending_search set.
|
||||
# Past this many seconds, remaining jobs are parked for a manual pick instead.
|
||||
BATCH_SEARCH_DEADLINE_SECONDS = 3000
|
||||
|
||||
|
||||
def _prepare_theme(job, job_manager: JobManager) -> None:
|
||||
@@ -131,61 +143,40 @@ async def _auto_select(job, selection_index: int, selected: dict,
|
||||
return await get_worker_service().trigger_audio_download_worker(job_id)
|
||||
|
||||
|
||||
async def process_job(job_id: str, job_manager: JobManager, audio_search_service) -> None:
|
||||
"""Search one batch job and either auto-select or park it."""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.warning("[bulk] job %s not found", job_id)
|
||||
return
|
||||
|
||||
artist = job.audio_search_artist or job.artist
|
||||
title = job.audio_search_title or job.title
|
||||
sd = job.state_data or {}
|
||||
bulk_settings = sd.get("bulk_settings", {}) or {}
|
||||
auto_enabled = bulk_settings.get("auto_select_if_lossless", True)
|
||||
|
||||
def _begin_search(job, job_manager: JobManager, message: str) -> None:
|
||||
"""Theme prep + move the job to SEARCHING_AUDIO."""
|
||||
_prepare_theme(job, job_manager)
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
job_id=job.job_id,
|
||||
new_status=JobStatus.SEARCHING_AUDIO,
|
||||
progress=5,
|
||||
message=f"Searching for: {artist} - {title}",
|
||||
message=message,
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
|
||||
try:
|
||||
results = await audio_search_service.search_async(artist, title)
|
||||
except (NoResultsError, AudioSearchError) as e:
|
||||
logger.warning("[bulk] search failed for job %s (%s); parking", job_id, e)
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message="No automatic audio sources found. Please choose a source.",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
|
||||
return
|
||||
|
||||
results_dicts = [r.to_dict() for r in results]
|
||||
store = {"state_data.audio_search_results": results_dicts}
|
||||
remote_id = getattr(audio_search_service, "last_remote_search_id", None)
|
||||
if remote_id:
|
||||
store["state_data.remote_search_id"] = remote_id
|
||||
def _park(job_id: str, job_manager: JobManager, message: str) -> None:
|
||||
"""Leave the job for human selection (the batch review queue)."""
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message=message,
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
|
||||
|
||||
|
||||
async def _finish_with_results(
|
||||
job, results_dicts: list, selection_index, job_manager: JobManager, extra_state: dict | None = None
|
||||
) -> None:
|
||||
"""Store a job's search results, then auto-select ``selection_index`` or park it."""
|
||||
job_id = job.job_id
|
||||
store = {"state_data.audio_search_results": results_dicts, **(extra_state or {})}
|
||||
job_manager.update_job(job_id, store)
|
||||
|
||||
selection_index = pick_auto_selection(results_dicts, title) if auto_enabled else None
|
||||
|
||||
if selection_index is None:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message=f"Found {len(results_dicts)} sources. Please choose one.",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
|
||||
_park(job_id, job_manager, f"Found {len(results_dicts)} sources. Please choose one.")
|
||||
return
|
||||
|
||||
auto_ok = await _auto_select(job, selection_index, results_dicts[selection_index], job_manager)
|
||||
@@ -203,18 +194,179 @@ async def process_job(job_id: str, job_manager: JobManager, audio_search_service
|
||||
)
|
||||
|
||||
|
||||
def _search_terms(job) -> tuple[str, str]:
|
||||
return (job.audio_search_artist or job.artist, job.audio_search_title or job.title)
|
||||
|
||||
|
||||
def _auto_enabled(job) -> bool:
|
||||
bulk_settings = (job.state_data or {}).get("bulk_settings", {}) or {}
|
||||
return bulk_settings.get("auto_select_if_lossless", True)
|
||||
|
||||
|
||||
async def process_job(job_id: str, job_manager: JobManager, audio_search_service) -> None:
|
||||
"""Search one batch job on its own (per-track) and either auto-select or park it."""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.warning("[bulk] job %s not found", job_id)
|
||||
return
|
||||
|
||||
artist, title = _search_terms(job)
|
||||
_begin_search(job, job_manager, f"Searching for: {artist} - {title}")
|
||||
|
||||
try:
|
||||
results = await audio_search_service.search_async(artist, title)
|
||||
except (NoResultsError, AudioSearchError) as e:
|
||||
logger.warning("[bulk] search failed for job %s (%s); parking", job_id, e)
|
||||
_park(job_id, job_manager, "No automatic audio sources found. Please choose a source.")
|
||||
return
|
||||
|
||||
results_dicts = [r.to_dict() for r in results]
|
||||
extra = {}
|
||||
remote_id = getattr(audio_search_service, "last_remote_search_id", None)
|
||||
if remote_id:
|
||||
extra["state_data.remote_search_id"] = remote_id
|
||||
|
||||
selection_index = pick_auto_selection(results_dicts, title, artist) if _auto_enabled(job) else None
|
||||
await _finish_with_results(job, results_dicts, selection_index, job_manager, extra)
|
||||
|
||||
|
||||
def _album_search_client():
|
||||
"""flacfetch client for album search (the fake one on the local stack), or None."""
|
||||
from backend.config import get_settings
|
||||
from backend.services.fake_workers import fake_workers_enabled
|
||||
|
||||
if fake_workers_enabled(get_settings()):
|
||||
from backend.services.fake_workers.search import FakeAlbumSearchClient
|
||||
|
||||
return FakeAlbumSearchClient()
|
||||
from backend.services.flacfetch_client import get_flacfetch_client
|
||||
|
||||
return get_flacfetch_client()
|
||||
|
||||
|
||||
async def process_album_jobs(album: dict, jobs: list, job_manager: JobManager) -> list:
|
||||
"""Resolve an album batch with ONE flacfetch album search.
|
||||
|
||||
Every job whose track the album's torrents cover gets those torrents as its
|
||||
search results, with the batch torrent (one torrent for the whole album) first
|
||||
and auto-selected when it's a confident pick. Returns the jobs that still need
|
||||
a per-track search: tracks no torrent covers, or every job when album search
|
||||
is unavailable or fails.
|
||||
"""
|
||||
from backend.services.bulk_album_search import (
|
||||
build_track_results,
|
||||
choose_batch_torrent,
|
||||
pick_album_auto_selection,
|
||||
)
|
||||
from backend.services.flacfetch_client import FlacfetchServiceError
|
||||
|
||||
client = _album_search_client()
|
||||
if client is None:
|
||||
return jobs
|
||||
|
||||
tracks = []
|
||||
for job in jobs:
|
||||
_artist, title = _search_terms(job)
|
||||
tracks.append({
|
||||
"key": job.job_id,
|
||||
"title": title,
|
||||
"position": (job.state_data or {}).get("bulk_track_position"),
|
||||
})
|
||||
|
||||
try:
|
||||
response = await client.search_album(album["artist"], album["title"], tracks)
|
||||
except FlacfetchServiceError as e:
|
||||
logger.warning("[bulk] album search failed for %s - %s (%s); searching per track",
|
||||
album["artist"], album["title"], e)
|
||||
return jobs
|
||||
|
||||
torrents = response.get("results") or []
|
||||
batch_torrent = choose_batch_torrent(torrents)
|
||||
logger.info(
|
||||
"[bulk] album search %s - %s: %d torrents; batch torrent %s",
|
||||
album["artist"], album["title"], len(torrents),
|
||||
f"{batch_torrent.get('provider')} {batch_torrent.get('source_id')} "
|
||||
f"({batch_torrent.get('matched_count')}/{len(tracks)} tracks)" if batch_torrent else "none",
|
||||
)
|
||||
|
||||
fallback = []
|
||||
for job in jobs:
|
||||
results = build_track_results(torrents, job.job_id, batch_torrent)
|
||||
if not results:
|
||||
fallback.append(job)
|
||||
continue
|
||||
try:
|
||||
artist, title = _search_terms(job)
|
||||
_begin_search(job, job_manager, f"Matching {title} on {album['title']}")
|
||||
selection_index = (
|
||||
pick_album_auto_selection(results, batch_torrent, title, artist)
|
||||
if _auto_enabled(job) else None
|
||||
)
|
||||
await _finish_with_results(job, results, selection_index, job_manager)
|
||||
except Exception as e: # noqa: BLE001 (one job must not kill the batch)
|
||||
logger.error("[bulk] album job %s crashed: %s", job.job_id, e, exc_info=True)
|
||||
try:
|
||||
_park_after_crash(job.job_id, job_manager)
|
||||
except BatchParkingError:
|
||||
fallback.append(job) # still pending: try it per track
|
||||
return fallback
|
||||
|
||||
|
||||
class BatchParkingError(RuntimeError):
|
||||
"""A job couldn't be parked after a crash: it's still pending, so the batch
|
||||
task must fail and let Cloud Run retry it (the retry only sees pending jobs)."""
|
||||
|
||||
|
||||
def _park_after_crash(
|
||||
job_id: str, job_manager: JobManager, message: str = "Search error. Please choose a source."
|
||||
) -> None:
|
||||
"""Park a job that can't be searched. Raises BatchParkingError if even that
|
||||
fails, so the caller can fail the batch instead of stranding the job."""
|
||||
try:
|
||||
_park(job_id, job_manager, message)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error("[bulk] could not park job %s: %s", job_id, e, exc_info=True)
|
||||
raise BatchParkingError(job_id) from e
|
||||
|
||||
|
||||
async def process_batch(batch_id: str) -> int:
|
||||
"""Process all pending-search jobs in a batch. Returns the count processed."""
|
||||
"""Process all pending-search jobs in a batch. Returns the count processed.
|
||||
|
||||
Album-mode jobs (``state_data.bulk_album``) share one album search per album;
|
||||
everything else, and album tracks it didn't cover, is searched per track,
|
||||
one at a time (SEARCH_CONCURRENCY).
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
|
||||
jobs = job_manager.list_jobs_by_batch_id(batch_id)
|
||||
pending = [j for j in jobs if (j.state_data or {}).get("bulk_pending_search")]
|
||||
logger.info("[batch:%s] processing %d/%d jobs needing search", batch_id, len(pending), len(jobs))
|
||||
|
||||
per_track = []
|
||||
albums: dict = {}
|
||||
for job in pending:
|
||||
album = (job.state_data or {}).get("bulk_album")
|
||||
if album and album.get("artist") and album.get("title"):
|
||||
albums.setdefault((album["artist"], album["title"]), (album, []))[1].append(job)
|
||||
else:
|
||||
per_track.append(job)
|
||||
|
||||
for album, album_jobs in albums.values():
|
||||
try:
|
||||
per_track.extend(await process_album_jobs(album, album_jobs, job_manager))
|
||||
except Exception as e: # noqa: BLE001 (fall back rather than strand the album's jobs)
|
||||
logger.error("[batch:%s] album path crashed: %s; searching per track", batch_id, e, exc_info=True)
|
||||
per_track.extend(j for j in album_jobs if _still_pending(j.job_id, job_manager))
|
||||
|
||||
sem = asyncio.Semaphore(SEARCH_CONCURRENCY)
|
||||
deadline = time.monotonic() + BATCH_SEARCH_DEADLINE_SECONDS
|
||||
|
||||
async def _guarded(job_id: str) -> None:
|
||||
async with sem:
|
||||
if time.monotonic() > deadline:
|
||||
logger.warning("[batch:%s] search deadline passed; parking %s for selection", batch_id, job_id)
|
||||
_park_after_crash(job_id, job_manager, "Please choose an audio source.")
|
||||
return
|
||||
# Fresh service per task: last_remote_search_id is instance state and
|
||||
# would be cross-contaminated if shared across concurrent searches.
|
||||
audio_search_service = AudioSearchService()
|
||||
@@ -222,22 +374,22 @@ async def process_batch(batch_id: str) -> int:
|
||||
await process_job(job_id, job_manager, audio_search_service)
|
||||
except Exception as e: # noqa: BLE001 (one job must not kill the batch)
|
||||
logger.error("[batch:%s] job %s crashed: %s", batch_id, job_id, e, exc_info=True)
|
||||
try:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message="Search error. Please choose a source.",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
job_manager.update_job(job_id, {"state_data.bulk_pending_search": False})
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
_park_after_crash(job_id, job_manager)
|
||||
|
||||
await asyncio.gather(*[_guarded(j.job_id) for j in pending])
|
||||
# Every job gets its turn; a job that couldn't even be parked fails the batch
|
||||
# afterwards so Cloud Run retries it (max_retries) instead of stranding it.
|
||||
outcomes = await asyncio.gather(*[_guarded(j.job_id) for j in per_track], return_exceptions=True)
|
||||
stranded = [o for o in outcomes if isinstance(o, BaseException)]
|
||||
if stranded:
|
||||
raise BatchParkingError(f"{len(stranded)} job(s) could not be parked: {stranded}")
|
||||
return len(pending)
|
||||
|
||||
|
||||
def _still_pending(job_id: str, job_manager: JobManager) -> bool:
|
||||
job = job_manager.get_job(job_id)
|
||||
return bool(job and (job.state_data or {}).get("bulk_pending_search"))
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
@@ -474,7 +474,7 @@ async def _search_and_start(job_id: str, artist: str, title: str) -> bool:
|
||||
store["state_data.remote_search_id"] = remote_id
|
||||
job_manager.update_job(job_id, store)
|
||||
|
||||
best_index = pick_auto_selection(results_dicts, search_title=title)
|
||||
best_index = pick_auto_selection(results_dicts, search_title=title, search_artist=artist)
|
||||
if best_index is None:
|
||||
logger.info("karaokehunt: no confident auto-pick for job %s; parking", job_id)
|
||||
return park("Please choose an audio source.")
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
"""
|
||||
Voice-pool separate-only GPU worker (Cloud Run Job ``voice-pool-separate-job``).
|
||||
|
||||
Reads a JSONL manifest (written by karaoke-decide) of original-audio objects in
|
||||
the gen bucket, separates the vocals stem with the ``instrumental_clean``
|
||||
ensemble preset and writes ``voice-pool/stems/<id>/vocals.flac`` plus per-task
|
||||
results. It touches no Firestore and no gen job state.
|
||||
|
||||
Manifest line: {"id": pool_id, "audio": "gs://<bucket>/voice-pool/audio/<id>/original.flac"}
|
||||
Results: <manifest without .jsonl>.results/part-<task_index>.jsonl, one line per
|
||||
song: {"id", "ok", "vocals", "seconds", "error"}
|
||||
|
||||
Cloud Run shards the manifest across tasks (CLOUD_RUN_TASK_INDEX / CLOUD_RUN_TASK_COUNT).
|
||||
|
||||
Usage: python -m backend.workers.voice_pool_separate_worker --manifest gs://.../<run>.jsonl
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
INSTRUMENTAL_PRESET = "instrumental_clean"
|
||||
STEMS_PREFIX = "voice-pool/stems"
|
||||
RESULTS_FLUSH_EVERY = 10
|
||||
|
||||
|
||||
class SystemicTaskError(RuntimeError):
|
||||
"""Failure that affects every song: the task fails fast with one ERROR."""
|
||||
|
||||
|
||||
class SeparatorLoadError(SystemicTaskError):
|
||||
"""Model load failed: systemic, so the task fails fast instead of retrying per song."""
|
||||
|
||||
|
||||
class WrongBucketError(ValueError):
|
||||
"""A gs:// URI points outside the gen bucket."""
|
||||
|
||||
|
||||
def shard(lines: List[dict], index: int, count: int) -> List[dict]:
|
||||
"""Lines owned by task ``index`` of ``count`` (round-robin over manifest order)."""
|
||||
return [line for i, line in enumerate(lines) if i % count == index]
|
||||
|
||||
|
||||
def vocals_path_from_outputs(paths: List[str]) -> Optional[str]:
|
||||
"""Pick the vocals stem from ensemble outputs.
|
||||
|
||||
Filenames look like ``{base}_(Vocals)_preset_instrumental_clean.flac``; match the
|
||||
stem tag, never the preset name (which itself contains "instrumental").
|
||||
"""
|
||||
for p in paths:
|
||||
if "_(vocals)_" in os.path.basename(p).lower():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _blob_path(uri: str, bucket: Optional[str] = None) -> str:
|
||||
"""``gs://bucket/path`` -> ``path`` (StorageService is bound to the gen bucket).
|
||||
|
||||
Raises WrongBucketError when ``bucket`` is given and the URI names another bucket.
|
||||
"""
|
||||
if uri.startswith("gs://"):
|
||||
uri_bucket, _, path = uri[5:].partition("/")
|
||||
if bucket is not None and uri_bucket != bucket:
|
||||
raise WrongBucketError("wrong_bucket")
|
||||
return path
|
||||
return uri
|
||||
|
||||
|
||||
def _results_path(manifest_uri: str, index: int) -> str:
|
||||
base = _blob_path(manifest_uri)
|
||||
if base.endswith(".jsonl"):
|
||||
base = base[: -len(".jsonl")]
|
||||
return f"{base}.results/part-{index}.jsonl"
|
||||
|
||||
|
||||
def _write_results(storage, manifest_uri: str, index: int, results: List[dict]) -> None:
|
||||
body = "".join(json.dumps(r) + "\n" for r in results)
|
||||
storage.upload_text(_results_path(manifest_uri, index), body, content_type="application/x-ndjson")
|
||||
|
||||
|
||||
def _read_manifest(storage, manifest_uri: str, bucket: Optional[str] = None) -> List[dict]:
|
||||
raw = storage.download_bytes(_blob_path(manifest_uri, bucket)).decode("utf-8")
|
||||
return [json.loads(line) for line in raw.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def run_manifest(
|
||||
storage,
|
||||
separator_factory: Callable[[], Any],
|
||||
manifest_uri: str,
|
||||
index: int,
|
||||
count: int,
|
||||
bucket: Optional[str] = None,
|
||||
) -> List[dict]:
|
||||
"""Separate this task's share of the manifest; never aborts on a per-song failure."""
|
||||
if bucket is None:
|
||||
from backend.config import get_settings
|
||||
|
||||
bucket = get_settings().gcs_bucket_name
|
||||
try:
|
||||
manifest = _read_manifest(storage, manifest_uri, bucket)
|
||||
except WrongBucketError:
|
||||
raise SystemicTaskError(f"manifest bucket is not {bucket} (wrong_bucket)")
|
||||
lines = shard(manifest, index, count)
|
||||
logger.info(f"Task {index}/{count}: {len(lines)} songs")
|
||||
results: List[dict] = []
|
||||
separator = None # built lazily so an all-skipped shard never loads models
|
||||
|
||||
for n, line in enumerate(lines, 1):
|
||||
pool_id = line.get("id")
|
||||
vocals_blob = f"{STEMS_PREFIX}/{pool_id}/vocals.flac"
|
||||
started = time.time()
|
||||
tmp = tempfile.mkdtemp(prefix="voicepool_")
|
||||
try:
|
||||
if storage.file_exists(vocals_blob):
|
||||
results.append({"id": pool_id, "ok": True, "vocals": vocals_blob, "seconds": 0, "error": None})
|
||||
continue
|
||||
if separator is None:
|
||||
try:
|
||||
separator = separator_factory()
|
||||
except Exception as e:
|
||||
raise SeparatorLoadError(f"separator failed to load: {e}") from e
|
||||
local = os.path.join(tmp, "original.flac")
|
||||
storage.download_file(_blob_path(line["audio"], bucket), local)
|
||||
outputs = separator.separate(local)
|
||||
# Separator may return bare filenames relative to its output_dir
|
||||
out_dir = getattr(separator, "output_dir", None)
|
||||
outputs = [o if os.path.isabs(o) or not out_dir else os.path.join(out_dir, o) for o in outputs]
|
||||
vocals = vocals_path_from_outputs(outputs)
|
||||
if not vocals or not os.path.exists(vocals):
|
||||
raise RuntimeError(f"no vocals stem in separator outputs: {[os.path.basename(o) for o in outputs]}")
|
||||
storage.upload_file(vocals, vocals_blob)
|
||||
for o in outputs: # all stems live in the shared output dir; free it per song
|
||||
try:
|
||||
os.remove(o)
|
||||
except OSError:
|
||||
pass
|
||||
results.append({
|
||||
"id": pool_id, "ok": True, "vocals": vocals_blob,
|
||||
"seconds": round(time.time() - started, 1), "error": None,
|
||||
})
|
||||
except SystemicTaskError:
|
||||
_write_results(storage, manifest_uri, index, results)
|
||||
raise
|
||||
except Exception as e: # per-song failure must not abort the task
|
||||
logger.warning(f"voice-pool separate failed for {pool_id}: {e}")
|
||||
results.append({
|
||||
"id": pool_id, "ok": False, "vocals": None,
|
||||
"seconds": round(time.time() - started, 1), "error": str(e)[:500],
|
||||
})
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
if n % RESULTS_FLUSH_EVERY == 0:
|
||||
try: # periodic flush is best-effort; the final write stays strict
|
||||
_write_results(storage, manifest_uri, index, results)
|
||||
except Exception as e:
|
||||
logger.warning(f"periodic results flush failed (will retry): {e}")
|
||||
|
||||
_write_results(storage, manifest_uri, index, results)
|
||||
return results
|
||||
|
||||
|
||||
def make_separator_factory(output_dir: str) -> Callable[[], Any]:
|
||||
def factory():
|
||||
from audio_separator.separator import Separator
|
||||
|
||||
from karaoke_gen.audio_processor import _separator_kwargs
|
||||
|
||||
separator = Separator(
|
||||
model_file_dir=os.environ["MODEL_DIR"],
|
||||
output_format="FLAC",
|
||||
output_dir=output_dir,
|
||||
ensemble_preset=INSTRUMENTAL_PRESET,
|
||||
**_separator_kwargs(),
|
||||
)
|
||||
separator.load_model()
|
||||
return separator
|
||||
|
||||
return factory
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--manifest", required=True, help="gs://bucket/voice-pool/manifests/<run>.jsonl")
|
||||
args = parser.parse_args(argv)
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
|
||||
index = int(os.environ.get("CLOUD_RUN_TASK_INDEX", "0"))
|
||||
count = int(os.environ.get("CLOUD_RUN_TASK_COUNT", "1"))
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
out_dir = tempfile.mkdtemp(prefix="voicepool_out_")
|
||||
try:
|
||||
results = run_manifest(StorageService(), make_separator_factory(out_dir), args.manifest, index, count)
|
||||
except SystemicTaskError as e:
|
||||
# task-independent text so every failing task groups as one alert pattern
|
||||
logger.info(f"Task {index}/{count} aborting")
|
||||
logger.error(f"voice-pool separate task aborted: {e}", extra={"task_index": index})
|
||||
return 1
|
||||
finally:
|
||||
shutil.rmtree(out_dir, ignore_errors=True)
|
||||
failed = sum(1 for r in results if not r["ok"])
|
||||
if results and failed == len(results):
|
||||
logger.info(f"Task {index}/{count}: all {failed} songs failed")
|
||||
logger.error(
|
||||
f"voice-pool separate task failed: every song failed (first error: {results[0]['error']})",
|
||||
extra={"task_index": index, "failed": failed},
|
||||
)
|
||||
return 1
|
||||
logger.info(f"Task {index}/{count} done: {len(results) - failed} ok, {failed} failed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+70
-3
@@ -1821,6 +1821,8 @@ Authorization: Bearer SESSION_TOKEN
|
||||
|
||||
Response includes `feedback_eligible: bool` indicating whether the user can earn credits by submitting feedback (requires 2+ completed jobs and no prior feedback submission).
|
||||
|
||||
Mobile-app fields: `app_user_id` (stable RevenueCat app user id; links IAP purchases to the account), `capabilities.account_deletion` (true only when `ACCOUNT_DELETION_ENABLED` is set), and `push_prefs` (`{ready, review, problems}` booleans, default all true).
|
||||
|
||||
### Logout
|
||||
|
||||
```http
|
||||
@@ -1837,6 +1839,70 @@ Authorization: Bearer SESSION_TOKEN
|
||||
|
||||
Grants the standard one-time welcome credit to a signed-in user (idempotent — once per account, with the usual abuse evaluation). Powers the voting board's "Make it yourself now" conversion: board sign-in grants no credit, so this claims it before sending the user into the generator. Returns `{status, credits, credits_granted}`.
|
||||
|
||||
## Mobile App Endpoints
|
||||
|
||||
### Push Preferences
|
||||
|
||||
```http
|
||||
PATCH /api/users/me/push-prefs
|
||||
Authorization: Bearer SESSION_TOKEN
|
||||
{"ready": true, "review": false, "problems": true} # any subset
|
||||
```
|
||||
|
||||
Returns the merged `{ready, review, problems}`. Read the current values from `push_prefs` on `GET /api/users/me`. Both Expo and Web Push honour them.
|
||||
|
||||
### Expo Push Token
|
||||
|
||||
```http
|
||||
POST /api/push/expo-token {"token": "ExponentPushToken[...]", "platform": "ios|android", "device_id": "..."} -> 204
|
||||
DELETE /api/push/expo-token {"token": "ExponentPushToken[...]"} -> 204
|
||||
```
|
||||
|
||||
Registers/removes the signed-in user's device for native push (sent via the Expo push service).
|
||||
|
||||
### Account Deletion (App Store 5.1.1(v) / Google Play)
|
||||
|
||||
All three return `404` unless `ACCOUNT_DELETION_ENABLED` is set (keep unset in prod until the app release ships).
|
||||
|
||||
```http
|
||||
GET /api/users/me/deletion-preview -> credits lost, videos cancelled; 409 {"code"} if deletion is refused
|
||||
DELETE /api/users/me {"apple_authorization_code": "..."} (body optional)
|
||||
```
|
||||
|
||||
`DELETE` cancels active jobs, erases decide and RevenueCat data, revokes Sign in with Apple (best-effort, when `apple_authorization_code` is given), deletes user-supplied inputs in GCS, revokes Dropbox share links (published outputs are kept), anonymises kept records and deletes the user doc. It returns `{"deleted": true, "summary": {...}}`. `409 {"code"}` = refused (`admin`, `referral_balance`, `connect_account`, `order_in_progress`), `503 {"step"}` = a step failed; safe to retry. Deletions are queued for kjbox to erase its copy (below). The web equivalent is the `/account/delete` page.
|
||||
|
||||
### RevenueCat Webhook
|
||||
|
||||
```http
|
||||
POST /api/users/webhooks/revenuecat
|
||||
Authorization: <REVENUECAT_WEBHOOK_AUTH value>
|
||||
```
|
||||
|
||||
Credits in-app credit-pack purchases (and reverses refunds). `503` while `REVENUECAT_WEBHOOK_AUTH` is unset, `401` on mismatch, `400` on malformed body. Handled outcomes (including duplicates and unmatched users) return 200; a Firestore failure returns 5xx so RevenueCat retries. Code: `backend/services/iap_service.py`.
|
||||
|
||||
### kjbox Account Deletions (partner, `X-Kjbox-Secret`)
|
||||
|
||||
```http
|
||||
GET /api/kjbox/account-deletions?since=ISO8601 -> {"deletions": [{id, email_hash, created_at}]}
|
||||
POST /api/kjbox/account-deletions/{id}/ack -> 204 (404 if unknown)
|
||||
```
|
||||
|
||||
kjbox pulls pending deletions (only the sha256 of the email), erases matching data, then acks.
|
||||
|
||||
### Test-Support Routes (local E2E stack only)
|
||||
|
||||
Mounted only when fake workers are enabled (never in production): `POST /api/test/fake-iap/purchase` and `/refund` simulate RevenueCat events (`product_id`, `email` or `app_user_id`, optional `transaction_id`); `GET`/`DELETE /api/test/push-outbox?to=` inspect/clear captured pushes.
|
||||
|
||||
### Mobile App Config (env)
|
||||
|
||||
| Env | Purpose |
|
||||
|-----|---------|
|
||||
| `REVENUECAT_WEBHOOK_AUTH` / `REVENUECAT_SECRET_API_KEY` | Webhook auth header / RevenueCat REST key (Secret Manager `revenuecat-webhook-auth`, `revenuecat-secret-api-key`) |
|
||||
| `REVENUECAT_PROJECT_ID` | RevenueCat project for the v2 customer delete on account deletion (default `9ea947ce`) |
|
||||
| `ACCOUNT_DELETION_ENABLED` | Enables the account-deletion endpoints and `capabilities.account_deletion`; unset in prod until release |
|
||||
| `APP_REVIEW_DEMO_EMAIL` / `APP_REVIEW_DEMO_CODE` | App Review demo sign-in: that email accepts the fixed code (`app-review-demo-code`); leave `APP_REVIEW_DEMO_EMAIL` unset in prod except during review |
|
||||
| `APPLE_SIWA_KEY_P8` / `APPLE_SIWA_KEY_ID` | Sign in with Apple key, used to revoke tokens on account deletion (not yet provisioned) |
|
||||
|
||||
## Requests Voting Board
|
||||
|
||||
Public Hacker-News-style board (served at `requests.nomadkaraoke.com`) where anyone signed in with an email magic link can submit a song request and cast **one vote per calendar day**. Phase 1 = the board (below); Phase 2 = the daily automation (internal endpoints at the end of this section), built and deployed dark behind `COMMUNITY_DAILY_PICK_ENABLED`.
|
||||
@@ -3131,7 +3197,7 @@ Served entirely from our BigQuery MusicBrainz mirror (`karaoke_decide.mb_*`, reb
|
||||
official dumps by karaoke-decide's `mb-refresh`); the live MusicBrainz API is never called. `404` = release not in the mirror; `502`
|
||||
means the BigQuery lookup failed.
|
||||
|
||||
- `GET /api/bulk/album/artists?q=<name>` → `[{mbid,name,disambiguation,type,country}]`
|
||||
- `GET /api/bulk/album/artists?q=<name>` → `[{mbid,name,disambiguation,type,country,alias}]`. Matches the artist name **or any MusicBrainz alias**, accent- and script-insensitive (`maximo park` → Maxïmo Park, `hikaru utada` → 宇多田ヒカル, `宇多田` and `Мумий` work as typed). `alias` is set when only an alias matched. Ranked exact → prefix → substring, name before alias, then popularity. Reads `karaoke_decide.mb_artists_normalized` + `musicbrainz.artist_alias` (~0.4 GB full scan, ~2 s; 10-min cache)
|
||||
- `GET /api/bulk/album/albums?artist_mbid=<mbid>` → `[{release_group_mbid,title,primary_type,secondary_types,first_release_date,is_studio}]` (studio albums first)
|
||||
- `GET /api/bulk/album/tracklist?artist=<name>&release_group_mbid=<mbid>` (or `&release_mbid=<mbid>` for a specific edition — also pass its album's `release_group_mbid` so the lookup stays cluster-pruned; optional `&locale=<code>` biases representative-pressing choice) → `{release_mbid,canonical_release_mbid,selected_variant_mbid,title,date,tracks:[{position,title,recording_mbid,length_ms,is_extra,extra_reason,available,brands,versions:[{brand,url}]}],editions:[{release_mbid,title,status,date,country,track_count}],variants:[{representative_release_mbid,label,track_count,year,pressing_count,delta_vs_original}]}`. `variants` collapses the release-group's country pressings into distinct tracklists grouped by track count (label `Original`/`Reissue`, `Original` = earliest); load one via its `representative_release_mbid` as `release_mbid`. Each track is enriched with KaraokeNerds community-version availability — `available`/`brands` plus `versions` (per-version `{brand,url}` YouTube links for clickable preview); enrichment is best-effort and never fatal.
|
||||
|
||||
@@ -3141,9 +3207,10 @@ means the BigQuery lookup failed.
|
||||
|
||||
### Submit
|
||||
|
||||
- `POST /api/bulk/submit` body `{songs:[{artist,title,display_artist?,display_title?}],settings:{auto_select_if_lossless,is_private,skip_audio_edit,skip_customization}}` → `{batch_id,job_ids,total}`.
|
||||
- `POST /api/bulk/submit` body `{songs:[{artist,title,display_artist?,display_title?,position?}],settings:{auto_select_if_lossless,is_private,skip_audio_edit,skip_customization},album?:{artist,title,release_group_mbid?,release_mbid?}}` → `{batch_id,job_ids,total}`. Album mode sends `album` + each track's `position`.
|
||||
- Credit gate: requires `credits >= len(songs)` (1/song minimum) before any job is created; admins bypass. Returns `402` with `{credits_available,credits_required}` if short (no jobs created). `422` for 0 or >100 songs.
|
||||
- Creates one parked job per song (`auto_download=False`), stamps `state_data.batch_id` + `bulk_settings`, and dispatches the `bulk-search-job` Cloud Run Job which runs each search and either auto-selects a confident lossless match or parks the job in `AWAITING_AUDIO_SELECTION`.
|
||||
- Creates one parked job per song (`auto_download=False`), stamps `state_data.batch_id` + `bulk_settings` (plus `bulk_album` + `bulk_track_position` for an album batch), and dispatches the `bulk-search-job` Cloud Run Job which runs the searches and either auto-selects a confident lossless match or parks the job in `AWAITING_AUDIO_SELECTION`.
|
||||
- Album batches make **one** flacfetch `POST /search/album` call: each track's file is resolved inside the album's torrents, the whole album is taken from one torrent (the first BEST CHOICE torrent, i.e. lossless, non-vinyl, ≥10 seeders), and each track is auto-selected when that torrent's file names it and the artist matches. Tracks no torrent covers, text batches, and album batches whose album search fails fall back to per-track search, **one search at a time** (flacfetch serializes searches on one worker; parallel requests only time out in its queue).
|
||||
|
||||
### Progress
|
||||
|
||||
|
||||
@@ -749,6 +749,16 @@ is still defined in Pulumi behind the `audioSeparatorServiceEnabled` flag — se
|
||||
[GCP-COST-OPTIMIZATION.md](GCP-COST-OPTIMIZATION.md#audio-separator-service-shut-down-on-demand-redeploy)
|
||||
to bring it back on demand.
|
||||
|
||||
### Voice-pool separate-only job
|
||||
|
||||
`voice-pool-separate-job` (Cloud Run Job, L4 GPU, us-east4, same GPU image) serves karaoke-decide's
|
||||
voice session. decide writes a JSONL manifest (`voice-pool/manifests/<run>.jsonl`, lines
|
||||
`{"id", "audio": "gs://…/voice-pool/audio/<id>/original.flac"}`) and starts the job with a per-run
|
||||
`task_count`. Each task (`CLOUD_RUN_TASK_INDEX`/`COUNT`, round-robin over manifest order) loads one
|
||||
`instrumental_clean` Separator, writes `voice-pool/stems/<id>/vocals.flac` (skipped if present) and
|
||||
`<manifest>.results/part-<task>.jsonl` (`{id, ok, vocals, seconds, error}`, flushed every 10 songs).
|
||||
No Firestore or gen job state. gen's Pulumi only creates the job; decide's Pulumi creates the `voice-pool` SA and grants it `roles/run.jobsExecutorWithOverrides` on it. The job has `parallelism=1` (decide cannot override it), so tasks run one after another and a pool run never uses more than one L4, leaving GPU capacity to customers' `audio-separation-job`. Task timeout is 3600s (Cloud Run's GPU maximum), so each task must finish in under 1h: decide chunks manifests accordingly and treats a timed-out execution as "re-run" (re-runs skip finished songs). URIs outside the gen bucket fail as `wrong_bucket`. A model-load failure or an all-songs-failed task exits non-zero with one ERROR. Code: `backend/workers/voice_pool_separate_worker.py`.
|
||||
|
||||
### Quick version (kjbox make-it jobs)
|
||||
|
||||
For jobs created by kjbox on behalf of a singer (`request_metadata.client_id` starts with
|
||||
|
||||
@@ -541,6 +541,28 @@ and `docs/archive/2026-07-20-edge-security-*.md`.
|
||||
test asserts the two values match. The bar also applies to unattended KaraokeHunt
|
||||
conversions (`karaokehunt_conversion.py` calls `pick_auto_selection`), where the
|
||||
title/filename check is the guard against wrong picks.
|
||||
- **Album batches search the album once (Oct 2026).** Searching each track separately made 12
|
||||
searches for a 12-track album. flacfetch runs searches on ONE worker
|
||||
(`flacfetch/api/routes/search.py` `_search_executor`), so 4 concurrent requests just queued
|
||||
there and the queued ones ran out their 95s budget (4/12 failed). A title-only file search
|
||||
also missed the album for a common title ("Time"). Now `bulk_search_worker` sends one
|
||||
flacfetch `/search/album` per album (`backend/services/bulk_album_search.py`) and runs any
|
||||
per-track fallback with `SEARCH_CONCURRENCY = 1`. Don't raise that without raising
|
||||
flacfetch's executor.
|
||||
- **Auto-pick checks the artist on the backend too** (`is_artist_match`, port of the frontend
|
||||
`isArtistMatch`, but Unicode-aware so CJK/Cyrillic names and "&"/"and" compare), so a
|
||||
10+-seeder cover or tribute torrent isn't auto-picked. Side effect: "Various Artists"
|
||||
compilation results no longer auto-pick on the per-track and KaraokeHunt paths; they park.
|
||||
- **Artist search must fold accents on BOTH sides (Oct 2026).** decide's `name_normalized`
|
||||
maps every char outside `[a-z0-9 ]` to a space, so "Maxïmo Park" is stored as `max mo park`
|
||||
and "maximo park" never matched; ~179k artists (Cyrillic, CJK, …) normalize to `""` and
|
||||
were unfindable. `search_artists` now applies `SEARCH_KEY_SQL` (NFKD, drop marks, fold
|
||||
ø/ß/æ…, keep letters of any script) to the name, every `musicbrainz.artist_alias`, and the
|
||||
query, in BigQuery. Don't search `name_normalized` for user-typed names. decide's
|
||||
`/api/catalog/artists` has the same flaw ("bjork" doesn't find Björk).
|
||||
- **Bulk batches have a search deadline** (`BATCH_SEARCH_DEADLINE_SECONDS`, 3000s): with one
|
||||
search at a time a 100-song text batch could outlast the 3600s Cloud Run Job, so jobs
|
||||
still waiting at the deadline are parked for a manual pick instead of stranded.
|
||||
- **Album cover thumbnails** in the By-album picker load straight from the Cover Art
|
||||
Archive in the browser (`coverartarchive.org/release-group/{mbid}/front-250`), with the
|
||||
disc icon as fallback when there's no cover. This isn't the live MusicBrainz API, and no
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*
|
||||
* Web account deletion page (Google Play web deletion path).
|
||||
*/
|
||||
import React from 'react'
|
||||
import { act, render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import { DeleteAccountClient } from '@/app/[locale]/account/delete/client'
|
||||
|
||||
const mockNotFound = jest.fn()
|
||||
jest.mock('next/navigation', () => ({
|
||||
notFound: () => mockNotFound(),
|
||||
useRouter: () => ({ push: jest.fn(), replace: jest.fn() }),
|
||||
}))
|
||||
jest.mock('@/components/app-header', () => ({ AppHeader: () => null }))
|
||||
jest.mock('@/components/auth/AuthDialog', () => ({ AuthDialog: () => null }))
|
||||
|
||||
const mockLogout = jest.fn().mockResolvedValue(undefined)
|
||||
jest.mock('@/lib/auth', () => ({
|
||||
useAuth: { getState: () => ({ logout: mockLogout }) },
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/api', () => ({
|
||||
getAccessToken: jest.fn(),
|
||||
api: {
|
||||
getCurrentUser: jest.fn(),
|
||||
getDeletionPreview: jest.fn(),
|
||||
deleteAccount: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { api, getAccessToken } from '@/lib/api'
|
||||
|
||||
const getCurrentUser = api.getCurrentUser as jest.Mock
|
||||
const getDeletionPreview = api.getDeletionPreview as jest.Mock
|
||||
const deleteAccount = api.deleteAccount as jest.Mock
|
||||
|
||||
const apiError = (status: number, data?: unknown) => Object.assign(new Error('x'), { status, data })
|
||||
|
||||
async function startDeletion() {
|
||||
await screen.findByTestId('delete-account-start')
|
||||
fireEvent.click(screen.getByTestId('delete-account-start'))
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByTestId('delete-account-confirm'))
|
||||
})
|
||||
}
|
||||
|
||||
describe('DeleteAccountClient', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
;(getAccessToken as jest.Mock).mockReturnValue('tok')
|
||||
getCurrentUser.mockResolvedValue({ user: {}, has_session: true, capabilities: { account_deletion: true } })
|
||||
getDeletionPreview.mockResolvedValue({ credits: 3, jobs_in_progress: 2, blocked: null })
|
||||
})
|
||||
|
||||
it('renders preview counts and the kept/deleted copy', async () => {
|
||||
render(<DeleteAccountClient />)
|
||||
expect(await screen.findByTestId('delete-account-credits')).toHaveTextContent('3 credits will be lost')
|
||||
expect(screen.getByTestId('delete-account-jobs')).toHaveTextContent('2 videos in progress will be cancelled')
|
||||
expect(screen.getByText(/kept for accounting/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/published on YouTube/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/song-discovery service/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Nomad night links/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('confirm calls DELETE, signs out and shows the deleted state', async () => {
|
||||
deleteAccount.mockResolvedValue({ deleted: true, summary: {} })
|
||||
render(<DeleteAccountClient />)
|
||||
await startDeletion()
|
||||
expect(await screen.findByTestId('delete-account-deleted')).toBeInTheDocument()
|
||||
expect(deleteAccount).toHaveBeenCalledTimes(1)
|
||||
expect(mockLogout).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not delete until the user confirms', async () => {
|
||||
render(<DeleteAccountClient />)
|
||||
fireEvent.click(await screen.findByTestId('delete-account-start'))
|
||||
expect(deleteAccount).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByTestId('delete-account-cancel'))
|
||||
expect(screen.getByTestId('delete-account-start')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('on 401 at confirm signs out and shows neutral copy (deleted, or just signed out)', async () => {
|
||||
deleteAccount.mockRejectedValue(apiError(401))
|
||||
render(<DeleteAccountClient />)
|
||||
await startDeletion()
|
||||
const msg = await screen.findByTestId('delete-account-signed-out-after-delete')
|
||||
expect(msg).toHaveTextContent(
|
||||
"You've been signed out. If you just deleted your account, it's gone. Otherwise sign in and try again.",
|
||||
)
|
||||
expect(screen.getByTestId('delete-account-sign-in')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('delete-account-deleted')).not.toBeInTheDocument()
|
||||
expect(mockLogout).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows generic support copy for an unknown 409 code without crashing', async () => {
|
||||
deleteAccount.mockRejectedValue(apiError(409, { code: 'brand_new_reason' }))
|
||||
render(<DeleteAccountClient />)
|
||||
await startDeletion()
|
||||
const blocked = await screen.findByTestId('delete-account-blocked')
|
||||
expect(blocked).toHaveTextContent(/cannot delete your account automatically/i)
|
||||
expect(blocked).toHaveTextContent('support@nomadkaraoke.com')
|
||||
expect(mockLogout).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows generic support copy for an unknown preview block code', async () => {
|
||||
getDeletionPreview.mockResolvedValue({ credits: 0, jobs_in_progress: 0, blocked: 'brand_new_reason' })
|
||||
render(<DeleteAccountClient />)
|
||||
const blocked = await screen.findByTestId('delete-account-blocked')
|
||||
expect(blocked).toHaveTextContent(/cannot delete your account automatically/i)
|
||||
})
|
||||
|
||||
it('shows support copy on 409', async () => {
|
||||
deleteAccount.mockRejectedValue(apiError(409, { code: 'referral_balance' }))
|
||||
render(<DeleteAccountClient />)
|
||||
await startDeletion()
|
||||
const blocked = await screen.findByTestId('delete-account-blocked')
|
||||
expect(blocked).toHaveTextContent('support@nomadkaraoke.com')
|
||||
expect(blocked).toHaveTextContent(/referral balance/i)
|
||||
expect(mockLogout).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows support copy when the preview is already blocked', async () => {
|
||||
getDeletionPreview.mockResolvedValue({ credits: 0, jobs_in_progress: 0, blocked: 'admin' })
|
||||
render(<DeleteAccountClient />)
|
||||
const blocked = await screen.findByTestId('delete-account-blocked')
|
||||
expect(blocked).toHaveTextContent('support@nomadkaraoke.com')
|
||||
expect(screen.queryByTestId('delete-account-start')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('offers retry on 503 and does not sign out', async () => {
|
||||
deleteAccount.mockRejectedValueOnce(apiError(503, { step: 'decide' }))
|
||||
render(<DeleteAccountClient />)
|
||||
await startDeletion()
|
||||
const retry = await screen.findByTestId('delete-account-retry')
|
||||
expect(screen.getByTestId('delete-account-error')).toHaveTextContent(
|
||||
'Something went wrong part-way. Please try again — deletion picks up where it left off.',
|
||||
)
|
||||
expect(screen.getByTestId('delete-account-error')).not.toHaveTextContent(/nothing was lost/i)
|
||||
expect(mockLogout).not.toHaveBeenCalled()
|
||||
deleteAccount.mockResolvedValue({ deleted: true })
|
||||
fireEvent.click(retry)
|
||||
await waitFor(() => expect(deleteAccount).toHaveBeenCalledTimes(2))
|
||||
expect(await screen.findByTestId('delete-account-deleted')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('is a 404 when the capability is false', async () => {
|
||||
getCurrentUser.mockResolvedValue({ user: {}, has_session: true, capabilities: { account_deletion: false } })
|
||||
render(<DeleteAccountClient />)
|
||||
await waitFor(() => expect(mockNotFound).toHaveBeenCalled())
|
||||
expect(getDeletionPreview).not.toHaveBeenCalled()
|
||||
expect(screen.queryByTestId('delete-account-start')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('asks signed-out visitors to sign in', async () => {
|
||||
;(getAccessToken as jest.Mock).mockReturnValue(null)
|
||||
render(<DeleteAccountClient />)
|
||||
expect(await screen.findByTestId('delete-account-signed-out')).toBeInTheDocument()
|
||||
expect(getCurrentUser).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -150,6 +150,22 @@ describe('BulkMode (album sub-mode)', () => {
|
||||
await waitFor(() => expect(screen.getByText('Batch settings')).toBeInTheDocument())
|
||||
expect(screen.getByRole('button', { name: 'Create 2 karaoke videos' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('submits the album and each track position so the backend searches the album once', async () => {
|
||||
mockApi.bulkSubmit.mockResolvedValue({ batch_id: 'b1', job_ids: ['j1', 'j2'], total: 2 } as any)
|
||||
render(<BulkMode />)
|
||||
await walkToTracklist()
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Create 2 karaoke videos' }))
|
||||
await waitFor(() => expect(mockApi.bulkSubmit).toHaveBeenCalled())
|
||||
|
||||
const payload = mockApi.bulkSubmit.mock.calls[0][0]
|
||||
expect(payload.album).toEqual({
|
||||
artist: 'Britney Spears', title: 'Oops!...I Did It Again', release_group_mbid: 'rg-1', release_mbid: null,
|
||||
})
|
||||
expect(payload.songs.map((s: any) => [s.title, s.position])).toEqual([
|
||||
['Oops!...I Did It Again', 1], ['Stronger', 2],
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('BulkAlbumMode cover art', () => {
|
||||
@@ -191,3 +207,60 @@ describe('BulkAlbumMode cover art', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('BulkAlbumMode artist search results', () => {
|
||||
async function search(q: string) {
|
||||
fireEvent.change(screen.getByPlaceholderText('Search for an artist…'), { target: { value: q } })
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Search$/ }))
|
||||
}
|
||||
|
||||
it('shows a no-results message (not a blank list) when nothing matches', async () => {
|
||||
mockApi.searchAlbumArtists.mockResolvedValue([] as any)
|
||||
render(<Harness />)
|
||||
await search('Zzyzx Nobody')
|
||||
const empty = await screen.findByTestId('bulk-artist-no-results')
|
||||
expect(empty).toHaveTextContent('No artists match “Zzyzx Nobody”.')
|
||||
// No switch button without a handler.
|
||||
expect(screen.queryByRole('button', { name: 'Add songs by name' })).toBeNull()
|
||||
})
|
||||
|
||||
it('hides the no-results message while a new search is loading and when results arrive', async () => {
|
||||
mockApi.searchAlbumArtists.mockResolvedValueOnce([] as any)
|
||||
render(<Harness />)
|
||||
await search('Nobody')
|
||||
await screen.findByTestId('bulk-artist-no-results')
|
||||
let resolve: (v: any) => void = () => {}
|
||||
mockApi.searchAlbumArtists.mockReturnValueOnce(new Promise((r) => { resolve = r }) as any)
|
||||
await search('Britney')
|
||||
expect(screen.queryByTestId('bulk-artist-no-results')).toBeNull()
|
||||
await act(async () => resolve([ARTIST]))
|
||||
expect(await screen.findByRole('button', { name: /Britney Spears/ })).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('bulk-artist-no-results')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not show the no-results message when the lookup fails', async () => {
|
||||
mockApi.searchAlbumArtists.mockRejectedValue(new Error('502'))
|
||||
render(<Harness />)
|
||||
await search('Britney')
|
||||
expect(await screen.findByText('Lookup failed. Please try again.')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('bulk-artist-no-results')).toBeNull()
|
||||
})
|
||||
|
||||
it('explains alias matches in the row subtitle', async () => {
|
||||
mockApi.searchAlbumArtists.mockResolvedValue([
|
||||
{ mbid: 'a-2', name: '宇多田ヒカル', disambiguation: 'Japanese-American singer-songwriter', alias: 'Hikaru Utada' },
|
||||
] as any)
|
||||
render(<Harness />)
|
||||
await search('hikaru utada')
|
||||
expect(await screen.findByText('Also known as Hikaru Utada · Japanese-American singer-songwriter')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('in BulkMode, the no-results state offers a switch to By text', async () => {
|
||||
mockApi.searchAlbumArtists.mockResolvedValue([] as any)
|
||||
localStorage.clear() // an earlier submit test remembers its batch, which opens batch progress
|
||||
render(<BulkMode />)
|
||||
await search('Zzyzx Nobody')
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Add songs by name' }))
|
||||
await waitFor(() => expect(screen.getByRole('tab', { name: /By text/ })).toHaveAttribute('data-state', 'active'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*
|
||||
* BulkBatchProgress when the remembered batch can't be loaded.
|
||||
* next-intl is globally mocked in jest.setup.js (real en strings).
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { api } from '@/lib/api'
|
||||
import { ApiError } from '@/lib/api-error'
|
||||
import { BulkBatchProgress } from '@/components/job/bulk/BulkBatchProgress'
|
||||
|
||||
jest.mock('@/lib/api', () => ({ api: { getBulkBatch: jest.fn() } }))
|
||||
jest.mock('@/components/audio-search/AudioSearchDialog', () => ({ AudioSearchDialog: () => null }))
|
||||
|
||||
const mockApi = api as jest.Mocked<typeof api>
|
||||
|
||||
beforeEach(() => jest.clearAllMocks())
|
||||
|
||||
describe('BulkBatchProgress', () => {
|
||||
it('returns to the form when the batch no longer exists (404)', async () => {
|
||||
mockApi.getBulkBatch.mockRejectedValue(new ApiError('Batch not found', 404, {}))
|
||||
const onStartAnother = jest.fn()
|
||||
render(<BulkBatchProgress batchId="gone" onStartAnother={onStartAnother} />)
|
||||
await waitFor(() => expect(onStartAnother).toHaveBeenCalled())
|
||||
expect(screen.queryByText("Couldn't load batch progress.")).toBeNull()
|
||||
})
|
||||
|
||||
it('other errors show the message with a way to start another batch', async () => {
|
||||
mockApi.getBulkBatch.mockRejectedValue(new ApiError('boom', 500, {}))
|
||||
const onStartAnother = jest.fn()
|
||||
render(<BulkBatchProgress batchId="b1" onStartAnother={onStartAnother} />)
|
||||
expect(await screen.findByText("Couldn't load batch progress.")).toBeInTheDocument()
|
||||
expect(onStartAnother).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Start another batch' }))
|
||||
expect(onStartAnother).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,259 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { Link } from '@/i18n/routing';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { AppHeader } from '@/components/app-header';
|
||||
import { AuthDialog } from '@/components/auth/AuthDialog';
|
||||
import { api, getAccessToken } from '@/lib/api';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import type { DeletionBlockedCode, DeletionPreview } from '@/lib/types';
|
||||
|
||||
const SUPPORT_EMAIL = 'support@nomadkaraoke.com';
|
||||
|
||||
type Phase =
|
||||
| { kind: 'loading' }
|
||||
| { kind: 'signedOut'; afterDelete?: boolean }
|
||||
| { kind: 'hidden' }
|
||||
| { kind: 'ready'; preview: DeletionPreview }
|
||||
| { kind: 'confirming'; preview: DeletionPreview }
|
||||
| { kind: 'deleting'; preview: DeletionPreview }
|
||||
| { kind: 'deleted' }
|
||||
| { kind: 'blocked'; code: DeletionBlockedCode | null }
|
||||
| { kind: 'error'; retryable: boolean; preview: DeletionPreview | null };
|
||||
|
||||
const BLOCKED_KEYS: Record<DeletionBlockedCode, string> = {
|
||||
admin: 'blockedAdmin',
|
||||
referral_balance: 'blockedReferralBalance',
|
||||
connect_account: 'blockedConnectAccount',
|
||||
order_in_progress: 'blockedOrderInProgress',
|
||||
};
|
||||
|
||||
function blockedCode(code: unknown): DeletionBlockedCode | null {
|
||||
// An unknown code (a newer backend) falls back to the generic support copy.
|
||||
return typeof code === 'string' && Object.prototype.hasOwnProperty.call(BLOCKED_KEYS, code)
|
||||
? (code as DeletionBlockedCode)
|
||||
: null;
|
||||
}
|
||||
|
||||
function statusOf(err: unknown): number | undefined {
|
||||
return err && typeof err === 'object' && 'status' in err ? (err as { status: number }).status : undefined;
|
||||
}
|
||||
|
||||
export function DeleteAccountClient() {
|
||||
const t = useTranslations('accountDelete');
|
||||
const [phase, setPhase] = useState<Phase>({ kind: 'loading' });
|
||||
const [showAuth, setShowAuth] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!getAccessToken()) {
|
||||
setPhase({ kind: 'signedOut' });
|
||||
return;
|
||||
}
|
||||
setPhase({ kind: 'loading' });
|
||||
try {
|
||||
const me = await api.getCurrentUser();
|
||||
if (me.capabilities?.account_deletion !== true) {
|
||||
setPhase({ kind: 'hidden' });
|
||||
return;
|
||||
}
|
||||
const preview = await api.getDeletionPreview();
|
||||
setPhase(preview.blocked ? { kind: 'blocked', code: blockedCode(preview.blocked) } : { kind: 'ready', preview });
|
||||
} catch (err) {
|
||||
const status = statusOf(err);
|
||||
if (status === 401) setPhase({ kind: 'signedOut' });
|
||||
else if (status === 404) setPhase({ kind: 'hidden' });
|
||||
else setPhase({ kind: 'error', retryable: false, preview: null });
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const finishDeleted = useCallback(async () => {
|
||||
// Same as sign-out: clears the stored session token and the auth store
|
||||
// (the logout call itself is best-effort and ignored if the session is gone).
|
||||
await useAuth.getState().logout();
|
||||
setPhase({ kind: 'deleted' });
|
||||
}, []);
|
||||
|
||||
const confirmDelete = useCallback(
|
||||
async (preview: DeletionPreview) => {
|
||||
setPhase({ kind: 'deleting', preview });
|
||||
try {
|
||||
await api.deleteAccount();
|
||||
await finishDeleted();
|
||||
} catch (err) {
|
||||
const status = statusOf(err);
|
||||
if (status === 401) {
|
||||
// The session is gone: either a retry after a lost 200 (deleted) or the
|
||||
// session simply expired. We can't tell, so sign out and say both.
|
||||
await useAuth.getState().logout();
|
||||
setPhase({ kind: 'signedOut', afterDelete: true });
|
||||
} else if (status === 409) {
|
||||
setPhase({ kind: 'blocked', code: blockedCode((err as { data?: { code?: unknown } }).data?.code) });
|
||||
} else {
|
||||
// 503 {step} is retryable; anything else (network, 5xx) is treated the same:
|
||||
// each backend step is idempotent, so a retry resumes the deletion.
|
||||
setPhase({ kind: 'error', retryable: true, preview });
|
||||
}
|
||||
}
|
||||
},
|
||||
[finishDeleted],
|
||||
);
|
||||
|
||||
if (phase.kind === 'hidden') {
|
||||
notFound();
|
||||
return null;
|
||||
}
|
||||
|
||||
const preview =
|
||||
phase.kind === 'ready' || phase.kind === 'confirming' || phase.kind === 'deleting'
|
||||
? phase.preview
|
||||
: phase.kind === 'error'
|
||||
? phase.preview
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen" style={{ backgroundColor: 'var(--background)' }}>
|
||||
<AppHeader />
|
||||
<main className="container mx-auto max-w-2xl px-4 pt-6 pb-12" data-testid="delete-account-page">
|
||||
<h1 className="text-2xl font-semibold mb-4" style={{ color: 'var(--text)' }}>
|
||||
{t('title')}
|
||||
</h1>
|
||||
|
||||
{phase.kind === 'loading' && (
|
||||
<div className="flex items-center gap-2" data-testid="delete-account-loading" style={{ color: 'var(--text-muted)' }}>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
{t('loading')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase.kind === 'signedOut' && (
|
||||
<div className="space-y-4" data-testid="delete-account-signed-out">
|
||||
<p data-testid={phase.afterDelete ? 'delete-account-signed-out-after-delete' : undefined}>
|
||||
{phase.afterDelete ? t('signedOutMaybeDeleted') : t('signInPrompt')}
|
||||
</p>
|
||||
<Button onClick={() => setShowAuth(true)} data-testid="delete-account-sign-in">
|
||||
{t('signInButton')}
|
||||
</Button>
|
||||
<AuthDialog
|
||||
open={showAuth}
|
||||
onClose={() => setShowAuth(false)}
|
||||
onSuccess={() => {
|
||||
setShowAuth(false);
|
||||
load();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase.kind === 'deleted' && (
|
||||
<div className="space-y-4" data-testid="delete-account-deleted">
|
||||
<h2 className="text-xl font-medium">{t('deletedTitle')}</h2>
|
||||
<p>{t('deletedBody')}</p>
|
||||
<Link href="/" className="underline" data-testid="delete-account-home">
|
||||
{t('backHome')}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase.kind === 'blocked' && (
|
||||
<div className="space-y-3" role="alert" data-testid="delete-account-blocked">
|
||||
{phase.code && <p>{t(BLOCKED_KEYS[phase.code])}</p>}
|
||||
<p>{t('blockedContact', { email: SUPPORT_EMAIL })}</p>
|
||||
<a href={`mailto:${SUPPORT_EMAIL}`} className="underline" data-testid="delete-account-support-link">
|
||||
{SUPPORT_EMAIL}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase.kind === 'error' && (
|
||||
<div className="space-y-3" role="alert" data-testid="delete-account-error">
|
||||
<p>{phase.retryable ? t('retryPartway') : t('genericError', { email: SUPPORT_EMAIL })}</p>
|
||||
<Button
|
||||
onClick={() => (phase.preview ? confirmDelete(phase.preview) : load())}
|
||||
data-testid="delete-account-retry"
|
||||
>
|
||||
{t('retryButton')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{preview && phase.kind !== 'error' && (
|
||||
<div className="space-y-6">
|
||||
<p>{t('intro')}</p>
|
||||
|
||||
<section>
|
||||
<h2 className="font-medium mb-2">{t('deletedHeading')}</h2>
|
||||
<ul className="list-disc pl-6 space-y-1">
|
||||
<li>{t('deletedPersonal')}</li>
|
||||
<li>{t('deletedUploads')}</li>
|
||||
<li>{t('deletedMusicData')}</li>
|
||||
<li>{t('deletedNightLinks')}</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 className="font-medium mb-2">{t('keptHeading')}</h2>
|
||||
<ul className="list-disc pl-6 space-y-1">
|
||||
<li>{t('keptRecords')}</li>
|
||||
<li>{t('keptYoutube')}</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{(preview.credits > 0 || preview.jobs_in_progress > 0) && (
|
||||
<ul className="space-y-1 font-medium" data-testid="delete-account-losses">
|
||||
{preview.credits > 0 && (
|
||||
<li data-testid="delete-account-credits">{t('creditsLost', { count: preview.credits })}</li>
|
||||
)}
|
||||
{preview.jobs_in_progress > 0 && (
|
||||
<li data-testid="delete-account-jobs">{t('jobsCancelled', { count: preview.jobs_in_progress })}</li>
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{phase.kind === 'ready' && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => setPhase({ kind: 'confirming', preview: phase.preview })}
|
||||
data-testid="delete-account-start"
|
||||
>
|
||||
{t('deleteButton')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{(phase.kind === 'confirming' || phase.kind === 'deleting') && (
|
||||
<div className="space-y-3 border rounded-md p-4" role="alertdialog" data-testid="delete-account-confirm-panel">
|
||||
<h2 className="font-medium">{t('confirmTitle')}</h2>
|
||||
<p>{t('confirmBody')}</p>
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={phase.kind === 'deleting'}
|
||||
onClick={() => confirmDelete(phase.preview)}
|
||||
data-testid="delete-account-confirm"
|
||||
>
|
||||
{phase.kind === 'deleting' ? t('deleting') : t('confirmButton')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={phase.kind === 'deleting'}
|
||||
onClick={() => setPhase({ kind: 'ready', preview: phase.preview })}
|
||||
data-testid="delete-account-cancel"
|
||||
>
|
||||
{t('cancelButton')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { DeleteAccountClient } from './client';
|
||||
|
||||
// Web account deletion (Google Play requires a web way to delete an account).
|
||||
// Mirrors the mobile app's flow. Shows a 404 when the backend flag is off.
|
||||
export default function DeleteAccountPage() {
|
||||
return <DeleteAccountClient />;
|
||||
}
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical, Gift, Tag, Palette, Music } from "lucide-react"
|
||||
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical, Gift, Tag, Palette, Music, Trash2 } from "lucide-react"
|
||||
import NextLink from "next/link"
|
||||
import { Link as LocaleLink } from "@/i18n/routing"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -206,6 +207,17 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
{user.account_deletion && (
|
||||
<>
|
||||
<DropdownMenuSeparator className="bg-border" />
|
||||
<DropdownMenuItem asChild className="text-muted-foreground focus:text-foreground focus:bg-secondary">
|
||||
<LocaleLink href="/account/delete" data-testid="delete-account-link">
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
<span>{t('deleteAccount')}</span>
|
||||
</LocaleLink>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuSeparator className="bg-border" />
|
||||
<DropdownMenuItem
|
||||
onClick={handleLogout}
|
||||
|
||||
@@ -17,6 +17,8 @@ import { BulkSongRow, newRow, shouldSelectTrack } from "./types"
|
||||
interface BulkAlbumModeProps {
|
||||
rows: BulkSongRow[]
|
||||
onChange: (rows: BulkSongRow[]) => void
|
||||
/** Switch Bulk Mode to "By song name" (offered when no artist matches). */
|
||||
onSwitchToText?: () => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
@@ -203,7 +205,7 @@ function PickRow({ icon: Icon, artMbid, title, subtitle, meta, onClick, disabled
|
||||
)
|
||||
}
|
||||
|
||||
export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps) {
|
||||
export function BulkAlbumMode({ rows, onChange, onSwitchToText, disabled }: BulkAlbumModeProps) {
|
||||
const t = useTranslations("bulk")
|
||||
const locale = useLocale()
|
||||
const [query, setQuery] = useState("")
|
||||
@@ -214,12 +216,17 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
// Release group of the loaded album; edition switches pass it so the backend's
|
||||
// mirror lookup stays pruned to this album.
|
||||
const [albumMbid, setAlbumMbid] = useState("")
|
||||
// Release-group title of the loaded album: what trackers name the album (the
|
||||
// tracklist's title comes from a locale-picked pressing and may be translated).
|
||||
const [albumTitle, setAlbumTitle] = useState("")
|
||||
// Distinct tracklist variants for the loaded album. Held separately from
|
||||
// `tracklist` because switching to a specific edition returns no variant list.
|
||||
const [variants, setVariants] = useState<BulkEditionVariant[]>([])
|
||||
const [showVariants, setShowVariants] = useState(false)
|
||||
const [loading, setLoading] = useState<"" | "artists" | "albums" | "tracks">("")
|
||||
const [error, setError] = useState("")
|
||||
// The query whose artist search last finished without error (drives the no-results state).
|
||||
const [searchedQuery, setSearchedQuery] = useState("")
|
||||
// Bumped on every lookup and on step navigation; a response whose id is no
|
||||
// longer current is stale (user moved on) and is dropped.
|
||||
const requestId = useRef(0)
|
||||
@@ -229,10 +236,10 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
async function searchArtists() {
|
||||
if (query.trim().length < 2) return
|
||||
const id = ++requestId.current
|
||||
setLoading("artists"); setError(""); setArtists([]); setArtist(null); setAlbums([]); setTracklist(null); resetVariants()
|
||||
setLoading("artists"); setError(""); setSearchedQuery(""); setArtists([]); setArtist(null); setAlbums([]); setTracklist(null); resetVariants()
|
||||
try {
|
||||
const found = await api.searchAlbumArtists(query.trim())
|
||||
if (id === requestId.current) setArtists(found)
|
||||
if (id === requestId.current) { setArtists(found); setSearchedQuery(query.trim()) }
|
||||
} catch {
|
||||
if (id === requestId.current) setError(t("lookupFailed"))
|
||||
} finally {
|
||||
@@ -254,7 +261,13 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
}
|
||||
}
|
||||
|
||||
function buildRows(tl: BulkTracklist): BulkSongRow[] {
|
||||
function buildRows(tl: BulkTracklist, releaseGroupMbid: string, releaseGroupTitle: string): BulkSongRow[] {
|
||||
const album = {
|
||||
artist: artist?.name || "",
|
||||
title: releaseGroupTitle || tl.title || "",
|
||||
release_group_mbid: releaseGroupMbid || null,
|
||||
release_mbid: tl.selected_variant_mbid || tl.release_mbid || tl.canonical_release_mbid || null,
|
||||
}
|
||||
return tl.tracks.map((tr) =>
|
||||
newRow({
|
||||
artist: artist?.name || "",
|
||||
@@ -267,6 +280,7 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
is_extra: tr.is_extra,
|
||||
length_ms: tr.length_ms,
|
||||
position: tr.position,
|
||||
album: album.title ? album : undefined,
|
||||
})
|
||||
)
|
||||
}
|
||||
@@ -275,6 +289,7 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
if (!artist?.name) return
|
||||
const id = ++requestId.current
|
||||
setLoading("tracks"); setError(""); resetVariants(); setAlbumMbid(album.release_group_mbid)
|
||||
setAlbumTitle(album.title)
|
||||
try {
|
||||
const tl = await api.getAlbumTracklist({
|
||||
artist: artist.name, releaseGroupMbid: album.release_group_mbid, locale,
|
||||
@@ -282,7 +297,7 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
if (id !== requestId.current) return
|
||||
setTracklist(tl)
|
||||
setVariants(tl.variants || [])
|
||||
onChange(buildRows(tl))
|
||||
onChange(buildRows(tl, album.release_group_mbid, album.title))
|
||||
} catch {
|
||||
if (id === requestId.current) setError(t("lookupFailed"))
|
||||
} finally {
|
||||
@@ -301,7 +316,7 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
})
|
||||
if (id !== requestId.current) return
|
||||
setTracklist(tl)
|
||||
onChange(buildRows(tl))
|
||||
onChange(buildRows(tl, albumMbid, albumTitle))
|
||||
} catch {
|
||||
if (id === requestId.current) setError(t("lookupFailed"))
|
||||
} finally {
|
||||
@@ -512,10 +527,25 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
onClick={() => pickArtist(a)}
|
||||
disabled={disabled || !a.mbid}
|
||||
title={a.name}
|
||||
subtitle={a.disambiguation}
|
||||
subtitle={[a.alias && t("artistAlsoKnownAs", { alias: a.alias }), a.disambiguation].filter(Boolean).join(" · ")}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{searchedQuery && artists.length === 0 && !loading && (
|
||||
<div
|
||||
className="rounded-md border border-dashed px-3 py-3 space-y-2"
|
||||
style={{ borderColor: "var(--card-border)" }}
|
||||
data-testid="bulk-artist-no-results"
|
||||
>
|
||||
<p className="text-sm" style={{ color: "var(--text)" }}>{t("noArtistsFound", { query: searchedQuery })}</p>
|
||||
<p className="text-xs" style={{ color: "var(--text-muted)" }}>{t("noArtistsFoundHint")}</p>
|
||||
{onSwitchToText && (
|
||||
<Button variant="outline" size="sm" onClick={onSwitchToText} disabled={disabled}>
|
||||
{t("noArtistsUseText")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{error && <p className="text-xs" style={{ color: "#ef4444" }}>{error}</p>}
|
||||
</div>
|
||||
)
|
||||
|
||||
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user