mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 18:08:07 +09:00
Compare commits
22
Commits
No files matched your search
+246
-3
@@ -1089,6 +1089,10 @@ jobs:
|
||||
id-token: write
|
||||
outputs:
|
||||
base_rebuilt: ${{ steps.check-base.outputs.needs_rebuild }}
|
||||
version: ${{ steps.version_check.outputs.version }}
|
||||
# R1: gates the post-deploy canary — "true" only when the backend version
|
||||
# actually changed (see "Detect backend version change" step).
|
||||
version_changed: ${{ steps.version_changed.outputs.changed }}
|
||||
env:
|
||||
REGISTRY: us-central1-docker.pkg.dev
|
||||
PROJECT_ID: nomadkaraoke
|
||||
@@ -1144,6 +1148,43 @@ jobs:
|
||||
echo "📋 Current version: $VERSION"
|
||||
echo "🚀 Deploying on every push to main"
|
||||
|
||||
# R1 gate — only run the post-deploy functional canary when the BACKEND
|
||||
# version actually changed. A frontend-/docs-/infra-only merge still runs
|
||||
# deploy-backend (image rebuild) but ships an identical version; a real
|
||||
# karaoke generation is slow + resource-heavy, so we short-circuit the
|
||||
# canary in that case. We compare the version we're about to ship against
|
||||
# the version currently served by production.
|
||||
- name: Detect backend version change
|
||||
id: version_changed
|
||||
run: |
|
||||
NEW_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
# Read the currently-serving version via the EDGE (api.nomadkaraoke.com),
|
||||
# NOT the raw Cloud Run origin URL, and retry. The single un-retried
|
||||
# origin probe returned empty on #987 (cold start on the scaled-to-zero
|
||||
# prior revision and/or origin edge-auth on the detailed endpoint), so
|
||||
# the gate fail-opened and ran the canary on a no-bump deploy — which
|
||||
# then flake-failed and paged. The edge URL is warm (real traffic) and
|
||||
# Cloudflare-fronted, so it returns the version reliably.
|
||||
CURRENT_VERSION=""
|
||||
for attempt in 1 2 3 4; do
|
||||
CURRENT_VERSION=$(curl -sf --connect-timeout 5 --max-time 25 \
|
||||
"https://api.nomadkaraoke.com/api/health/detailed" | jq -r '.version // empty' 2>/dev/null || echo "")
|
||||
[ -n "$CURRENT_VERSION" ] && break
|
||||
echo " version probe attempt $attempt/4 empty; retrying…"
|
||||
sleep 5
|
||||
done
|
||||
echo "Currently-serving version: ${CURRENT_VERSION:-<unknown>}"
|
||||
echo "New version: $NEW_VERSION"
|
||||
if [ -n "$CURRENT_VERSION" ] && [ "$CURRENT_VERSION" = "$NEW_VERSION" ]; then
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "↩️ Backend version unchanged — post-deploy canary will be SKIPPED."
|
||||
else
|
||||
# Unknown current version (first deploy / unreachable after retries) →
|
||||
# run the canary to be safe rather than skip a potentially real change.
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||
echo "✅ Backend version changed (or current unknown) — post-deploy canary will RUN."
|
||||
fi
|
||||
|
||||
- name: Capture build metadata
|
||||
id: build-meta
|
||||
run: |
|
||||
@@ -1908,17 +1949,37 @@ jobs:
|
||||
# header — i.e. direct-to-origin traffic bypassing the edge (health/root
|
||||
# exempt). Cutover done 2026-07-20; validated via prod E2E with 0 blocked
|
||||
# legit callers. To disable, set EDGE_AUTH_MODE=off here and redeploy.
|
||||
- name: Deploy to Cloud Run
|
||||
# R3/R4 — traffic-gated service canary.
|
||||
# Deploy the new revision with NO traffic and a `candidate` tag, smoke the
|
||||
# tagged candidate URL, then migrate 100% traffic only on pass. If the
|
||||
# smoke fails we simply don't migrate: traffic stays on the prior revision,
|
||||
# so a bad revision serves 0% instead of 100% (auto-revert by default).
|
||||
# NOTE: this protects only the Cloud Run *service*. The Cloud Run *jobs*
|
||||
# updated below cannot traffic-split, so they still rely on R1's real-job
|
||||
# post-deploy canary + the codified `scripts/rollback.sh` (R2).
|
||||
- name: Deploy to Cloud Run (candidate revision, no traffic)
|
||||
id: deploy_candidate
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
|
||||
echo "🚀 Deploying to Cloud Run..."
|
||||
# Capture the revision currently serving traffic so we can name it in
|
||||
# logs / the failure message (it's what we auto-revert to on a failed
|
||||
# smoke — no action needed since we deploy --no-traffic).
|
||||
PREV_REVISION=$(gcloud run services describe karaoke-backend \
|
||||
--region us-central1 \
|
||||
--format='value(status.traffic[0].revisionName)' 2>/dev/null || echo "")
|
||||
echo "prev_revision=$PREV_REVISION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
echo "🚀 Deploying candidate revision to Cloud Run (no traffic)..."
|
||||
echo "Image: $IMAGE"
|
||||
echo "Version: $VERSION"
|
||||
echo "Previously-serving revision: ${PREV_REVISION:-<unknown>}"
|
||||
|
||||
gcloud run deploy karaoke-backend \
|
||||
--image $IMAGE \
|
||||
--no-traffic \
|
||||
--tag candidate \
|
||||
--region us-central1 \
|
||||
--platform managed \
|
||||
--allow-unauthenticated \
|
||||
@@ -1933,10 +1994,64 @@ jobs:
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,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-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-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,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,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,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"
|
||||
|
||||
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
|
||||
- name: Smoke candidate revision
|
||||
run: |
|
||||
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
|
||||
# The `candidate` tag gives the new (0%-traffic) revision its own URL.
|
||||
CANDIDATE_URL=$(gcloud run services describe karaoke-backend \
|
||||
--region us-central1 \
|
||||
--format='json' | jq -r '.status.traffic[] | select(.tag=="candidate") | .url' | head -1)
|
||||
|
||||
if [ -z "$CANDIDATE_URL" ] || [ "$CANDIDATE_URL" = "null" ]; then
|
||||
echo "❌ Could not resolve the candidate revision URL — aborting before traffic migration."
|
||||
exit 1
|
||||
fi
|
||||
echo "Candidate URL: $CANDIDATE_URL"
|
||||
|
||||
# Health check on the candidate only (traffic still on prior revision).
|
||||
curl -f --connect-timeout 5 --max-time 30 "$CANDIDATE_URL/api/health" || {
|
||||
echo "❌ Candidate health check failed — NOT migrating traffic (prior revision keeps serving)."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Version check with retries (new revision may take a moment to be routable).
|
||||
MAX_RETRIES=6
|
||||
RETRY_DELAY=10
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Checking candidate version (attempt $i/$MAX_RETRIES)..."
|
||||
CAND_VERSION=$(curl -sf --connect-timeout 5 --max-time 30 "$CANDIDATE_URL/api/health/detailed" | jq -r '.version // empty')
|
||||
if [ "$CAND_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "✅ Candidate serving expected version: $CAND_VERSION"
|
||||
break
|
||||
fi
|
||||
echo "⚠️ Candidate version: deployed=$CAND_VERSION expected=$EXPECTED_VERSION"
|
||||
if [ $i -lt $MAX_RETRIES ]; then
|
||||
sleep $RETRY_DELAY
|
||||
else
|
||||
echo "❌ Candidate never reported the expected version — NOT migrating traffic."
|
||||
echo " Prior revision '${{ steps.deploy_candidate.outputs.prev_revision }}' keeps serving 100%."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Migrate 100% traffic to candidate
|
||||
run: |
|
||||
echo "✅ Candidate passed smoke — migrating 100% traffic to the new revision."
|
||||
gcloud run services update-traffic karaoke-backend \
|
||||
--region us-central1 \
|
||||
--to-latest
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
# NOTE: Cloud Run *Jobs* cannot traffic-split or canary — this is an
|
||||
# image-only, all-or-nothing update picked up on each job's next
|
||||
# invocation. There is no per-revision smoke here; the jobs rely on R1's
|
||||
# post-deploy real-job canary and the codified `scripts/rollback.sh` (R2)
|
||||
# for recovery if a bad image reaches them.
|
||||
run: |
|
||||
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
@@ -2026,6 +2141,134 @@ jobs:
|
||||
echo "📊 Built on self-hosted GCP runner (200GB SSD, no disk space issues)"
|
||||
echo " Runner: gcp-runner with 4 vCPU, 16GB RAM"
|
||||
|
||||
# ============================================
|
||||
# R1 — POST-DEPLOY FUNCTIONAL CANARY (version-change-gated)
|
||||
# Runs the real production happy-path (admin-credit variant, no Stripe) after
|
||||
# a backend deploy — but ONLY when the backend version actually changed
|
||||
# (deploy-backend.outputs.version_changed == 'true'). A frontend-/docs-/
|
||||
# infra-only merge ships an identical backend version and short-circuits here,
|
||||
# so we don't burn encode-VM time + a real Drive/YouTube publish on a no-op.
|
||||
# On failure: the workflow fails loudly (Discord) — this is where an operator
|
||||
# invokes `scripts/rollback.sh` (R2) to revert the service + jobs.
|
||||
# ============================================
|
||||
deploy-verify:
|
||||
name: "Deploy - Post-Deploy Canary (Happy Path)"
|
||||
needs: [deploy-backend]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
if: >-
|
||||
github.ref == 'refs/heads/main' && github.event_name == 'push' &&
|
||||
needs.deploy-backend.result == 'success' &&
|
||||
needs.deploy-backend.outputs.version_changed == 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
# Admin-credit variant: impersonate the E2E test runner (which holds
|
||||
# admin-granted credits) instead of going through Stripe. Same token-refresh
|
||||
# pattern as e2e-daily.yml's use_test_token path.
|
||||
- name: Refresh E2E session token
|
||||
id: refresh_token
|
||||
run: |
|
||||
RESPONSE=$(curl -sf --connect-timeout 5 --max-time 30 -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run post-deploy happy-path canary
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
run: |
|
||||
echo "=== Post-deploy canary: happy path against production ==="
|
||||
echo "Deployed version: ${{ needs.deploy-backend.outputs.version }}"
|
||||
echo "Time: $(date)"
|
||||
# --retries=2: the happy-path has inherently flaky UI waits (e.g. the
|
||||
# review page's "proceed to instrumental" enable), and this canary
|
||||
# PAGES on failure — a single flaky attempt must not cry wolf. Only a
|
||||
# failure that survives 2 retries is treated as real.
|
||||
npx playwright test happy-path-real-user.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=chromium \
|
||||
--reporter=list \
|
||||
--retries=2 \
|
||||
--timeout=3600000 \
|
||||
2>&1 | tee test-output-canary.log
|
||||
# Capture Playwright's real exit code, not tee's (0). Matches
|
||||
# e2e-daily.yml's rationale (grepping the log is fragile).
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check canary result
|
||||
id: test_result
|
||||
run: |
|
||||
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
|
||||
echo "result=success" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Upload canary artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: deploy-verify-canary-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
frontend/test-output-canary.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Discord notification (canary failed)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"🚨 Post-deploy canary FAILED (v${{ needs.deploy-backend.outputs.version }})\", \"description\": \"The production happy-path failed AFTER deploying v${{ needs.deploy-backend.outputs.version }}. The service already migrated 100% traffic to the new revision — consider rolling back with scripts/rollback.sh.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}" || echo "Discord notify failed (non-fatal)"
|
||||
|
||||
- name: Fail if canary failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
echo "::error::Post-deploy canary failed for v${{ needs.deploy-backend.outputs.version }}."
|
||||
echo "Roll back now with:"
|
||||
echo " scripts/rollback.sh --list # find the previous good revision + version"
|
||||
echo " scripts/rollback.sh --to-revision <PREV_REV> --image-version <PREV_VERSION>"
|
||||
exit 1
|
||||
|
||||
# ============================================
|
||||
# PROPAGATE BASE IMAGE TO ALL RUNNERS
|
||||
# When base image is rebuilt, pull it to all 3 runners
|
||||
|
||||
+121
-1
@@ -11,7 +11,7 @@ import asyncio
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Tuple, List, Optional, Any, Dict
|
||||
from typing import Tuple, List, Literal, Optional, Any, Dict
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
@@ -4189,3 +4189,123 @@ def list_user_feedback(
|
||||
avg_lyrics_accuracy_rating=round(avg_lyrics, 2) if avg_lyrics is not None else None,
|
||||
avg_correction_experience_rating=round(avg_correction, 2) if avg_correction is not None else None,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Requests board — existing-community-version review queue
|
||||
# =============================================================================
|
||||
|
||||
class CommunityReviewItem(BaseModel):
|
||||
"""A requests-board pick held for existing-community-version review."""
|
||||
id: str
|
||||
artist: str
|
||||
title: str
|
||||
submitted_by: str
|
||||
vote_count: int
|
||||
upvoter_count: int
|
||||
community_versions: Optional[Dict[str, Any]] = None
|
||||
community_checked_at: Optional[str] = None
|
||||
|
||||
|
||||
class CommunityReviewListResponse(BaseModel):
|
||||
reviews: List[CommunityReviewItem]
|
||||
|
||||
|
||||
class CommunityReviewActionBody(BaseModel):
|
||||
# make = make our own version anyway; reject = decline + notify up-voters of the
|
||||
# existing version; keep = leave on the board, snooze re-review.
|
||||
action: Literal["make", "reject", "keep"]
|
||||
|
||||
|
||||
class CommunityReviewActionResponse(BaseModel):
|
||||
status: str
|
||||
request_id: str
|
||||
message: str
|
||||
|
||||
|
||||
@router.get("/community-reviews", response_model=CommunityReviewListResponse)
|
||||
async def list_community_reviews(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""List requests-board picks the daily picker flagged because an existing
|
||||
community karaoke version was found (awaiting keep/make/reject)."""
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
service = get_song_request_service()
|
||||
items = []
|
||||
for r in service.list_pending_reviews():
|
||||
try:
|
||||
upvoters = service.list_upvoters(r.id)
|
||||
except Exception:
|
||||
upvoters = []
|
||||
items.append(CommunityReviewItem(
|
||||
id=r.id, artist=r.artist, title=r.title, submitted_by=r.submitted_by,
|
||||
vote_count=r.vote_count, upvoter_count=len(upvoters),
|
||||
community_versions=r.community_versions,
|
||||
community_checked_at=r.community_checked_at.isoformat() if r.community_checked_at else None,
|
||||
))
|
||||
return CommunityReviewListResponse(reviews=items)
|
||||
|
||||
|
||||
@router.post("/community-reviews/{request_id}", response_model=CommunityReviewActionResponse)
|
||||
async def action_community_review(
|
||||
request_id: str,
|
||||
body: CommunityReviewActionBody,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Resolve a flagged pick: make our own version, reject (notify up-voters of the
|
||||
existing version), or keep it on the board (snooze re-review)."""
|
||||
from backend.config import get_settings
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
service = get_song_request_service()
|
||||
settings = get_settings()
|
||||
|
||||
req = service.get_request(request_id)
|
||||
if req is None or req.review_state != "pending":
|
||||
raise HTTPException(status_code=404, detail="No pending review for that request.")
|
||||
|
||||
if body.action == "keep":
|
||||
until = datetime.now(timezone.utc) + timedelta(days=settings.community_review_snooze_days)
|
||||
service.snooze_review(request_id, until)
|
||||
return CommunityReviewActionResponse(
|
||||
status="snoozed", request_id=request_id,
|
||||
message=f"Kept on the board; won't be re-flagged for {settings.community_review_snooze_days} days.",
|
||||
)
|
||||
|
||||
if body.action == "reject":
|
||||
versions = req.community_versions or {}
|
||||
best_url = versions.get("best_youtube_url")
|
||||
if not best_url:
|
||||
tracks = versions.get("tracks") or []
|
||||
best_url = tracks[0].get("youtube_url") if tracks else None
|
||||
service.reject_request(request_id)
|
||||
# Notify up-voters of the existing community version (best-effort fan-out).
|
||||
notified = 0
|
||||
try:
|
||||
from backend.services.job_notification_service import get_job_notification_service
|
||||
notifier = get_job_notification_service()
|
||||
for voter in service.list_upvoters(request_id):
|
||||
ok = await notifier.send_community_existing_version_email(
|
||||
to_email=voter, artist=req.artist, title=req.title, youtube_url=best_url,
|
||||
)
|
||||
notified += 1 if ok else 0
|
||||
except Exception:
|
||||
logger.exception("community-review reject: voter notify failed for %s", request_id)
|
||||
return CommunityReviewActionResponse(
|
||||
status="rejected", request_id=request_id,
|
||||
message=f"Rejected; notified {notified} up-voter(s) of the existing version.",
|
||||
)
|
||||
|
||||
# action == "make": clear the flag and provision the job now (grant + create).
|
||||
from backend.workers.community_daily_pick import _provision_and_start
|
||||
service.clear_review(request_id)
|
||||
owner = (req.owner_email or req.submitted_by).lower()
|
||||
result = await _provision_and_start(service, settings, req, owner)
|
||||
if result.get("status") != "made":
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Failed to make request ({result.get('step')}): {result.get('message')}",
|
||||
)
|
||||
return CommunityReviewActionResponse(
|
||||
status="made", request_id=request_id,
|
||||
message=f"Making our version (job {result.get('job_id')}).",
|
||||
)
|
||||
@@ -600,6 +600,94 @@ async def process_stale_reviews_endpoint(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/youtube-backfill/run")
|
||||
async def youtube_backfill_run_endpoint(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
max_updates: Optional[int] = None,
|
||||
dry_run: bool = False,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Rewrite existing YouTube video descriptions to the current template.
|
||||
|
||||
Called by Cloud Scheduler (daily). Drains a quota-capped batch each run until
|
||||
the whole channel matches the template, emailing progress + a completion note.
|
||||
Optional query params for manual testing: ?max_updates=N&dry_run=true
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
from backend.workers.youtube_description_backfill_worker import run_backfill_sync
|
||||
|
||||
if not get_settings().youtube_backfill_enabled:
|
||||
return {"status": "disabled", "message": "YOUTUBE_BACKFILL_ENABLED is false"}
|
||||
|
||||
logger.info(f"YOUTUBE_BACKFILL starting (max_updates={max_updates}, dry_run={dry_run})")
|
||||
|
||||
async def _process():
|
||||
try:
|
||||
result = await asyncio.to_thread(run_backfill_sync, max_updates, dry_run)
|
||||
logger.info(f"YOUTUBE_BACKFILL complete: {result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"YOUTUBE_BACKFILL failed: {e}")
|
||||
|
||||
background_tasks.add_task(_process)
|
||||
return {
|
||||
"status": "started",
|
||||
"message": "YouTube description backfill started in background",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/community-daily-pick")
|
||||
async def community_daily_pick_endpoint(
|
||||
http_request: Request,
|
||||
dry_run: bool = False,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Pick + make the daily free community track (requests voting board Phase 2).
|
||||
|
||||
Called by Cloud Scheduler once a day (noon US Eastern). Idempotent: the
|
||||
per-UTC-day lock guarantees at most one free track per day even if retried.
|
||||
|
||||
Query param ``dry_run=true`` shadow-runs (logs the pick, makes nothing) —
|
||||
handy for verifying behavior before flipping the kill-switch on. The master
|
||||
switch is settings.community_daily_pick_enabled (off ⇒ always shadow).
|
||||
"""
|
||||
from backend.workers.community_daily_pick import run_daily_pick
|
||||
|
||||
logger.info("COMMUNITY_DAILY_PICK starting (dry_run=%s)", dry_run)
|
||||
add_span_attribute("operation", "community_daily_pick")
|
||||
try:
|
||||
result = await run_daily_pick(dry_run=dry_run)
|
||||
logger.info(f"COMMUNITY_DAILY_PICK complete: {result}")
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.exception(f"COMMUNITY_DAILY_PICK failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/community-handoffs")
|
||||
async def community_handoffs_endpoint(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Run the 24h ownership handoff for community picks (requests board Phase 2).
|
||||
|
||||
Called by Cloud Scheduler hourly. Reassigns tracks whose owner hasn't
|
||||
completed the review within 24h to the next up-voter (capped), or parks them.
|
||||
"""
|
||||
from backend.workers.community_handoff import process_community_handoffs
|
||||
|
||||
logger.info("COMMUNITY_HANDOFFS starting")
|
||||
add_span_attribute("operation", "community_handoffs")
|
||||
try:
|
||||
result = await process_community_handoffs()
|
||||
logger.info(f"COMMUNITY_HANDOFFS complete: {result}")
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.exception(f"COMMUNITY_HANDOFFS failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/trigger-gdrive-validation")
|
||||
async def trigger_gdrive_validation_endpoint(
|
||||
http_request: Request,
|
||||
@@ -616,11 +704,27 @@ async def trigger_gdrive_validation_endpoint(
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
# Optional brand code (incident-hardening D2): forwarded so the validator can
|
||||
# check the just-published track's own completeness same-run. expect_cdg says
|
||||
# whether that track produced a CDG (so the validator requires the CDG folder).
|
||||
brand_code = None
|
||||
expect_cdg = False
|
||||
try:
|
||||
body = await http_request.json()
|
||||
if isinstance(body, dict):
|
||||
brand_code = body.get("brand_code")
|
||||
expect_cdg = bool(body.get("expect_cdg", False))
|
||||
except Exception: # noqa: BLE001 - empty/non-JSON body is the normal case
|
||||
brand_code = None
|
||||
expect_cdg = False
|
||||
|
||||
logger.info("GDRIVE_VALIDATION_TRIGGER starting (delayed post-job)")
|
||||
add_span_attribute("operation", "gdrive_validation_trigger")
|
||||
if brand_code:
|
||||
add_span_attribute("brand_code", str(brand_code))
|
||||
|
||||
try:
|
||||
result = trigger_gdrive_validation()
|
||||
result = trigger_gdrive_validation(brand_code=brand_code, expect_cdg=expect_cdg)
|
||||
if result is None:
|
||||
return {"status": "skipped", "message": "GDRIVE_VALIDATOR_URL not configured"}
|
||||
|
||||
|
||||
@@ -1667,6 +1667,7 @@ DOWNLOAD_FILENAME_SUFFIXES = {
|
||||
"lossless_4k_mkv": " (Final Karaoke Lossless 4k).mkv",
|
||||
"lossy_4k_mp4": " (Final Karaoke Lossy 4k).mp4",
|
||||
"lossy_720p_mp4": " (Final Karaoke Lossy 720p).mp4",
|
||||
"portrait_1080x1920": " (Final Karaoke Portrait 1080x1920).mp4",
|
||||
"cdg_zip": " (Final Karaoke CDG).zip",
|
||||
"txt_zip": " (Final Karaoke TXT).zip",
|
||||
"with_vocals_mp4": " (With Vocals).mp4",
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""
|
||||
Public song-request voting board API (requests.nomadkaraoke.com).
|
||||
|
||||
Anyone signed in with an email magic link can submit a song request (auto-corrected
|
||||
artist/title) and cast one vote per calendar day. The board itself (GET /requests) is
|
||||
readable without auth so it can be linked from YouTube descriptions and browsed freely.
|
||||
|
||||
Phase 2 (daily auto-picker, free-credit grant, ownership handoff, voter emails) is not
|
||||
here — see docs/archive/2026-09-02-requests-voting-board-plan.md.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
|
||||
from backend.api.dependencies import require_auth, security, get_token_from_request
|
||||
from backend.services.auth_service import AuthResult, get_auth_service
|
||||
from backend.services.match_judge.classifier import normalize_for_match
|
||||
from backend.models.song_request import (
|
||||
BoardResponse,
|
||||
DailyVoteStatus,
|
||||
SongRequest,
|
||||
SongRequestPublic,
|
||||
SubmitRequestBody,
|
||||
SubmitResponse,
|
||||
VoteBody,
|
||||
)
|
||||
from backend.services.song_request_service import (
|
||||
RequestNotFound,
|
||||
SubmissionRateLimited,
|
||||
get_song_request_service,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/requests-board", tags=["requests-board"])
|
||||
|
||||
|
||||
async def optional_user_email(
|
||||
request: Request,
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
||||
) -> Optional[str]:
|
||||
"""Resolve the caller's email if a valid token is present, else None.
|
||||
|
||||
Unlike require_auth this never raises — the board is publicly viewable, we just
|
||||
annotate the viewer's own vote when they happen to be signed in.
|
||||
"""
|
||||
token = await get_token_from_request(request, credentials, None)
|
||||
if not token:
|
||||
return None
|
||||
try:
|
||||
result = get_auth_service().validate_token_full(token)
|
||||
return result.user_email if result.is_valid else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _was_corrected(req: SongRequest) -> bool:
|
||||
return (
|
||||
normalize_for_match(req.artist_raw) != normalize_for_match(req.artist)
|
||||
or normalize_for_match(req.title_raw) != normalize_for_match(req.title)
|
||||
)
|
||||
|
||||
|
||||
def _to_public(req: SongRequest, your_vote: Optional[int] = None) -> SongRequestPublic:
|
||||
return SongRequestPublic(
|
||||
id=req.id,
|
||||
artist=req.artist,
|
||||
title=req.title,
|
||||
status=req.status,
|
||||
source=req.source,
|
||||
vote_count=req.vote_count,
|
||||
created_at=req.created_at.isoformat(),
|
||||
youtube_url=req.youtube_url,
|
||||
was_corrected=_was_corrected(req),
|
||||
your_vote=your_vote,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/requests", response_model=BoardResponse)
|
||||
async def list_requests(
|
||||
viewer_email: Optional[str] = Depends(optional_user_email),
|
||||
):
|
||||
"""The ranked board: active requests + recently published, with the caller's vote."""
|
||||
service = get_song_request_service()
|
||||
active = service.list_active()
|
||||
published = service.list_published()
|
||||
|
||||
daily_vote = service.get_daily_vote(viewer_email) if viewer_email else None
|
||||
voted_request_id = daily_vote.request_id if daily_vote else None
|
||||
voted_value = daily_vote.value if daily_vote else None
|
||||
|
||||
return BoardResponse(
|
||||
requests=[
|
||||
_to_public(r, your_vote=voted_value if r.id == voted_request_id else None)
|
||||
for r in active
|
||||
],
|
||||
published=[_to_public(r) for r in published],
|
||||
voted_today=bool(daily_vote) if viewer_email is not None else None,
|
||||
your_vote_request_id=voted_request_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/requests", response_model=SubmitResponse)
|
||||
async def submit_request(
|
||||
body: SubmitRequestBody,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Submit a song request (requires sign-in). Auto-corrects artist/title and dedupes."""
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=403, detail="A signed-in email is required to submit.")
|
||||
|
||||
service = get_song_request_service()
|
||||
try:
|
||||
request, already_existed, canonical_artist, canonical_title = await service.submit_request(
|
||||
auth_result.user_email, body.artist, body.title
|
||||
)
|
||||
except SubmissionRateLimited:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail="You've submitted a lot today — please come back tomorrow.",
|
||||
)
|
||||
|
||||
daily = service.get_daily_vote(auth_result.user_email)
|
||||
your_vote = daily.value if daily and daily.request_id == request.id else None
|
||||
return SubmitResponse(
|
||||
status="already_exists" if already_existed else "created",
|
||||
request=_to_public(request, your_vote=your_vote),
|
||||
canonical_artist=canonical_artist,
|
||||
canonical_title=canonical_title,
|
||||
was_corrected=_was_corrected(request),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/requests/{request_id}/vote", response_model=SongRequestPublic)
|
||||
async def vote(
|
||||
request_id: str,
|
||||
body: VoteBody,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Cast/move/undo your single daily vote on a request."""
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=403, detail="A signed-in email is required to vote.")
|
||||
|
||||
service = get_song_request_service()
|
||||
try:
|
||||
service.cast_vote(auth_result.user_email, request_id, body.direction)
|
||||
except RequestNotFound:
|
||||
raise HTTPException(status_code=404, detail="That request no longer exists.")
|
||||
|
||||
updated = service.get_request(request_id)
|
||||
if not updated:
|
||||
raise HTTPException(status_code=404, detail="That request no longer exists.")
|
||||
daily = service.get_daily_vote(auth_result.user_email)
|
||||
your_vote = daily.value if daily and daily.request_id == request_id else None
|
||||
return _to_public(updated, your_vote=your_vote)
|
||||
|
||||
|
||||
@router.get("/me", response_model=DailyVoteStatus)
|
||||
async def my_daily_status(
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""The caller's daily-vote status (has today's vote been used, and on what)."""
|
||||
service = get_song_request_service()
|
||||
daily = service.get_daily_vote(auth_result.user_email) if auth_result.user_email else None
|
||||
return DailyVoteStatus(
|
||||
voted_today=bool(daily),
|
||||
request_id=daily.request_id if daily else None,
|
||||
value=daily.value if daily else None,
|
||||
)
|
||||
@@ -65,7 +65,7 @@ from backend.services.job_defaults_service import (
|
||||
get_effective_distribution_settings,
|
||||
resolve_cdg_txt_defaults,
|
||||
)
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.api.dependencies import require_admin, require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
from backend.services.auth_service import UserType
|
||||
@@ -259,12 +259,18 @@ async def send_magic_link(
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
# Board sign-in ("requests_board") is passwordless identity only: no welcome credit,
|
||||
# and a HIGHER per-IP signup cap (BOARD_MAX_SIGNUPS_PER_IP) so a whole venue on shared
|
||||
# WiFi can sign in to vote — but still a deterministic ceiling, not an open door.
|
||||
is_board_signin = request.purpose == "requests_board"
|
||||
|
||||
# Per-IP and per-fingerprint signup rate limit (only for new users)
|
||||
device_fingerprint = request.device_fingerprint
|
||||
existing_user = user_service.get_user(email)
|
||||
if existing_user is None:
|
||||
signup_limit = user_service.BOARD_MAX_SIGNUPS_PER_IP if is_board_signin else None
|
||||
if user_service.is_signup_rate_limited(
|
||||
ip_address=ip_address, device_fingerprint=device_fingerprint
|
||||
ip_address=ip_address, device_fingerprint=device_fingerprint, max_signups=signup_limit
|
||||
):
|
||||
logger.warning(
|
||||
f"Signup rate limit hit: IP={ip_address} for {_mask_email(email)}"
|
||||
@@ -310,6 +316,7 @@ async def send_magic_link(
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
referral_code=request.referral_code,
|
||||
purpose=request.purpose,
|
||||
)
|
||||
|
||||
# Get tenant-specific email configuration
|
||||
@@ -341,7 +348,8 @@ async def send_magic_link(
|
||||
# By the time they check their email and click the link, the decision
|
||||
# will be ready and verification will be instant.
|
||||
# Skip for test emails — they get auto-granted without evaluation.
|
||||
if existing_user is None and not is_test_email(email):
|
||||
# Skip for board sign-in — it never grants a welcome credit, so there's nothing to eval.
|
||||
if existing_user is None and not is_test_email(email) and not is_board_signin:
|
||||
thread = threading.Thread(
|
||||
target=_precompute_credit_eval,
|
||||
args=(magic_link.token, email),
|
||||
@@ -385,9 +393,11 @@ async def verify_magic_link(
|
||||
magic_link_doc = user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).get()
|
||||
is_first_login = False
|
||||
magic_link_tenant_id = None
|
||||
magic_link_purpose = None
|
||||
if magic_link_doc.exists:
|
||||
magic_link_data = magic_link_doc.to_dict()
|
||||
magic_link_tenant_id = magic_link_data.get('tenant_id')
|
||||
magic_link_purpose = magic_link_data.get('purpose')
|
||||
pre_verify_user = user_service.get_user(magic_link_data.get('email', ''))
|
||||
if pre_verify_user:
|
||||
is_first_login = pre_verify_user.total_jobs_created == 0 and not pre_verify_user.last_login_at
|
||||
@@ -410,9 +420,15 @@ async def verify_magic_link(
|
||||
|
||||
credits_granted = 0
|
||||
credit_status = "not_applicable" # returning user, not first login
|
||||
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
|
||||
user.email, precomputed_eval=precomputed_eval,
|
||||
)
|
||||
# Board sign-in grants NO welcome credit — it's identity only. The credit is granted
|
||||
# later, when the user converts via the "make it yourself now" flow (claim endpoint),
|
||||
# or when their requested track gets picked (Phase 2).
|
||||
is_board_signin = magic_link_purpose == "requests_board"
|
||||
granted = False
|
||||
if not is_board_signin:
|
||||
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
|
||||
user.email, precomputed_eval=precomputed_eval,
|
||||
)
|
||||
if granted:
|
||||
credits_granted = user_service.NEW_USER_FREE_CREDITS
|
||||
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
|
||||
@@ -472,8 +488,9 @@ async def verify_magic_link(
|
||||
device_fingerprint=magic_link_fingerprint,
|
||||
)
|
||||
|
||||
# Send welcome email to first-time users
|
||||
if is_first_login:
|
||||
# Send welcome email to first-time users (not for board sign-in — no credit granted,
|
||||
# and the credit-centric welcome copy would be confusing with a 0 balance).
|
||||
if is_first_login and not is_board_signin:
|
||||
email_service.send_welcome_email(user.email, user.credits, locale=locale)
|
||||
|
||||
# Return user info with tenant_id
|
||||
@@ -496,6 +513,40 @@ async def verify_magic_link(
|
||||
tenant_subdomain=tenant_subdomain,
|
||||
credits_granted=credits_granted,
|
||||
credit_status=credit_status,
|
||||
redirect_path="/requests" if is_board_signin else None,
|
||||
)
|
||||
|
||||
|
||||
class ClaimWelcomeCreditResponse(BaseModel):
|
||||
"""Response for the convert-to-gen welcome-credit claim."""
|
||||
status: str # "granted" | "already_granted" | "denied" | "pending_review" | ...
|
||||
credits: int
|
||||
credits_granted: int = 0
|
||||
|
||||
|
||||
@router.post("/claim-welcome-credit", response_model=ClaimWelcomeCreditResponse)
|
||||
async def claim_welcome_credit(
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""Grant the standard one-time welcome credit to a signed-in user.
|
||||
|
||||
Powers the requests-board "Don't want to wait? Make it yourself now" conversion:
|
||||
board sign-in itself grants no credit, so when a board user decides to use the
|
||||
generator we grant their welcome credit here (idempotent — once per account, with
|
||||
the usual abuse evaluation). Returns the resulting balance.
|
||||
"""
|
||||
email = auth_result.user_email
|
||||
if not email:
|
||||
raise HTTPException(status_code=403, detail="A signed-in email is required.")
|
||||
|
||||
granted, credit_status = user_service.grant_welcome_credits_if_eligible(email)
|
||||
user = user_service.get_user(email)
|
||||
balance = user.credits if user else 0
|
||||
return ClaimWelcomeCreditResponse(
|
||||
status=credit_status,
|
||||
credits=balance,
|
||||
credits_granted=user_service.NEW_USER_FREE_CREDITS if granted else 0,
|
||||
)
|
||||
|
||||
|
||||
|
||||
+65
-3
@@ -200,6 +200,15 @@ class Settings(BaseSettings):
|
||||
# Default is false - Cloud Tasks is sufficient for most videos (15-20 min).
|
||||
use_cloud_run_jobs_for_video: bool = os.getenv("USE_CLOUD_RUN_JOBS_FOR_VIDEO", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
# When enabled AND enable_cloud_tasks is true, the post-review render worker
|
||||
# also runs as a Cloud Run Job (reusing video-encoding-job with an args
|
||||
# override). As a BackgroundTask on the service it was killed by every
|
||||
# deploy rollout that landed mid-render — Cloud Run gives instances only
|
||||
# 10s after SIGTERM, far less than a render takes, so the job froze at
|
||||
# rendering_video until the 45-min stuck-job sweep (incident 2026-09-13,
|
||||
# job 41e06b90; same class as incident 2026-03-08 for the video worker).
|
||||
use_cloud_run_jobs_for_render: bool = os.getenv("USE_CLOUD_RUN_JOBS_FOR_RENDER", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
# GCE Encoding Worker (for high-performance video encoding)
|
||||
# When enabled, video encoding is offloaded to a dedicated C4 GCE instance
|
||||
# with faster CPU (Intel Granite Rapids 3.9 GHz) instead of Cloud Run.
|
||||
@@ -257,6 +266,19 @@ class Settings(BaseSettings):
|
||||
default_enable_youtube_upload: bool = os.getenv("DEFAULT_ENABLE_YOUTUBE_UPLOAD", "false").lower() in ("true", "1", "yes")
|
||||
default_brand_prefix: Optional[str] = os.getenv("DEFAULT_BRAND_PREFIX")
|
||||
|
||||
# Requests voting board — Phase 2 daily free-community-track automation.
|
||||
# Master kill-switch: when False the daily picker claims the day and records a
|
||||
# "skipped" lock but never grants credits or creates a job (safe to deploy dark).
|
||||
community_daily_pick_enabled: bool = os.getenv(
|
||||
"COMMUNITY_DAILY_PICK_ENABLED", "false"
|
||||
).lower() in ("true", "1", "yes")
|
||||
# Max distinct voters the 24h ownership handoff will try before parking a track.
|
||||
community_handoff_max_attempts: int = int(os.getenv("COMMUNITY_HANDOFF_MAX_ATTEMPTS", "5"))
|
||||
# Hours an owner has to complete their review before the job is handed off.
|
||||
community_handoff_hours: int = int(os.getenv("COMMUNITY_HANDOFF_HOURS", "24"))
|
||||
# When a flagged pick is "kept on board", how long before it can be re-flagged.
|
||||
community_review_snooze_days: int = int(os.getenv("COMMUNITY_REVIEW_SNOOZE_DAYS", "30"))
|
||||
|
||||
# Private (non-published) track distribution settings
|
||||
default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")
|
||||
default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")
|
||||
@@ -270,13 +292,53 @@ class Settings(BaseSettings):
|
||||
youtube_quota_safety_margin: int = int(os.getenv("YOUTUBE_QUOTA_SAFETY_MARGIN", "500"))
|
||||
# E2E test bypass key for rate limiting (set via secret in production)
|
||||
e2e_bypass_key: str = os.getenv("E2E_BYPASS_KEY", "")
|
||||
# Canonical YouTube description template. Placeholders ({title}, {artist},
|
||||
# {artist_hashtag}, {brand_code}) are filled by
|
||||
# backend.services.youtube_description.render_youtube_description, which is the
|
||||
# single source of truth shared with the bulk-rewrite tool
|
||||
# (scripts/youtube-descriptions). Keep those two in sync when editing this.
|
||||
default_youtube_description: str = os.getenv(
|
||||
"DEFAULT_YOUTUBE_DESCRIPTION",
|
||||
"Karaoke video created with Nomad Karaoke (https://nomadkaraoke.com)\n\n"
|
||||
"AI-powered vocal separation and synchronized lyrics.\n\n"
|
||||
"#karaoke #music #singing #instrumental #lyrics"
|
||||
'🎤 Sing along to "{title}" by {artist} — a high-quality karaoke version '
|
||||
"using the original song audio with the lead vocals removed and scrolling "
|
||||
"lyrics hand-synced to the music.\n\n"
|
||||
"⬆️ REQUEST THE NEXT NOMAD RELEASE\n"
|
||||
"Vote for the songs you want us to make next — the most-upvoted requests get "
|
||||
"made into karaoke videos and published free, right here on this channel. "
|
||||
"Nothing to buy, no password needed:\n"
|
||||
"👉 https://requests.nomadkaraoke.com\n\n"
|
||||
"▶️ MAKE A VIDEO LIKE THIS FOR ANY SONG\n"
|
||||
"Create studio-quality karaoke videos of ANY song, ready in under an hour:\n"
|
||||
"👉 https://nomadkaraoke.com/r/youtube\n"
|
||||
"Follow that link for 50% off all credit purchases for your first 30 days.\n\n"
|
||||
"🎶 KARAOKE LOVER LINKS\n"
|
||||
"• Nomad Karaoke Community Discord: https://discord.nomadkaraoke.com\n"
|
||||
"• Decide what to sing at karaoke: https://decide.nomadkaraoke.com\n"
|
||||
"• Search all community karaoke tracks: https://karaokenerds.com\n\n"
|
||||
"🔔 Subscribe for new karaoke tracks, and comment to show some love!\n\n"
|
||||
"#karaoke #{artist_hashtag} #instrumental #lyrics #singalong\n"
|
||||
"—\n"
|
||||
"COPYRIGHT: I don't own the rights to the original music; all rights belong "
|
||||
"to the respective copyright holders. If you enjoy the song, please buy the "
|
||||
"original and support the artist. Under §107 of the U.S. Copyright Act 1976, "
|
||||
'allowance is made for "fair use" (criticism, comment, teaching, and '
|
||||
"research).\n\n"
|
||||
"Brand Code: {brand_code}"
|
||||
)
|
||||
|
||||
# YouTube description back-catalogue rewrite (scheduled daily drain worker).
|
||||
# Rewrites existing channel videos to match `default_youtube_description`.
|
||||
# Reusable: whenever the template changes, the worker re-drains the channel.
|
||||
youtube_backfill_enabled: bool = os.getenv("YOUTUBE_BACKFILL_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
# Hard ceiling on updates per daily run (each costs ~50 quota units).
|
||||
youtube_backfill_daily_max_updates: int = int(os.getenv("YOUTUBE_BACKFILL_DAILY_MAX_UPDATES", "150"))
|
||||
# Quota units to leave untouched for the live upload pipeline each day.
|
||||
youtube_backfill_quota_reserve: int = int(os.getenv("YOUTUBE_BACKFILL_QUOTA_RESERVE", "3000"))
|
||||
# Refresh tags too (not just description) when rewriting.
|
||||
youtube_backfill_enrich_tags: bool = os.getenv("YOUTUBE_BACKFILL_ENRICH_TAGS", "true").lower() in ("true", "1", "yes")
|
||||
# Where the daily progress + completion emails are sent.
|
||||
youtube_backfill_report_email: str = os.getenv("YOUTUBE_BACKFILL_REPORT_EMAIL", "andrew@nomadkaraoke.com")
|
||||
|
||||
# Default CDG/TXT generation settings
|
||||
# When True, CDG and TXT packages are generated by default (when a theme is set)
|
||||
# These can be overridden per-request via explicit enable_cdg/enable_txt parameters
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Video IDs to FORCE-rewrite even though the title isn't high-confidence
|
||||
# "Artist - Title (Karaoke)" — e.g. genuine tracks whose "(Karaoke)" suffix was
|
||||
# truncated by YouTube's 100-char title limit.
|
||||
#
|
||||
# Two forms per line ('#' starts a comment):
|
||||
# <id> use the tool's best-effort parsed artist/title
|
||||
# <id> | <Artist> | <Title> override artist/title (for truncated titles)
|
||||
#
|
||||
# --- Genuine tracks rescued from the "review candidates" bucket (2026-09-03) ---
|
||||
|
||||
# Truncated titles restored to full song titles:
|
||||
5zSFKuCEIhs | Los Campesinos! | This Is How You Spell "HAHAHA, We Destroyed the Hopes and Dreams of a Generation of Faux-Romantics"
|
||||
kkT-bZhi9jI | Arctic Monkeys | You Probably Couldn't See for the Lights but You Were Looking Straight at Me
|
||||
|
||||
# Long medley titles parsed fine — no override needed:
|
||||
le347q8nHT4 # Daniel O'Donnell - Medley: Galway Bay, The Mountains Of Mourne, ...
|
||||
3ihDlPse--k # Daniel O'Donnell - Medley: It's a Long Way to Tipperary / ...
|
||||
@@ -0,0 +1,29 @@
|
||||
# Video IDs that should NEVER have their description rewritten by the bulk tool.
|
||||
# One YouTube video ID per line. Everything after a '#' is ignored.
|
||||
#
|
||||
# The "unparseable" videos are already auto-skipped by the classifier; these are
|
||||
# listed explicitly for the record + belt-and-suspenders (so they stay skipped
|
||||
# even if a title changes later).
|
||||
|
||||
# --- Lyrics videos WITH vocals (NOT instrumental karaoke) ---
|
||||
SUkl49w9GPA # buildspace, MAYV - the end (Lyrics Video)
|
||||
jAAhbfmh8Bc # 100 gecs - mememe (Lyrics Video With Vocals)
|
||||
mcZtK8kkx3E # Fleet Foxes - Montezuma (Lyrics / With Vocals)
|
||||
|
||||
# --- Demos / tutorials / screencasts / pitch / channel-explainer (not karaoke) ---
|
||||
VTR3oaqgn0A # Nomad karaoke-gen hosted demo screencast 2026-05-16
|
||||
-dI3r7qXo3A # Nomad Karaoke Generator - Full Tutorial
|
||||
C0Zyy_9V5F8 # Purim Shpiel custom lyrics karaoke tracks production screencast
|
||||
josVDsYwsFM # Nomad Karaoke Lyrics Review Demo (for AudioShake) Screencast
|
||||
NZ8j0uxq6tA # YouTube "Reused content" claim appeal - channel explanation
|
||||
asnwjLyqY4k # Nomad Karaoke production workflow (real time) 2025-02-26
|
||||
dPWyYfjfHvw # Pitch Night - BIC Energy
|
||||
63-Fk3mfZ7Q # Nomad Karaoke Creation Workflow (Normal Speed) 2023-12-19
|
||||
ZsROHgqAVHs # Nomad Karaoke Creation Workflow (MidiCo Tutorial) 2023-12-19
|
||||
|
||||
# --- Unparseable-title non-karaoke (already auto-skipped; explicit for record) ---
|
||||
RLkIEHGwFcU # Nomad Karaoke Generator Quick Demo
|
||||
GJY60IfIHOQ # Nomad Karaoke Generator Demo 2026
|
||||
v1Hox6XMYEw # "YouTube Karaoke just suffered a major loss" (short/commentary)
|
||||
R3eOl1aeq5c # Nomad Karaoke stands with Lemmy Caution (commentary)
|
||||
wHiMti3xLJE # Nomad Karaoke Creation Tutorial / Demo 1 (MidiCo, July 2023)
|
||||
+19
-8
@@ -111,19 +111,28 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown - wait for any active workers to complete before terminating
|
||||
# This prevents Cloud Run from killing workers mid-processing.
|
||||
# Shutdown - best-effort parking of any still-registered workers.
|
||||
#
|
||||
# Cloud Run gen2 default termination grace period is 600s. We wait up to
|
||||
# 480s, leaving ~120s for the cleanup pass below to write Firestore state
|
||||
# before SIGKILL. Without that headroom, render jobs that miss the wait
|
||||
# would sit in `rendering_video` forever waiting for an operator.
|
||||
# Reality check (incident 2026-09-13, job 41e06b90): Cloud Run services
|
||||
# SIGKILL instances ~10 seconds after SIGTERM — NOT the 600s this comment
|
||||
# previously claimed — and uvicorn only runs this lifespan-shutdown code
|
||||
# AFTER all BackgroundTasks have completed ("Waiting for background tasks
|
||||
# to complete"). A long-running worker task therefore keeps uvicorn stuck
|
||||
# in that wait until SIGKILL, and this hook never executes at all. It can
|
||||
# NOT be relied on to protect in-flight renders; that protection comes
|
||||
# from running them as Cloud Run Jobs instead (USE_CLOUD_RUN_JOBS_FOR_RENDER,
|
||||
# mirroring USE_CLOUD_RUN_JOBS_FOR_VIDEO from incident 2026-03-08).
|
||||
#
|
||||
# This hook is kept as a cheap safety net for the legacy flag-off path and
|
||||
# for the narrow case where workers finish right as SIGTERM lands. The wait
|
||||
# is capped well inside the 10s kill window so the parking pass below still
|
||||
# gets a chance to write Firestore state.
|
||||
logger.info("Shutdown requested, checking for active workers...")
|
||||
if worker_registry.has_active_workers():
|
||||
active = worker_registry.get_active_workers()
|
||||
logger.info(f"Active workers found: {active}")
|
||||
logger.info("Waiting for workers to complete (timeout: 480s)...")
|
||||
completed = await worker_registry.wait_for_completion(timeout=480)
|
||||
logger.info("Waiting for workers to complete (timeout: 5s)...")
|
||||
completed = await worker_registry.wait_for_completion(timeout=5)
|
||||
if not completed:
|
||||
logger.error(
|
||||
"Shutdown timeout - some workers may not have completed cleanly. "
|
||||
@@ -201,6 +210,8 @@ app.include_router(push.router, prefix="/api") # Push notification subscription
|
||||
app.include_router(catalog.router, prefix="/api") # Catalog proxy for song/artist autocomplete
|
||||
app.include_router(parse_titles.router, prefix="/api") # kjbox karaoke-filename parser
|
||||
app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submission
|
||||
from backend.api.routes import requests_board
|
||||
app.include_router(requests_board.router, prefix="/api") # Public song-request voting board
|
||||
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
app.include_router(tenant_admin.router) # Admin tenant provisioning (router has /api prefix)
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""
|
||||
Models for the public song-request voting board (requests.nomadkaraoke.com).
|
||||
|
||||
A minimal, Hacker-News-style board where anyone (email magic-link auth) can:
|
||||
- submit a song request (artist + title, auto-corrected via match_judge)
|
||||
- cast one vote per calendar day, up or down, on a single request
|
||||
|
||||
Phase 1 (this file) covers the board itself. Phase 2 adds the daily auto-picker,
|
||||
free-credit grant, ownership handoff, and voter publish emails — see
|
||||
docs/archive/2026-09-02-requests-voting-board-plan.md.
|
||||
"""
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
# Request lifecycle. Phase 1 only ever sets/reads "open"; the later states are
|
||||
# advanced by the daily picker (Phase 2):
|
||||
# open -> queued (picked, job being created) -> in_progress (job created, owner reviewing)
|
||||
# -> published (live on YouTube) | rejected (manually killed)
|
||||
# -> stalled (handoff exhausted its voter cap without anyone completing the review)
|
||||
RequestStatus = Literal[
|
||||
"open", "queued", "in_progress", "published", "rejected", "stalled"
|
||||
]
|
||||
|
||||
# Where a request came from. Phase 2's trending-karaoke agent submits with
|
||||
# source="trending_agent"; everything a human submits is "human".
|
||||
RequestSource = Literal["human", "trending_agent"]
|
||||
|
||||
# Existing-community-version review state (set when the daily picker's KaraokeNerds
|
||||
# check finds an existing community karaoke version for a would-be pick):
|
||||
# pending -> flagged, awaiting Andrew's keep/make/reject decision (admin queue)
|
||||
# snoozed -> Andrew chose "keep on board"; not re-flagged until review_snoozed_until
|
||||
# None means never flagged. The request stays votable/visible on the board throughout;
|
||||
# the picker just won't auto-make a flagged (pending, or still-snoozed) request.
|
||||
ReviewState = Literal["pending", "snoozed"]
|
||||
|
||||
|
||||
class SongRequest(BaseModel):
|
||||
"""A single song request on the public board (Firestore: song_requests)."""
|
||||
|
||||
id: str
|
||||
# Canonical (post match_judge) artist/title shown on the board.
|
||||
artist: str
|
||||
title: str
|
||||
# Exactly what the user typed, kept for audit / "did we correct this right?".
|
||||
artist_raw: str
|
||||
title_raw: str
|
||||
# Normalized artist+title used to dedupe re-submissions of the same song.
|
||||
dedupe_key: str
|
||||
|
||||
submitted_by: str # lowercased email
|
||||
source: RequestSource = "human"
|
||||
status: RequestStatus = "open"
|
||||
|
||||
# Denormalized net score (sum of vote values). Kept in sync via Increment.
|
||||
vote_count: int = 0
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
# Phase-2 fields (never set in Phase 1).
|
||||
job_id: Optional[str] = None
|
||||
youtube_url: Optional[str] = None
|
||||
picked_at: Optional[datetime] = None
|
||||
|
||||
# Current owner of the generated job (starts as the requester; the 24h handoff
|
||||
# reassigns it to successive up-voters). owner_assigned_at gates the 24h clock.
|
||||
owner_email: Optional[str] = None
|
||||
owner_assigned_at: Optional[datetime] = None
|
||||
# Emails already made owner (submitter first, then handoff targets) — never retry one.
|
||||
attempted_owners: list[str] = Field(default_factory=list)
|
||||
handoff_attempts: int = 0
|
||||
|
||||
# Idempotency guards for the daily-pick side effects.
|
||||
community_credit_granted: bool = False # the free credit was granted for this pick
|
||||
voters_notified: bool = False # publish fan-out fully delivered to every up-voter
|
||||
# Voters already successfully emailed on publish — lets a re-run retry only the
|
||||
# failures instead of re-emailing everyone (voters_notified is the all-done flag).
|
||||
notified_voters: list[str] = Field(default_factory=list)
|
||||
|
||||
# Existing-community-version review (set by the daily picker's KaraokeNerds check).
|
||||
review_state: Optional[ReviewState] = None
|
||||
# The community versions we found, stored so the admin queue + reject email can
|
||||
# show/link them: {"best_youtube_url": str|None, "tracks": [{"brand_name","youtube_url"}]}.
|
||||
community_versions: Optional[dict] = None
|
||||
community_checked_at: Optional[datetime] = None
|
||||
review_snoozed_until: Optional[datetime] = None
|
||||
|
||||
|
||||
class Vote(BaseModel):
|
||||
"""A single daily vote (Firestore: song_request_votes, doc id = {email}__{date}).
|
||||
|
||||
The doc id encodes the one-vote-per-person-per-day rule structurally: a user can
|
||||
only ever have one vote document for a given UTC date.
|
||||
"""
|
||||
|
||||
voter_email: str # lowercased
|
||||
voted_date: str # UTC "YYYY-MM-DD"
|
||||
request_id: str
|
||||
value: int # +1 (up) or -1 (down)
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
|
||||
class DailyCommunityPick(BaseModel):
|
||||
"""Per-UTC-day lock/ledger for the daily free-track picker (Firestore:
|
||||
daily_community_pick, doc id = "YYYY-MM-DD").
|
||||
|
||||
Created create-only so only one run per day can proceed (enforces "one free
|
||||
track per day, total"). ``phase`` lets a crashed run resume the same day
|
||||
without double-granting credits or creating a second job.
|
||||
"""
|
||||
|
||||
date: str # UTC "YYYY-MM-DD" (also the doc id)
|
||||
# claimed -> credit_granted -> job_created -> done
|
||||
# empty -> board had nothing eligible (no track made today)
|
||||
# skipped -> disabled / dry-run
|
||||
phase: Literal[
|
||||
"claimed", "credit_granted", "job_created", "done", "empty", "skipped"
|
||||
] = "claimed"
|
||||
request_id: Optional[str] = None
|
||||
job_id: Optional[str] = None
|
||||
owner_email: Optional[str] = None
|
||||
note: Optional[str] = None
|
||||
claimed_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
|
||||
# --- API request/response models ---
|
||||
|
||||
|
||||
class SubmitRequestBody(BaseModel):
|
||||
artist: str = Field(..., min_length=1, max_length=200)
|
||||
title: str = Field(..., min_length=1, max_length=200)
|
||||
|
||||
@field_validator("artist", "title")
|
||||
@classmethod
|
||||
def _not_blank(cls, v: str) -> str:
|
||||
# min_length=1 accepts " " — strip first so whitespace-only input is rejected
|
||||
# (the service also strips, but this stops a blank request at the API boundary).
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("must not be blank")
|
||||
return v
|
||||
|
||||
|
||||
class VoteBody(BaseModel):
|
||||
direction: Literal["up", "down"]
|
||||
|
||||
|
||||
class SongRequestPublic(BaseModel):
|
||||
"""Board item as exposed to the frontend. Never includes voter emails."""
|
||||
|
||||
id: str
|
||||
artist: str
|
||||
title: str
|
||||
status: RequestStatus
|
||||
source: RequestSource
|
||||
vote_count: int
|
||||
created_at: str # ISO
|
||||
youtube_url: Optional[str] = None
|
||||
# Whether the submitter's raw input differed from the canonical form we stored.
|
||||
was_corrected: bool = False
|
||||
# Per-viewer annotation (only set when the caller is authenticated).
|
||||
your_vote: Optional[int] = None # +1 / -1 / None
|
||||
|
||||
|
||||
class SubmitResponse(BaseModel):
|
||||
status: str # "created" | "already_exists"
|
||||
request: SongRequestPublic
|
||||
# match_judge canonicalization surfaced so the UI can say "we tidied that to …".
|
||||
canonical_artist: str
|
||||
canonical_title: str
|
||||
was_corrected: bool
|
||||
|
||||
|
||||
class BoardResponse(BaseModel):
|
||||
"""The board payload: active (votable) requests + recently published ones."""
|
||||
|
||||
requests: list[SongRequestPublic]
|
||||
published: list[SongRequestPublic] = []
|
||||
# The authenticated caller's daily-vote state (null when signed out).
|
||||
voted_today: Optional[bool] = None
|
||||
your_vote_request_id: Optional[str] = None
|
||||
|
||||
|
||||
class DailyVoteStatus(BaseModel):
|
||||
voted_today: bool
|
||||
request_id: Optional[str] = None
|
||||
value: Optional[int] = None
|
||||
@@ -149,6 +149,11 @@ class MagicLinkToken(BaseModel):
|
||||
# Referral attribution (travels with magic link for cross-device support)
|
||||
referral_code: Optional[str] = None
|
||||
|
||||
# Sign-in context. "requests_board" = passwordless identity only: skip the welcome
|
||||
# credit + the per-IP signup limit (so a whole venue on shared WiFi can sign in to
|
||||
# vote), and route the user back to the board after verifying.
|
||||
purpose: Optional[str] = None
|
||||
|
||||
# Pre-computed credit evaluation (set asynchronously after magic link is sent)
|
||||
credit_eval_decision: Optional[str] = None # "grant", "deny", "pending_review"
|
||||
credit_eval_reasoning: Optional[str] = None
|
||||
@@ -185,6 +190,8 @@ class SendMagicLinkRequest(BaseModel):
|
||||
email: str
|
||||
device_fingerprint: Optional[str] = None
|
||||
referral_code: Optional[str] = None # From referral interstitial
|
||||
# "requests_board" = board sign-in (identity only; no welcome credit / no IP limit).
|
||||
purpose: Optional[str] = None
|
||||
|
||||
|
||||
class SendMagicLinkResponse(BaseModel):
|
||||
@@ -219,6 +226,8 @@ class VerifyMagicLinkResponse(BaseModel):
|
||||
tenant_subdomain: Optional[str] = None
|
||||
credits_granted: int = 0
|
||||
credit_status: str = "not_applicable" # "granted", "denied", "pending_review", "already_granted", "not_applicable"
|
||||
# Where the frontend should land after verifying (e.g. "/requests" for board sign-in).
|
||||
redirect_path: Optional[str] = None
|
||||
|
||||
|
||||
class UserPublic(BaseModel):
|
||||
|
||||
@@ -101,9 +101,19 @@ def _copy_segments(segments: List[Segment]) -> List[Segment]:
|
||||
|
||||
|
||||
def apply_suggestion(
|
||||
segments: List[Segment], suggestion: Suggestion
|
||||
segments: List[Segment],
|
||||
suggestion: Suggestion,
|
||||
undo_out: Optional[Dict[str, Any]] = None,
|
||||
) -> Optional[List[Segment]]:
|
||||
"""Apply one suggestion; returns new segments or None when stale."""
|
||||
"""Apply one suggestion; returns new segments or None when stale.
|
||||
|
||||
When ``undo_out`` is passed, it is populated with enough information to
|
||||
reverse this single suggestion later (mirrors the frontend's
|
||||
``SuggestionUndoInfo`` in ``autoCorrectApply.ts``), so a suggestion applied
|
||||
server-side (pre-apply / auto-approval) can still be undone per-item once
|
||||
the client has this data — independent of any other suggestions applied
|
||||
around it.
|
||||
"""
|
||||
if is_suggestion_stale(segments, suggestion):
|
||||
return None
|
||||
found = _find_segment_with_words(segments, suggestion.get("word_ids") or [])
|
||||
@@ -116,6 +126,7 @@ def apply_suggestion(
|
||||
result = _copy_segments(segments)
|
||||
seg = result[seg_index]
|
||||
words = seg["words"]
|
||||
prev_word_id = words[span_start - 1]["id"] if span_start > 0 else None
|
||||
op = suggestion.get("op")
|
||||
new_text = suggestion.get("new_text") or ""
|
||||
|
||||
@@ -153,18 +164,44 @@ def apply_suggestion(
|
||||
]
|
||||
words[span_end + 1 : span_end + 1] = new_words
|
||||
seg["text"] = _rebuild_text(words)
|
||||
if undo_out is not None:
|
||||
undo_out.update(
|
||||
{
|
||||
"op": op,
|
||||
"new_word_ids": [w["id"] for w in new_words],
|
||||
"removed_words": [],
|
||||
"segment_id": seg["id"],
|
||||
"prev_word_id": anchor["id"],
|
||||
"removed_segment": None,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
removed = words[span_start : span_end + 1]
|
||||
removed_snapshot = [dict(w) for w in removed]
|
||||
segment_snapshot = {**seg, "words": [dict(w) for w in words]}
|
||||
|
||||
if op == "delete":
|
||||
del words[span_start : span_start + len(removed)]
|
||||
removed_segment_info = None
|
||||
if not words:
|
||||
removed_segment_info = {"segment": segment_snapshot, "index": seg_index}
|
||||
del result[seg_index]
|
||||
else:
|
||||
seg["text"] = _rebuild_text(words)
|
||||
seg["start_time"] = words[0].get("start_time")
|
||||
seg["end_time"] = words[-1].get("end_time")
|
||||
if undo_out is not None:
|
||||
undo_out.update(
|
||||
{
|
||||
"op": op,
|
||||
"new_word_ids": [],
|
||||
"removed_words": removed_snapshot,
|
||||
"segment_id": segment_snapshot["id"],
|
||||
"prev_word_id": prev_word_id,
|
||||
"removed_segment": removed_segment_info,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
# replace
|
||||
@@ -195,6 +232,17 @@ def apply_suggestion(
|
||||
new_words.append(w)
|
||||
words[span_start : span_start + len(removed)] = new_words
|
||||
seg["text"] = _rebuild_text(words)
|
||||
if undo_out is not None:
|
||||
undo_out.update(
|
||||
{
|
||||
"op": "replace",
|
||||
"new_word_ids": [w["id"] for w in new_words],
|
||||
"removed_words": removed_snapshot,
|
||||
"segment_id": seg["id"],
|
||||
"prev_word_id": prev_word_id,
|
||||
"removed_segment": None,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -203,29 +251,35 @@ def apply_all_suggestions(
|
||||
) -> Dict[str, Any]:
|
||||
"""Accept-all with conflict resolution, mirroring the UI's on-load auto-apply.
|
||||
|
||||
Returns ``{"segments", "applied_ids", "rejected_ids", "stale_ids"}``.
|
||||
Returns ``{"segments", "applied_ids", "rejected_ids", "stale_ids", "undo_info"}``.
|
||||
``undo_info`` maps each applied suggestion id to its ``SuggestionUndoInfo``-shaped
|
||||
dict, so an applied suggestion can be individually reverted later.
|
||||
"""
|
||||
winners = set(pick_accept_all_winners(suggestions))
|
||||
current = segments
|
||||
applied: List[str] = []
|
||||
rejected: List[str] = []
|
||||
stale: List[str] = []
|
||||
undo_info: Dict[str, Any] = {}
|
||||
for s in suggestions:
|
||||
sid = s.get("id") or ""
|
||||
if sid not in winners:
|
||||
rejected.append(sid)
|
||||
continue
|
||||
result = apply_suggestion(current, s)
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(current, s, undo_out=undo)
|
||||
if result is None:
|
||||
stale.append(sid)
|
||||
continue
|
||||
current = result
|
||||
applied.append(sid)
|
||||
undo_info[sid] = undo
|
||||
return {
|
||||
"segments": current,
|
||||
"applied_ids": applied,
|
||||
"rejected_ids": rejected,
|
||||
"stale_ids": stale,
|
||||
"undo_info": undo_info,
|
||||
}
|
||||
|
||||
|
||||
@@ -261,6 +315,7 @@ def build_applied_segments(
|
||||
"segments": new_segments,
|
||||
"applied_ids": result["applied_ids"],
|
||||
"rejected_ids": result["rejected_ids"],
|
||||
"undo_info": result["undo_info"],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -99,6 +99,10 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
|
||||
"applied_suggestion_ids": result["applied_ids"],
|
||||
"rejected_suggestion_ids": result["rejected_ids"],
|
||||
"suggestions": ai_suggestions,
|
||||
# Per-suggestion undo info (SuggestionUndoInfo shape) so the review
|
||||
# UI can still revert an individual pre-applied correction even
|
||||
# though it never applied it client-side itself.
|
||||
"undo_info": result["undo_info"],
|
||||
"applied_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
updated["metadata"] = metadata
|
||||
|
||||
@@ -104,7 +104,11 @@ class DiscordNotificationService:
|
||||
return True
|
||||
|
||||
self.logger.info(f"Posting message to Discord webhook...")
|
||||
data = {"content": message}
|
||||
# Disable all mentions: message content can include user-supplied text
|
||||
# (artist/title in ops alerts), so an embedded @everyone / <@id> must not
|
||||
# trigger a Discord ping. (CWE-74 — output injection into a downstream
|
||||
# component.)
|
||||
data = {"content": message, "allowed_mentions": {"parse": []}}
|
||||
response = requests.post(url, json=data, timeout=30)
|
||||
response.raise_for_status()
|
||||
self.logger.info("Message posted to Discord successfully")
|
||||
|
||||
@@ -1779,6 +1779,77 @@ class EmailService:
|
||||
cc_emails=["gen@nomadkaraoke.com"],
|
||||
)
|
||||
|
||||
def send_community_track_live(
|
||||
self,
|
||||
to_email: str,
|
||||
message_content: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""Notify a voter that a community track they voted for is live on YouTube.
|
||||
|
||||
Sent (fanned out) to every up-voter when a requests-board pick publishes.
|
||||
No cc to gen@ — this is a bulk voter notification, not an ops email.
|
||||
"""
|
||||
safe_artist = sanitize_filename(artist) if artist else None
|
||||
safe_title = sanitize_filename(title) if title else None
|
||||
if safe_artist and safe_title:
|
||||
subject = t(locale, "emails.communityTrackLive.subject", artist=safe_artist, title=safe_title)
|
||||
else:
|
||||
subject = t(locale, "emails.communityTrackLive.subjectFallback")
|
||||
|
||||
extra_styles = """
|
||||
.content {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
"""
|
||||
content = f"""
|
||||
<div class="content">{html.escape(message_content)}</div>
|
||||
"""
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=message_content,
|
||||
)
|
||||
|
||||
def send_community_existing_version(
|
||||
self,
|
||||
to_email: str,
|
||||
message_content: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""Notify an up-voter that a requests-board pick was rejected because a good
|
||||
community karaoke version already exists (with a link to it)."""
|
||||
safe_artist = sanitize_filename(artist) if artist else None
|
||||
safe_title = sanitize_filename(title) if title else None
|
||||
if safe_artist and safe_title:
|
||||
subject = t(locale, "emails.communityExistingVersion.subject", artist=safe_artist, title=safe_title)
|
||||
else:
|
||||
subject = t(locale, "emails.communityExistingVersion.subjectFallback")
|
||||
|
||||
extra_styles = """
|
||||
.content {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
"""
|
||||
content = f"""
|
||||
<div class="content">{html.escape(message_content)}</div>
|
||||
"""
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=message_content,
|
||||
)
|
||||
|
||||
def send_made_for_you_order_confirmation(
|
||||
self,
|
||||
to_email: str,
|
||||
|
||||
@@ -10,15 +10,125 @@ can be swapped without changing the orchestration logic.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Any
|
||||
from typing import Dict, List, Optional, Any, TypedDict
|
||||
|
||||
from backend.services.encoding_errors import EncodingJobLostError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class GceEncodeResponse(TypedDict, total=False):
|
||||
"""Typed schema for the raw response the GCE encoding worker returns from
|
||||
``encode_videos`` (forwarded up from ``wait_for_completion`` /
|
||||
``submit_encoding_job``).
|
||||
|
||||
This is the *single shared definition* of the encode→publish seam contract:
|
||||
both the producer (``EncodingService.encode_videos``) and the consumer
|
||||
(``GCEEncodingBackend.encode``) annotate against it, so the shape can't
|
||||
silently drift between caller and callee. Mock drift on exactly this shape
|
||||
is what hid NOMAD-1632's Failure B (the "empty output_files" / stale-cache
|
||||
case was never in any test corpus). Golden fixtures under
|
||||
``backend/tests/fixtures/encoding/`` are validated against this schema.
|
||||
|
||||
Keys (``total=False`` — the worker omits most of them on the happy path):
|
||||
- ``status``: terminal/intermediate job state, e.g. ``"complete"``,
|
||||
``"failed"``, ``"running"``, ``"pending"``. ``encode_videos`` normalises a
|
||||
cached hit to ``"complete"``.
|
||||
- ``output_files``: GCS paths to the encoded finals, classified by
|
||||
:func:`classify_encoded_output`. The worker returns a **list**; a few
|
||||
legacy/short-name paths arrive as a ``dict`` keyed by format token, which
|
||||
``encode`` still tolerates. **May be an empty list** on a stale/cached job
|
||||
whose finals were deleted from GCS — a *recoverable* condition, NOT a
|
||||
partial/defective result (see the completeness guard in ``encode``).
|
||||
- ``progress``: 0–100 while running.
|
||||
- ``error``: present when ``status == "failed"``.
|
||||
"""
|
||||
|
||||
status: str
|
||||
output_files: List[str]
|
||||
progress: int
|
||||
error: str
|
||||
|
||||
|
||||
def classify_encoded_output(filename: str) -> Optional[str]:
|
||||
"""Classify a GCE-encoded output file by format, robust to artist/title text.
|
||||
|
||||
GCE finals are named ``<artist> - <title> (<format tag>).<ext>``, e.g.
|
||||
``Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4``. The
|
||||
format is entirely in the trailing parenthetical, so we match on THAT tag only
|
||||
— never the whole filename. Matching the whole filename is what caused the
|
||||
NOMAD-1632 gap: the title "Portrait of Jennie" contains "portrait", so the
|
||||
720p master matched the portrait-video branch (checked before "720p") and was
|
||||
never mapped to ``mp4_720p`` — it published to MP4/ + CDG/ with no 720p, and
|
||||
only the daily GDrive validator caught it. Any song whose artist/title contains
|
||||
a format word ("portrait", "720p", "4k", "lossless", "vocals", …) hit the same
|
||||
class of bug.
|
||||
|
||||
Returns a canonical token or ``None`` if the file isn't a recognised final:
|
||||
``mp4_4k_lossless``, ``mkv_4k``, ``mp4_4k_lossy``, ``mp4_720p``,
|
||||
``portrait_mp4``, ``with_vocals_mp4``, ``title_mov``, ``end_mov``,
|
||||
``cdg_zip``, ``txt_zip``.
|
||||
"""
|
||||
name = os.path.basename(filename)
|
||||
stem, ext = os.path.splitext(name)
|
||||
ext = ext.lower()
|
||||
|
||||
# System-generated short canonical names, e.g. jobs/{id}/finals/lossy_720p_mp4.mp4
|
||||
# (uploaded by _upload_results) and packages/cdg_zip.zip. They carry no artist/title
|
||||
# text, so an exact-stem match is unambiguous — and the redistribution flow reads
|
||||
# these back from GCS. Checked first so the underscore forms don't fall through.
|
||||
# (stem, ext) so a mismatched extension can't slip a stray file into a slot.
|
||||
short_name = {
|
||||
("lossless_4k_mp4", ".mp4"): "mp4_4k_lossless",
|
||||
("lossless_4k_mkv", ".mkv"): "mkv_4k",
|
||||
("lossy_4k_mp4", ".mp4"): "mp4_4k_lossy",
|
||||
("lossy_720p_mp4", ".mp4"): "mp4_720p",
|
||||
("portrait_1080x1920", ".mp4"): "portrait_mp4",
|
||||
("cdg_zip", ".zip"): "cdg_zip",
|
||||
("txt_zip", ".zip"): "txt_zip",
|
||||
}.get((stem.lower(), ext))
|
||||
if short_name:
|
||||
return short_name
|
||||
|
||||
# Otherwise the format tag is the LAST parenthetical group before the extension.
|
||||
# A file without that parenthetical isn't a recognised final. Every branch also
|
||||
# pins the expected extension, so a stray file whose artist/title happens to
|
||||
# contain a format word (e.g. "Artist 720p notes.txt") can't be misclassified
|
||||
# into a slot and then falsely satisfy the completeness guard.
|
||||
match = re.search(r"\(([^()]*)\)[^()]*$", name)
|
||||
if not match:
|
||||
return None
|
||||
tag = match.group(1).lower()
|
||||
|
||||
if "720p" in tag and ext == ".mp4":
|
||||
return "mp4_720p"
|
||||
if ("portrait" in tag or "1080x1920" in tag) and ext == ".mp4":
|
||||
return "portrait_mp4"
|
||||
if "lossless 4k" in tag:
|
||||
if ext == ".mkv":
|
||||
return "mkv_4k"
|
||||
if ext == ".mp4":
|
||||
return "mp4_4k_lossless"
|
||||
return None
|
||||
if "lossy 4k" in tag and ext == ".mp4":
|
||||
return "mp4_4k_lossy"
|
||||
if "with vocals" in tag and ext == ".mp4":
|
||||
return "with_vocals_mp4"
|
||||
if tag == "title" and ext == ".mov":
|
||||
return "title_mov"
|
||||
if tag == "end" and ext == ".mov":
|
||||
return "end_mov"
|
||||
if "cdg" in tag and ext == ".zip":
|
||||
return "cdg_zip"
|
||||
if "txt" in tag and ext == ".zip":
|
||||
return "txt_zip"
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class EncodingInput:
|
||||
"""
|
||||
@@ -380,34 +490,54 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
# We need dict like: {"mp4_4k_lossless": "path/...", "mp4_720p": "path/..."}
|
||||
if isinstance(raw_output_files, list):
|
||||
output_files = {}
|
||||
# Classify each returned final by its format tag (the trailing
|
||||
# parenthetical), NOT the whole filename — see classify_encoded_output.
|
||||
# Matching the whole filename misfiled the 720p of "Portrait of Jennie"
|
||||
# as the portrait video (NOMAD-1632).
|
||||
for path in raw_output_files:
|
||||
if not isinstance(path, str):
|
||||
continue
|
||||
filename = path.split("/")[-1] if "/" in path else path
|
||||
filename_lower = filename.lower()
|
||||
# Map filename patterns to output format keys
|
||||
# Files are named like "Artist - Title (Final Karaoke Lossless 4k).mp4"
|
||||
if "lossless 4k" in filename_lower:
|
||||
if filename.endswith(".mkv"):
|
||||
output_files["mkv_4k"] = path
|
||||
else:
|
||||
output_files["mp4_4k_lossless"] = path
|
||||
elif "lossy 4k" in filename_lower:
|
||||
output_files["mp4_4k_lossy"] = path
|
||||
elif "portrait" in filename_lower:
|
||||
output_files["portrait_mp4"] = path
|
||||
elif "720p" in filename_lower:
|
||||
output_files["mp4_720p"] = path
|
||||
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
|
||||
output_files["with_vocals_mp4"] = path
|
||||
elif filename_lower.endswith("(title).mov"):
|
||||
output_files["title_mov"] = path
|
||||
elif filename_lower.endswith("(end).mov"):
|
||||
output_files["end_mov"] = path
|
||||
key = classify_encoded_output(path)
|
||||
if key:
|
||||
output_files[key] = path
|
||||
self.logger.info(f"Converted output_files list to dict: {output_files}")
|
||||
else:
|
||||
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
|
||||
|
||||
# Completeness guard (defense-in-depth): a worker that returns SOME formats
|
||||
# but not every one we requested — the title-collision mapping bug that
|
||||
# dropped the 720p (NOMAD-1632, fixed above by classify_encoded_output), a
|
||||
# stale-wheel fallback VM, or an output lost before the worker's
|
||||
# glob/upload — must NOT sail through to distribution and publish an
|
||||
# incomplete public release, leaving a sequence gap the daily GDrive
|
||||
# validator only flags ~24h later. Fail loud so the orchestrator errors the
|
||||
# job (retried on a healthy worker) and the alert fires immediately.
|
||||
#
|
||||
# IMPORTANT: only fire on a PARTIAL result. An EMPTY output_files means the
|
||||
# worker returned nothing at all — typically a stale GCE job cache whose
|
||||
# finals were deleted from GCS (admin reset / re-run). That is a normal,
|
||||
# recoverable condition the orchestrator already handles: it downloads zero
|
||||
# files, raises a "stale" RuntimeError from _download_gce_encoded_files, and
|
||||
# re-encodes under a fresh job id. Guarding the empty case here would
|
||||
# short-circuit that recovery and hard-fail real jobs (regression fixed in
|
||||
# v0.222.3).
|
||||
requested_formats = encoding_config.get("formats", [])
|
||||
missing_formats = [f for f in requested_formats if not output_files.get(f)]
|
||||
if output_files and missing_formats:
|
||||
error_message = (
|
||||
f"Encoder returned an incomplete result: missing {missing_formats} "
|
||||
f"(requested {requested_formats}, got {sorted(output_files.keys())}). "
|
||||
"Refusing to publish a partial release."
|
||||
)
|
||||
self.logger.error(f"[job:{job_id}] {error_message}")
|
||||
return EncodingOutput(
|
||||
success=False,
|
||||
error_message=error_message,
|
||||
output_files=output_files,
|
||||
encoding_time_seconds=encoding_time,
|
||||
encoding_backend=self.name,
|
||||
)
|
||||
|
||||
return EncodingOutput(
|
||||
success=True,
|
||||
lossless_4k_mp4_path=output_files.get("mp4_4k_lossless"),
|
||||
|
||||
@@ -21,10 +21,15 @@ import os
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Awaitable, Callable, Optional, Dict, Any, AsyncIterator
|
||||
from typing import Awaitable, Callable, Optional, Dict, Any, AsyncIterator, TYPE_CHECKING
|
||||
|
||||
import aiohttp
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# Shared seam contract. Type-only import (no runtime cost, no import cycle —
|
||||
# encoding_interface imports encoding_service lazily inside methods).
|
||||
from backend.services.encoding_interface import GceEncodeResponse
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.encoding_errors import (
|
||||
ENCODING_RESTART_FAILURE_CODE,
|
||||
@@ -904,7 +909,7 @@ class EncodingService:
|
||||
output_gcs_path: str,
|
||||
encoding_config: Optional[Dict[str, Any]] = None,
|
||||
progress_callback=None,
|
||||
) -> Dict[str, Any]:
|
||||
) -> "GceEncodeResponse":
|
||||
"""
|
||||
Submit encoding job and wait for completion.
|
||||
|
||||
|
||||
@@ -113,6 +113,25 @@ class FirestoreService:
|
||||
except Exception as e:
|
||||
logger.error(f"Error updating job status {job_id}: {e}")
|
||||
raise
|
||||
|
||||
# Incident-hardening D1: near-real-time alert on ANY transition to FAILED.
|
||||
# The spike-based error monitor is blind to a novel low-volume failure
|
||||
# (rolling_avg==0 → never a spike), so a brand-new error on a couple of
|
||||
# jobs can go unnoticed. This is the universal net. Best-effort: it must
|
||||
# never turn a successful status write into a failure, hence the guard.
|
||||
if status == JobStatus.FAILED:
|
||||
try:
|
||||
from backend.services.ops_alerts import notify_job_failed
|
||||
|
||||
notify_job_failed(
|
||||
db=self.db,
|
||||
collection=self.collection,
|
||||
job_id=job_id,
|
||||
message=message,
|
||||
additional_fields=additional_fields,
|
||||
)
|
||||
except Exception as alert_exc: # noqa: BLE001
|
||||
logger.warning(f"Failure alert for job {job_id} did not send: {alert_exc}")
|
||||
|
||||
def list_jobs(
|
||||
self,
|
||||
|
||||
@@ -20,12 +20,21 @@ logger = logging.getLogger(__name__)
|
||||
GDRIVE_VALIDATOR_URL = os.environ.get("GDRIVE_VALIDATOR_URL", "")
|
||||
|
||||
|
||||
def trigger_gdrive_validation() -> dict | None:
|
||||
def trigger_gdrive_validation(
|
||||
brand_code: str | None = None, expect_cdg: bool = False
|
||||
) -> dict | None:
|
||||
"""
|
||||
Invoke the GDrive validator Cloud Function.
|
||||
|
||||
Uses the backend service account's OIDC token for authentication.
|
||||
|
||||
Args:
|
||||
brand_code: Optional brand code of the just-published track. When set, the
|
||||
validator additionally verifies this track is present in all expected
|
||||
folders same-run (incident-hardening D2).
|
||||
expect_cdg: Whether the just-published track produced a CDG package (so the
|
||||
validator requires the CDG folder for it). Ignored without brand_code.
|
||||
|
||||
Returns:
|
||||
Parsed JSON response from the function, or None on error.
|
||||
"""
|
||||
@@ -41,6 +50,7 @@ def trigger_gdrive_validation() -> dict | None:
|
||||
response = requests.post(
|
||||
GDRIVE_VALIDATOR_URL,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"brand_code": brand_code, "expect_cdg": expect_cdg} if brand_code else None,
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
@@ -219,6 +219,63 @@ class JobNotificationService:
|
||||
logger.exception(f"Error sending YouTube upload notification for job {job_id}: {e}")
|
||||
return False
|
||||
|
||||
async def send_community_track_live_email(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""Notify one voter that a community track they voted for is now live.
|
||||
|
||||
Returns True if the email was sent. Best-effort: swallows errors so a
|
||||
single bad address never aborts the voter fan-out.
|
||||
"""
|
||||
if not ENABLE_AUTO_EMAILS:
|
||||
logger.info("Auto emails disabled, skipping community-track-live notification")
|
||||
return False
|
||||
if not to_email:
|
||||
return False
|
||||
try:
|
||||
user_locale = self._get_user_locale(to_email)
|
||||
message_content = self.template_service.render_community_track_live(
|
||||
artist=artist, title=title, youtube_url=youtube_url, locale=user_locale,
|
||||
)
|
||||
return self.email_service.send_community_track_live(
|
||||
to_email=to_email, message_content=message_content,
|
||||
artist=artist, title=title, locale=user_locale,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error sending community-track-live email to {_mask_email(to_email)}: {e}")
|
||||
return False
|
||||
|
||||
async def send_community_existing_version_email(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""Notify one up-voter that their request was rejected because a community
|
||||
karaoke version already exists (linking them to it). Best-effort."""
|
||||
if not ENABLE_AUTO_EMAILS:
|
||||
logger.info("Auto emails disabled, skipping community-existing-version notification")
|
||||
return False
|
||||
if not to_email:
|
||||
return False
|
||||
try:
|
||||
user_locale = self._get_user_locale(to_email)
|
||||
message_content = self.template_service.render_community_existing_version(
|
||||
artist=artist, title=title, youtube_url=youtube_url, locale=user_locale,
|
||||
)
|
||||
return self.email_service.send_community_existing_version(
|
||||
to_email=to_email, message_content=message_content,
|
||||
artist=artist, title=title, locale=user_locale,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error sending community-existing-version email to {_mask_email(to_email)}: {e}")
|
||||
return False
|
||||
|
||||
async def send_action_reminder_email(
|
||||
self,
|
||||
job_id: str,
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Near-real-time operational alerting (incident-hardening D1 + G1 channel).
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
The production error monitor (``backend/services/error_monitor``) is
|
||||
**spike-based**: a pattern only alerts when its current count exceeds a rolling
|
||||
average by a multiplier *and* clears a minimum-count floor. A brand-new error
|
||||
has ``rolling_avg == 0`` → it is mathematically never a spike, so a novel,
|
||||
low-volume failure is invisible to it. That is exactly how incident NOMAD-1632's
|
||||
follow-on outage (2 jobs failing with a never-before-seen error string) went
|
||||
unnoticed until a human spotted failed jobs in the UI.
|
||||
|
||||
This module is the **universal net**: the moment *any* job transitions to
|
||||
``FAILED`` we emit an immediate Discord alert, independent of the spike detector,
|
||||
de-duplicated by a normalized error signature so a burst collapses into one
|
||||
alert. Novel error signatures always alert regardless of count.
|
||||
|
||||
It also exposes :func:`send_ops_alert`, a generic best-effort sender reused by
|
||||
the publish-completeness shadow invariant (G1).
|
||||
|
||||
Everything here is **best-effort**: any failure to alert is swallowed and
|
||||
logged. It must never raise into — nor add a failure mode to — the status write
|
||||
that triggered it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Secret Manager name of the ops/alert Discord webhook (same channel the startup
|
||||
# credential-validation alert uses — see backend/main.py).
|
||||
_ALERT_WEBHOOK_SECRET = "discord-alert-webhook"
|
||||
|
||||
# Firestore collection used to de-dupe/throttle failure alerts by signature.
|
||||
_DEDUP_COLLECTION = "ops_failure_alerts"
|
||||
|
||||
# Collapse repeat alerts for the same error signature within this window into a
|
||||
# single Discord message (the burst is counted, not re-sent). Override with
|
||||
# FAILURE_ALERT_THROTTLE_MINUTES.
|
||||
_DEFAULT_THROTTLE_MINUTES = 30
|
||||
|
||||
# Environments whose failures we do NOT page on (intentional test/dev failures
|
||||
# would otherwise be noise). Production + unlabeled jobs always alert. Override
|
||||
# with FAILURE_ALERT_SKIP_ENVIRONMENTS (comma-separated).
|
||||
_DEFAULT_SKIP_ENVIRONMENTS = {"test", "development"}
|
||||
|
||||
|
||||
def _is_enabled() -> bool:
|
||||
"""Only alert from a deployed environment.
|
||||
|
||||
Local runs and the test suite have no ``K_SERVICE`` / non-production
|
||||
``ENVIRONMENT`` (see :func:`backend.config.is_production`), so this short
|
||||
circuits before any Secret Manager or Discord call — keeping unit tests
|
||||
silent and fast.
|
||||
"""
|
||||
if os.environ.get("FAILURE_ALERTS_ENABLED", "").lower() in ("1", "true", "yes"):
|
||||
return True
|
||||
try:
|
||||
from backend.config import is_production
|
||||
|
||||
return is_production()
|
||||
except Exception: # noqa: BLE001 - never let config import break a status write
|
||||
return False
|
||||
|
||||
|
||||
def _throttle_minutes() -> int:
|
||||
try:
|
||||
return int(os.environ.get("FAILURE_ALERT_THROTTLE_MINUTES", _DEFAULT_THROTTLE_MINUTES))
|
||||
except (TypeError, ValueError):
|
||||
return _DEFAULT_THROTTLE_MINUTES
|
||||
|
||||
|
||||
def _skip_environments() -> set[str]:
|
||||
raw = os.environ.get("FAILURE_ALERT_SKIP_ENVIRONMENTS")
|
||||
if raw is None:
|
||||
return set(_DEFAULT_SKIP_ENVIRONMENTS)
|
||||
return {e.strip().lower() for e in raw.split(",") if e.strip()}
|
||||
|
||||
|
||||
def _get_webhook_url() -> Optional[str]:
|
||||
"""Resolve the ops-alert Discord webhook (cached via settings.get_secret)."""
|
||||
try:
|
||||
from backend.config import settings
|
||||
|
||||
if hasattr(settings, "get_secret"):
|
||||
return settings.get_secret(_ALERT_WEBHOOK_SECRET)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug("ops_alerts: could not resolve webhook: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def send_ops_alert(message: str) -> bool:
|
||||
"""Post a plaintext ops alert to the Discord alert channel. Best-effort.
|
||||
|
||||
Returns True if the message was sent, False otherwise (disabled, no webhook,
|
||||
or a delivery error). Never raises.
|
||||
"""
|
||||
try:
|
||||
if not _is_enabled():
|
||||
logger.debug("ops_alerts: disabled (not a deployed environment); skipping")
|
||||
return False
|
||||
webhook = _get_webhook_url()
|
||||
if not webhook:
|
||||
logger.debug("ops_alerts: no webhook configured; skipping")
|
||||
return False
|
||||
from backend.services.discord_service import get_discord_notification_service
|
||||
|
||||
service = get_discord_notification_service(webhook_url=webhook)
|
||||
return service.post_message(message, webhook_url=webhook)
|
||||
except Exception as exc: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("ops_alerts: failed to send alert: %s", exc)
|
||||
return False
|
||||
|
||||
|
||||
def _signature(error_message: str) -> str:
|
||||
"""Stable fingerprint for an error string (reuses the error-monitor normalizer)."""
|
||||
try:
|
||||
from backend.services.error_monitor.normalizer import (
|
||||
compute_pattern_hash,
|
||||
normalize_message,
|
||||
)
|
||||
|
||||
return compute_pattern_hash("karaoke-job", normalize_message(error_message or ""))
|
||||
except Exception: # noqa: BLE001
|
||||
# Fallback: hash the raw string so dedup still works if the normalizer
|
||||
# import fails for any reason.
|
||||
import hashlib
|
||||
|
||||
return hashlib.sha256((error_message or "").encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, int, Any]:
|
||||
"""Decide whether to send, WITHOUT yet acknowledging delivery.
|
||||
|
||||
Returns ``(should_send, is_novel, suppressed_since_last, doc_ref)``:
|
||||
* ``should_send`` — emit a Discord alert this time.
|
||||
* ``is_novel`` — we have never seen this signature before.
|
||||
* ``suppressed_since_last`` — how many failures were collapsed (throttled)
|
||||
since the last *successful* alert for this signature.
|
||||
* ``doc_ref`` — the dedup doc, passed to :func:`_mark_alerted` **only after a
|
||||
successful send** so a failed Discord delivery does NOT advance the
|
||||
throttle window (which would suppress the next real failure). ``None`` if
|
||||
Firestore was unreachable.
|
||||
|
||||
This records ``first_seen`` / ``total_count`` (and, when throttled, the
|
||||
suppressed counter) but deliberately does NOT touch ``last_alerted_at`` — that
|
||||
is the delivery acknowledgement, set separately once the alert actually sends.
|
||||
|
||||
Best-effort: on any Firestore error we default to *send* (fail open — an extra
|
||||
alert is far better than a missed outage). NOTE: the ``get()`` + ``update()``
|
||||
are not transactional, so two truly-concurrent failures of the same signature
|
||||
could each send once. That's an acceptable trade (a duplicate alert is
|
||||
harmless; a missed one is not), so we don't pay for a transaction here.
|
||||
"""
|
||||
try:
|
||||
doc_ref = db.collection(_DEDUP_COLLECTION).document(signature)
|
||||
snap = doc_ref.get()
|
||||
now_iso = now.isoformat()
|
||||
if not snap.exists:
|
||||
# Create the record but leave last_alerted_at unset — it's stamped by
|
||||
# _mark_alerted only if the send succeeds.
|
||||
doc_ref.set(
|
||||
{
|
||||
"signature": signature,
|
||||
"first_seen": now_iso,
|
||||
"last_alerted_at": None,
|
||||
"total_count": 1,
|
||||
"alert_count": 0,
|
||||
"suppressed_since_last": 0,
|
||||
}
|
||||
)
|
||||
return True, True, 0, doc_ref
|
||||
|
||||
data = snap.to_dict() or {}
|
||||
last_alerted_raw = data.get("last_alerted_at")
|
||||
within_window = False
|
||||
if last_alerted_raw:
|
||||
try:
|
||||
last_alerted = datetime.fromisoformat(last_alerted_raw)
|
||||
within_window = (now - last_alerted) < timedelta(minutes=_throttle_minutes())
|
||||
except (TypeError, ValueError):
|
||||
within_window = False
|
||||
|
||||
if within_window:
|
||||
# Collapse: count it but don't re-page.
|
||||
doc_ref.update(
|
||||
{
|
||||
"total_count": (data.get("total_count", 0) or 0) + 1,
|
||||
"suppressed_since_last": (data.get("suppressed_since_last", 0) or 0) + 1,
|
||||
}
|
||||
)
|
||||
return False, False, 0, doc_ref
|
||||
|
||||
doc_ref.update({"total_count": (data.get("total_count", 0) or 0) + 1})
|
||||
suppressed = data.get("suppressed_since_last", 0) or 0
|
||||
return True, False, suppressed, doc_ref
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug("ops_alerts: dedup lookup failed (%s); defaulting to send", exc)
|
||||
return True, False, 0, None
|
||||
|
||||
|
||||
def _mark_alerted(doc_ref: Any, now: datetime) -> None:
|
||||
"""Acknowledge a successful send: advance the throttle window + reset counters.
|
||||
|
||||
Called ONLY after :func:`send_ops_alert` returns True. Best-effort.
|
||||
"""
|
||||
if doc_ref is None:
|
||||
return
|
||||
try:
|
||||
snap = doc_ref.get()
|
||||
data = snap.to_dict() or {} if snap.exists else {}
|
||||
doc_ref.update(
|
||||
{
|
||||
"last_alerted_at": now.isoformat(),
|
||||
"alert_count": (data.get("alert_count", 0) or 0) + 1,
|
||||
"suppressed_since_last": 0,
|
||||
}
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug("ops_alerts: could not record alert delivery: %s", exc)
|
||||
|
||||
|
||||
def notify_job_failed(
|
||||
db: Any,
|
||||
collection: str,
|
||||
job_id: str,
|
||||
message: Optional[str] = None,
|
||||
additional_fields: Optional[dict] = None,
|
||||
) -> bool:
|
||||
"""Emit a near-real-time alert for a job that just transitioned to FAILED.
|
||||
|
||||
Invoked from the single status-write chokepoint
|
||||
(:meth:`FirestoreService.update_job_status`). ``db`` is the caller's existing
|
||||
Firestore client (reused to avoid a second client / circular import);
|
||||
``collection`` is the jobs collection so we can enrich the alert with the
|
||||
job's artist/title/environment. Best-effort; never raises.
|
||||
|
||||
Returns True if an alert was sent.
|
||||
"""
|
||||
try:
|
||||
if not _is_enabled():
|
||||
return False
|
||||
|
||||
# Enrich from the job doc (best-effort). We only just wrote it, so this
|
||||
# is a single extra read on the rare FAILED path.
|
||||
artist = title = environment = brand_code = None
|
||||
error_message = (additional_fields or {}).get("error_message") or message or ""
|
||||
try:
|
||||
snap = db.collection(collection).document(job_id).get()
|
||||
if snap.exists:
|
||||
job = snap.to_dict() or {}
|
||||
artist = job.get("artist")
|
||||
title = job.get("title")
|
||||
meta = job.get("request_metadata") or {}
|
||||
environment = meta.get("environment")
|
||||
state = job.get("state_data") or {}
|
||||
brand_code = state.get("brand_code")
|
||||
if not error_message:
|
||||
error_message = job.get("error_message") or ""
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug("ops_alerts: job enrichment read failed: %s", exc)
|
||||
|
||||
if environment and environment.lower() in _skip_environments():
|
||||
logger.debug("ops_alerts: skipping failure alert for %s env job %s", environment, job_id)
|
||||
return False
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
signature = _signature(error_message)
|
||||
should_send, is_novel, suppressed, doc_ref = _should_alert(db, signature, now)
|
||||
if not should_send:
|
||||
return False
|
||||
|
||||
track = " - ".join(p for p in (artist, title) if p) or "(unknown track)"
|
||||
lines = [
|
||||
"🔴 **Job failed** — near-real-time alert",
|
||||
f"**Job:** `{job_id}`" + (f" ({brand_code})" if brand_code else ""),
|
||||
f"**Track:** {track}",
|
||||
]
|
||||
if environment:
|
||||
lines.append(f"**Env:** {environment}")
|
||||
if is_novel:
|
||||
lines.append("🆕 **First time we've ever seen this error signature.**")
|
||||
elif suppressed:
|
||||
lines.append(f"_(Collapsed {suppressed} earlier occurrence(s) of this signature.)_")
|
||||
err = (error_message or "").strip()
|
||||
if err:
|
||||
if len(err) > 1500:
|
||||
err = err[:1500] + " …[truncated]"
|
||||
lines.append(f"**Error:** ```{err}```")
|
||||
|
||||
sent = send_ops_alert("\n".join(lines))
|
||||
# Only advance the throttle window once delivery actually succeeded — a
|
||||
# failed send must NOT suppress the next occurrence of this signature.
|
||||
if sent:
|
||||
_mark_alerted(doc_ref, now)
|
||||
return sent
|
||||
except Exception as exc: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("ops_alerts: notify_job_failed failed: %s", exc)
|
||||
return False
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Publish-boundary completeness invariant (incident-hardening G1), shadow-first.
|
||||
|
||||
Incident NOMAD-1632 published a public track to Google Drive **missing its 720p
|
||||
variant** while the pipeline reported success: ``GCEEncodingBackend.encode()``
|
||||
misclassified ``… (Final Karaoke Lossy 720p).mp4`` (title contained "Portrait")
|
||||
so ``mp4_720p`` was never set, and ``upload_to_public_share`` *silently skipped*
|
||||
the ``None`` path. Nothing inline noticed; the daily validator caught it ~24h
|
||||
later.
|
||||
|
||||
This module computes, at the publish boundary, the set of outputs a public
|
||||
GDrive release *should* have shipped and compares it against what was actually
|
||||
distributed (``result.gdrive_files``). The orchestrator logs + alerts on any
|
||||
shortfall **in shadow mode** (never fails the job) — the right altitude for the
|
||||
check (publish-aware of what *should* ship) and the rollout discipline the
|
||||
original fix skipped.
|
||||
|
||||
The compute function is intentionally pure (config + result in, list of missing
|
||||
outputs out) so it is trivially unit-testable and side-effect free.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# gdrive_files keys produced by GDriveService.upload_to_public_share(), mapped to
|
||||
# a human-readable label for alerts.
|
||||
_LOSSY_4K_KEY = "mp4"
|
||||
_720P_KEY = "mp4_720p"
|
||||
_CDG_KEY = "cdg"
|
||||
|
||||
_LABELS = {
|
||||
_LOSSY_4K_KEY: "lossy 4K MP4",
|
||||
_720P_KEY: "720p MP4",
|
||||
_CDG_KEY: "CDG zip",
|
||||
}
|
||||
|
||||
|
||||
def expected_gdrive_outputs(config: Any, result: Any) -> list[str]:
|
||||
"""The gdrive_files keys a public-share release is expected to contain.
|
||||
|
||||
Always the lossy 4K MP4 and the 720p MP4. The CDG zip is expected only when
|
||||
the job actually **produced** a CDG package (``result.final_karaoke_cdg_zip``
|
||||
is set). Keying CDG off ``config.enable_cdg`` alone false-fires on legitimate
|
||||
skips: a lyric-less track (``_lrc_has_lyrics_content()`` False) is packaged
|
||||
without a CDG even when ``enable_cdg`` is True, so the upload omits ``cdg`` by
|
||||
design. Basing the expectation on the produced artifact still catches the real
|
||||
fault we care about — a CDG that WAS made but never distributed.
|
||||
"""
|
||||
expected = [_LOSSY_4K_KEY, _720P_KEY]
|
||||
if getattr(result, "final_karaoke_cdg_zip", None):
|
||||
expected.append(_CDG_KEY)
|
||||
return expected
|
||||
|
||||
|
||||
def compute_publish_shortfall(config: Any, result: Any) -> list[str]:
|
||||
"""Return human-readable labels for expected-but-missing public outputs.
|
||||
|
||||
Empty list == complete (or not a public-share release). Only meaningful for
|
||||
the public GDrive distribution path (``config.gdrive_folder_id`` set); returns
|
||||
``[]`` for any other job so callers can invoke it unconditionally.
|
||||
"""
|
||||
if not getattr(config, "gdrive_folder_id", None):
|
||||
return []
|
||||
|
||||
distributed = getattr(result, "gdrive_files", None) or {}
|
||||
missing: list[str] = []
|
||||
for key in expected_gdrive_outputs(config, result):
|
||||
# A key is satisfied only if present AND truthy (an empty id/url means the
|
||||
# upload didn't actually land).
|
||||
if not distributed.get(key):
|
||||
missing.append(_LABELS.get(key, key))
|
||||
return missing
|
||||
@@ -0,0 +1,571 @@
|
||||
"""
|
||||
Service for the public song-request voting board.
|
||||
|
||||
Phase 1 responsibilities:
|
||||
- submit a request (auto-correct artist/title via match_judge, dedupe re-submissions)
|
||||
- list the ranked board (+ recently published), annotated with the viewer's vote
|
||||
- cast one vote per person per UTC calendar day (up/down, movable within the day)
|
||||
|
||||
The one-vote-per-day rule is enforced structurally: a user's vote for a given day lives
|
||||
at a fixed doc id ({email}__{YYYY-MM-DD}), so there can only ever be one.
|
||||
"""
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
from google.api_core import exceptions as gcloud_exceptions
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.models.song_request import DailyCommunityPick, SongRequest, Vote
|
||||
from backend.services.match_judge.classifier import normalize_for_match
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
REQUESTS_COLLECTION = "song_requests"
|
||||
VOTES_COLLECTION = "song_request_votes"
|
||||
# Per-UTC-day lock/ledger for the daily free-track picker (Phase 2).
|
||||
DAILY_PICK_COLLECTION = "daily_community_pick"
|
||||
|
||||
# Soft anti-spam cap on how many distinct requests one person can submit per day.
|
||||
MAX_SUBMISSIONS_PER_DAY = 15
|
||||
# How many published tracks to surface in the "already made" section.
|
||||
PUBLISHED_LIMIT = 20
|
||||
# Hard ceiling on active requests fetched for ranking (board is small; sort in Python).
|
||||
ACTIVE_FETCH_LIMIT = 500
|
||||
|
||||
|
||||
class SubmissionRateLimited(Exception):
|
||||
"""Raised when a user exceeds MAX_SUBMISSIONS_PER_DAY."""
|
||||
|
||||
|
||||
class RequestNotFound(Exception):
|
||||
"""Raised when voting on a non-existent or non-votable request."""
|
||||
|
||||
|
||||
def _utc_today() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _dedupe_key(artist: str, title: str) -> str:
|
||||
return f"{normalize_for_match(artist)}|{normalize_for_match(title)}"
|
||||
|
||||
|
||||
class SongRequestService:
|
||||
"""Firestore-backed logic for the requests voting board."""
|
||||
|
||||
def __init__(self):
|
||||
self.settings = get_settings()
|
||||
self.db = firestore.Client(project=self.settings.google_cloud_project)
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Submit
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
async def submit_request(
|
||||
self, user_email: str, artist: str, title: str
|
||||
) -> Tuple[SongRequest, bool, str, str]:
|
||||
"""Create (or resurface) a request for artist/title.
|
||||
|
||||
Returns (request, already_existed, canonical_artist, canonical_title).
|
||||
Auto-corrects artist/title via match_judge; a re-submission of the same song
|
||||
(by dedupe key) counts as an up-vote for the existing open request.
|
||||
"""
|
||||
email = user_email.lower()
|
||||
artist = artist.strip()
|
||||
title = title.strip()
|
||||
|
||||
# Auto-correct / canonicalize using the same judge the job-submission flow uses.
|
||||
canonical_artist, canonical_title = await self._canonicalize(artist, title)
|
||||
|
||||
key = _dedupe_key(canonical_artist, canonical_title)
|
||||
|
||||
existing = self._find_open_by_key(key)
|
||||
if existing is not None:
|
||||
# Same song already requested — treat this as an up-vote and resurface it.
|
||||
# Idempotent: cast_vote toggles OFF a matching same-request/same-direction
|
||||
# vote, so re-submitting a song you already up-voted today would REMOVE the
|
||||
# vote. Only cast when the user isn't already up-voting this request today.
|
||||
current = self.get_daily_vote(email)
|
||||
if not (current and current.request_id == existing.id and current.value == 1):
|
||||
self.cast_vote(email, existing.id, "up")
|
||||
refreshed = self.get_request(existing.id) or existing
|
||||
return refreshed, True, canonical_artist, canonical_title
|
||||
|
||||
# Enforce the per-day submission cap (cheap: equality query + in-Python day filter).
|
||||
if self._submissions_today(email) >= MAX_SUBMISSIONS_PER_DAY:
|
||||
raise SubmissionRateLimited()
|
||||
|
||||
request = SongRequest(
|
||||
id=str(uuid.uuid4()),
|
||||
artist=canonical_artist,
|
||||
title=canonical_title,
|
||||
artist_raw=artist,
|
||||
title_raw=title,
|
||||
dedupe_key=key,
|
||||
submitted_by=email,
|
||||
source="human",
|
||||
status="open",
|
||||
vote_count=0,
|
||||
)
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request.id).set(
|
||||
request.model_dump(mode="json")
|
||||
)
|
||||
logger.info("song request created id=%s by=%s key=%s", request.id, email, key)
|
||||
|
||||
# The submitter's endorsement counts as their vote for today.
|
||||
self.cast_vote(email, request.id, "up")
|
||||
return self.get_request(request.id) or request, False, canonical_artist, canonical_title
|
||||
|
||||
async def _canonicalize(self, artist: str, title: str) -> Tuple[str, str]:
|
||||
"""Best-effort artist/title tidy via match_judge; never blocks submission."""
|
||||
try:
|
||||
from backend.services.match_judge.service import judge_match
|
||||
|
||||
verdict = await judge_match(artist, title, stage="full")
|
||||
# Only adopt the canonical form when the judge is confident and it's a real
|
||||
# song (cosmetic/content). Ambiguous/none → keep what the user typed.
|
||||
if verdict.confident and verdict.kind in ("cosmetic", "content"):
|
||||
ca = verdict.canonical_artist.strip() or artist
|
||||
ct = verdict.canonical_title.strip() or title
|
||||
return ca, ct
|
||||
except Exception:
|
||||
logger.warning("match_judge canonicalize failed; using raw input", exc_info=True)
|
||||
return artist, title
|
||||
|
||||
def _find_open_by_key(self, key: str) -> Optional[SongRequest]:
|
||||
# Single equality filter on dedupe_key (auto single-field index) + filter status
|
||||
# in Python — avoids needing a composite index. A dedupe_key maps to at most a
|
||||
# handful of docs (usually one open + maybe past published ones).
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("dedupe_key", "==", key)
|
||||
)
|
||||
for doc in query.stream():
|
||||
req = SongRequest(**doc.to_dict())
|
||||
if req.status == "open":
|
||||
return req
|
||||
return None
|
||||
|
||||
def _submissions_today(self, email: str) -> int:
|
||||
today = _utc_today()
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("submitted_by", "==", email)
|
||||
)
|
||||
return sum(
|
||||
1
|
||||
for doc in query.stream()
|
||||
if str(doc.to_dict().get("created_at", "")).startswith(today)
|
||||
)
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Read
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
def get_request(self, request_id: str) -> Optional[SongRequest]:
|
||||
doc = self.db.collection(REQUESTS_COLLECTION).document(request_id).get()
|
||||
if doc.exists:
|
||||
return SongRequest(**doc.to_dict())
|
||||
return None
|
||||
|
||||
def list_active(self) -> list[SongRequest]:
|
||||
"""Open requests, ranked by net votes desc then oldest-first."""
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("status", "==", "open")
|
||||
).limit(ACTIVE_FETCH_LIMIT)
|
||||
items = [SongRequest(**doc.to_dict()) for doc in query.stream()]
|
||||
items.sort(key=lambda r: (-r.vote_count, r.created_at))
|
||||
return items
|
||||
|
||||
def list_published(self) -> list[SongRequest]:
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("status", "==", "published")
|
||||
).limit(ACTIVE_FETCH_LIMIT)
|
||||
items = [SongRequest(**doc.to_dict()) for doc in query.stream()]
|
||||
items.sort(key=lambda r: (r.picked_at or r.updated_at), reverse=True)
|
||||
return items[:PUBLISHED_LIMIT]
|
||||
|
||||
def get_daily_vote(self, email: str) -> Optional[Vote]:
|
||||
"""The caller's vote for today, if any."""
|
||||
doc = (
|
||||
self.db.collection(VOTES_COLLECTION)
|
||||
.document(self._vote_doc_id(email.lower(), _utc_today()))
|
||||
.get()
|
||||
)
|
||||
if doc.exists:
|
||||
return Vote(**doc.to_dict())
|
||||
return None
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Vote
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _vote_doc_id(email: str, day: str) -> str:
|
||||
return f"{email}__{day}"
|
||||
|
||||
def cast_vote(self, user_email: str, request_id: str, direction: str) -> Optional[Vote]:
|
||||
"""Cast/move/undo the caller's single daily vote.
|
||||
|
||||
Rules (one vote total per person per UTC day):
|
||||
- No vote yet today -> record it, apply +/-1 to the request.
|
||||
- Same request+dir -> toggle it OFF (frees today's vote).
|
||||
- Different request or direction -> move it (reverse old, apply new).
|
||||
|
||||
Returns the resulting Vote, or None if it was toggled off. Runs in a
|
||||
Firestore transaction so the vote doc and denormalized counts never drift.
|
||||
"""
|
||||
email = user_email.lower()
|
||||
value = 1 if direction == "up" else -1
|
||||
day = _utc_today()
|
||||
vote_ref = self.db.collection(VOTES_COLLECTION).document(self._vote_doc_id(email, day))
|
||||
target_ref = self.db.collection(REQUESTS_COLLECTION).document(request_id)
|
||||
|
||||
transaction = self.db.transaction()
|
||||
return _cast_vote_txn(transaction, self, vote_ref, target_ref, request_id, email, day, value)
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Phase 2 — daily picker, ownership handoff, publish fan-out
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
# --- per-day lock / ledger ---
|
||||
|
||||
def claim_day(self, date: str) -> Tuple[DailyCommunityPick, bool]:
|
||||
"""Atomically claim the day for the daily picker.
|
||||
|
||||
Returns (lock, claimed_new). ``claimed_new`` is True only for the run that
|
||||
created the lock; every other (retried/overlapping) run gets the existing
|
||||
lock and False. This is what enforces "one free track per day, total".
|
||||
"""
|
||||
ref = self.db.collection(DAILY_PICK_COLLECTION).document(date)
|
||||
lock = DailyCommunityPick(date=date, phase="claimed")
|
||||
try:
|
||||
ref.create(lock.model_dump(mode="json"))
|
||||
logger.info("daily-pick: claimed day %s", date)
|
||||
return lock, True
|
||||
except gcloud_exceptions.AlreadyExists:
|
||||
existing = ref.get()
|
||||
return DailyCommunityPick(**existing.to_dict()), False
|
||||
|
||||
def get_lock(self, date: str) -> Optional[DailyCommunityPick]:
|
||||
doc = self.db.collection(DAILY_PICK_COLLECTION).document(date).get()
|
||||
return DailyCommunityPick(**doc.to_dict()) if doc.exists else None
|
||||
|
||||
def update_lock(self, date: str, **fields) -> None:
|
||||
fields["updated_at"] = datetime.now(timezone.utc).isoformat()
|
||||
self.db.collection(DAILY_PICK_COLLECTION).document(date).update(fields)
|
||||
|
||||
# --- picking ---
|
||||
|
||||
def pick_eligible(self) -> Optional[SongRequest]:
|
||||
"""The single highest-priority auto-makeable request (net votes >= 0, oldest
|
||||
tiebreak), ignoring the community-version review flow. Kept for callers that
|
||||
just want the top request; the daily picker uses list_pick_candidates so it
|
||||
can community-check each candidate in rank order."""
|
||||
candidates = self.list_pick_candidates()
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
def list_pick_candidates(self) -> list[SongRequest]:
|
||||
"""Ranked auto-make candidates: open, net votes >= 0, oldest-first, EXCLUDING
|
||||
requests currently held for existing-community-version review (pending, or
|
||||
snoozed and not yet past their cooldown). The daily picker walks these in
|
||||
order, community-checks each, and makes the first with no existing version."""
|
||||
now = datetime.now(timezone.utc)
|
||||
out: list[SongRequest] = []
|
||||
for req in self.list_active(): # already ranked -vote_count, created_at asc
|
||||
if req.vote_count < 0:
|
||||
continue
|
||||
if req.review_state == "pending":
|
||||
continue
|
||||
if req.review_state == "snoozed":
|
||||
until = _as_aware(req.review_snoozed_until)
|
||||
if until and until > now:
|
||||
continue # still in its keep-cooldown
|
||||
out.append(req)
|
||||
return out
|
||||
|
||||
def set_review_pending(self, request_id: str, versions: dict) -> bool:
|
||||
"""Flag a request as needing existing-version review. Transactional and
|
||||
idempotent: returns True only the first time it transitions to pending (so
|
||||
the picker emails Andrew about a newly-flagged pick exactly once)."""
|
||||
ref = self.db.collection(REQUESTS_COLLECTION).document(request_id)
|
||||
transaction = self.db.transaction()
|
||||
return _set_review_pending_txn(transaction, ref, versions)
|
||||
|
||||
def list_pending_reviews(self) -> list[SongRequest]:
|
||||
"""Requests flagged pending existing-version review (the admin queue)."""
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("review_state", "==", "pending")
|
||||
).limit(ACTIVE_FETCH_LIMIT)
|
||||
items = [SongRequest(**doc.to_dict()) for doc in query.stream()]
|
||||
items.sort(key=lambda r: (-r.vote_count, r.created_at))
|
||||
return items
|
||||
|
||||
def snooze_review(self, request_id: str, until: datetime) -> None:
|
||||
"""'Keep on board': clear the pending flag but snooze re-review until `until`."""
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update({
|
||||
"review_state": "snoozed",
|
||||
"review_snoozed_until": until.isoformat(),
|
||||
"updated_at": _now_iso(),
|
||||
})
|
||||
|
||||
def clear_review(self, request_id: str) -> None:
|
||||
"""Clear any review flag (used when admin chooses to make our version anyway)."""
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"review_state": None, "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
def reject_request(self, request_id: str) -> None:
|
||||
"""Reject a request (admin declined to make it — e.g. a good community
|
||||
version already exists). Removes it from the board and clears review flags."""
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"status": "rejected", "review_state": None, "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
def transition_status(
|
||||
self, request_id: str, expected_from: str, new_status: str, **extra
|
||||
) -> bool:
|
||||
"""Move a request's status inside a transaction, guarding on the current
|
||||
value so two runners can't both advance the same request. Extra fields are
|
||||
written alongside. Returns True if the transition was applied."""
|
||||
ref = self.db.collection(REQUESTS_COLLECTION).document(request_id)
|
||||
transaction = self.db.transaction()
|
||||
return _transition_status_txn(
|
||||
transaction, ref, expected_from, new_status, extra
|
||||
)
|
||||
|
||||
def mark_credit_granted(self, request_id: str) -> None:
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"community_credit_granted": True, "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
def set_job_id(self, request_id: str, job_id: str) -> None:
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"job_id": job_id, "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
def assign_owner(
|
||||
self, request_id: str, email: str, expected_owner: Optional[str] = None
|
||||
) -> bool:
|
||||
"""Make ``email`` the current owner and (re)start their 24h review clock.
|
||||
|
||||
Records the email in attempted_owners and bumps handoff_attempts when it is
|
||||
a genuinely new owner (so the initial assignment counts as attempt #1).
|
||||
|
||||
``expected_owner`` is a compare-and-set guard for the handoff: pass the
|
||||
owner you observed, and the write is skipped (returns False) if a newer
|
||||
run already moved the request to someone else — preventing a stale handoff
|
||||
from clobbering a fresher assignment. The picker passes None (initial
|
||||
assignment always applies). Returns True if the assignment was written.
|
||||
"""
|
||||
email = email.lower()
|
||||
expected = expected_owner.lower() if expected_owner else None
|
||||
ref = self.db.collection(REQUESTS_COLLECTION).document(request_id)
|
||||
transaction = self.db.transaction()
|
||||
return _assign_owner_txn(transaction, ref, email, expected)
|
||||
|
||||
def mark_stalled(self, request_id: str) -> None:
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"status": "stalled", "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
# --- reads for handoff / publish ---
|
||||
|
||||
def get_by_job_id(self, job_id: str) -> Optional[SongRequest]:
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("job_id", "==", job_id)
|
||||
).limit(1)
|
||||
for doc in query.stream():
|
||||
return SongRequest(**doc.to_dict())
|
||||
return None
|
||||
|
||||
def list_in_progress(self) -> list[SongRequest]:
|
||||
"""Community picks currently owned by someone reviewing (status in_progress)."""
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("status", "==", "in_progress")
|
||||
).limit(ACTIVE_FETCH_LIMIT)
|
||||
return [SongRequest(**doc.to_dict()) for doc in query.stream()]
|
||||
|
||||
def list_upvoters(self, request_id: str) -> list[str]:
|
||||
"""Emails that up-voted this request (value > 0), oldest vote first.
|
||||
|
||||
Votes are stored per-day at doc id {email}__{date}, and a mover's vote row
|
||||
reflects only their *latest* request — so a voter appears here iff their
|
||||
current daily vote still points at this request with a positive value.
|
||||
"""
|
||||
query = self.db.collection(VOTES_COLLECTION).where(
|
||||
filter=FieldFilter("request_id", "==", request_id)
|
||||
)
|
||||
rows = [doc.to_dict() for doc in query.stream()]
|
||||
upvotes = [r for r in rows if int(r.get("value", 0)) > 0]
|
||||
# Order by when the voter last committed to THIS request: a moved vote keeps
|
||||
# its original created_at but refreshes updated_at, so updated_at reflects the
|
||||
# moment they actually backed this request (created_at as a fallback).
|
||||
upvotes.sort(key=lambda r: r.get("updated_at") or r.get("created_at", ""))
|
||||
# De-dupe by email, preserving earliest.
|
||||
seen: set[str] = set()
|
||||
emails: list[str] = []
|
||||
for r in upvotes:
|
||||
e = (r.get("voter_email") or "").lower()
|
||||
if e and e not in seen:
|
||||
seen.add(e)
|
||||
emails.append(e)
|
||||
return emails
|
||||
|
||||
def mark_published(self, request_id: str, youtube_url: str) -> None:
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"status": "published", "youtube_url": youtube_url, "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
def add_notified_voters(self, request_id: str, emails: list[str]) -> None:
|
||||
"""Record voters that were successfully emailed on publish (ArrayUnion so
|
||||
concurrent/retried fan-outs can't clobber each other)."""
|
||||
if not emails:
|
||||
return
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"notified_voters": firestore.ArrayUnion(emails), "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
def mark_voters_notified(self, request_id: str) -> None:
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"voters_notified": True, "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _as_aware(dt: Optional[datetime]) -> Optional[datetime]:
|
||||
"""Coerce a (possibly naive) datetime to UTC-aware for safe comparison."""
|
||||
if dt is None:
|
||||
return None
|
||||
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
@firestore.transactional
|
||||
def _set_review_pending_txn(transaction, ref, versions):
|
||||
snap = ref.get(transaction=transaction)
|
||||
if not snap.exists:
|
||||
return False
|
||||
if snap.to_dict().get("review_state") == "pending":
|
||||
return False # already flagged — don't re-notify
|
||||
transaction.update(ref, {
|
||||
"review_state": "pending",
|
||||
"community_versions": versions,
|
||||
"community_checked_at": _now_iso(),
|
||||
"updated_at": _now_iso(),
|
||||
})
|
||||
return True
|
||||
|
||||
|
||||
@firestore.transactional
|
||||
def _transition_status_txn(transaction, ref, expected_from, new_status, extra):
|
||||
snap = ref.get(transaction=transaction)
|
||||
if not snap.exists or snap.to_dict().get("status") != expected_from:
|
||||
return False
|
||||
update = {"status": new_status, "updated_at": _now_iso(), **extra}
|
||||
transaction.update(ref, update)
|
||||
return True
|
||||
|
||||
|
||||
@firestore.transactional
|
||||
def _assign_owner_txn(transaction, ref, email, expected_owner):
|
||||
snap = ref.get(transaction=transaction)
|
||||
if not snap.exists:
|
||||
return False
|
||||
data = snap.to_dict()
|
||||
# Compare-and-set: a handoff aborts if the request already moved on.
|
||||
if expected_owner is not None and (data.get("owner_email") or "").lower() != expected_owner:
|
||||
return False
|
||||
attempted = list(data.get("attempted_owners") or [])
|
||||
is_new = email not in attempted
|
||||
if is_new:
|
||||
attempted.append(email)
|
||||
transaction.update(ref, {
|
||||
"owner_email": email,
|
||||
"owner_assigned_at": _now_iso(),
|
||||
"attempted_owners": attempted,
|
||||
"handoff_attempts": int(data.get("handoff_attempts", 0)) + (1 if is_new else 0),
|
||||
"updated_at": _now_iso(),
|
||||
})
|
||||
return True
|
||||
|
||||
|
||||
@firestore.transactional
|
||||
def _cast_vote_txn(transaction, service, vote_ref, target_ref, request_id, email, day, value):
|
||||
"""Transactional body for cast_vote.
|
||||
|
||||
Module-level (not a method) because @firestore.transactional returns a plain
|
||||
callable, not a descriptor — as a method it wouldn't bind `self`, shifting args.
|
||||
"""
|
||||
# --- reads first (Firestore transaction requirement) ---
|
||||
target_snap = target_ref.get(transaction=transaction)
|
||||
if not target_snap.exists or target_snap.to_dict().get("status") != "open":
|
||||
raise RequestNotFound(request_id)
|
||||
|
||||
existing_snap = vote_ref.get(transaction=transaction)
|
||||
existing = existing_snap.to_dict() if existing_snap.exists else None
|
||||
old_value = int(existing.get("value", 0)) if existing else 0
|
||||
old_request_id = existing.get("request_id") if existing else None
|
||||
|
||||
# Snapshot registry so each request doc is read once and updated once
|
||||
# (multiple bumps to the same doc from a single pre-txn snapshot would clobber).
|
||||
snaps = {request_id: target_snap}
|
||||
if old_request_id and old_request_id != request_id:
|
||||
old_ref = service.db.collection(REQUESTS_COLLECTION).document(old_request_id)
|
||||
snaps[old_request_id] = old_ref.get(transaction=transaction)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# --- accumulate net vote-count deltas per request, then write once each ---
|
||||
deltas: dict[str, int] = {}
|
||||
toggling_off = (
|
||||
existing is not None and old_request_id == request_id and old_value == value
|
||||
)
|
||||
if toggling_off:
|
||||
# Remove today's vote and undo its effect — frees the daily vote.
|
||||
transaction.delete(vote_ref)
|
||||
deltas[request_id] = -value
|
||||
vote = None
|
||||
else:
|
||||
if existing is not None:
|
||||
deltas[old_request_id] = deltas.get(old_request_id, 0) - old_value
|
||||
deltas[request_id] = deltas.get(request_id, 0) + value
|
||||
vote = Vote(
|
||||
voter_email=email,
|
||||
voted_date=day,
|
||||
request_id=request_id,
|
||||
value=value,
|
||||
created_at=(existing.get("created_at") if existing else now) or now,
|
||||
updated_at=now,
|
||||
)
|
||||
transaction.set(vote_ref, vote.model_dump(mode="json"))
|
||||
|
||||
for rid, delta in deltas.items():
|
||||
if delta == 0:
|
||||
continue
|
||||
snap = snaps.get(rid)
|
||||
if snap is None or not snap.exists:
|
||||
continue # request gone (e.g. old vote pointed at a closed request)
|
||||
ref = service.db.collection(REQUESTS_COLLECTION).document(rid)
|
||||
current = int(snap.to_dict().get("vote_count", 0))
|
||||
transaction.update(ref, {
|
||||
"vote_count": current + delta,
|
||||
"updated_at": now.isoformat(),
|
||||
})
|
||||
|
||||
return vote
|
||||
|
||||
|
||||
_song_request_service: Optional[SongRequestService] = None
|
||||
|
||||
|
||||
def get_song_request_service() -> SongRequestService:
|
||||
"""Get the global song-request service instance."""
|
||||
global _song_request_service
|
||||
if _song_request_service is None:
|
||||
_song_request_service = SongRequestService()
|
||||
return _song_request_service
|
||||
@@ -474,6 +474,66 @@ class TemplateService:
|
||||
}
|
||||
return self.render_template(template, variables)
|
||||
|
||||
def render_community_track_live(
|
||||
self,
|
||||
name: Optional[str] = None,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""Render the "a track you voted for is live" email (requests board).
|
||||
|
||||
Built directly from i18n strings (no GCS template) — sent to every voter
|
||||
when a community-picked track is published to YouTube.
|
||||
"""
|
||||
ns = "emails.templates.communityTrackLive"
|
||||
template = f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.body")}
|
||||
{{youtube_url}}
|
||||
|
||||
{t(locale, f"{ns}.callToAction")}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"artist": artist or "Unknown Artist",
|
||||
"title": title or "Unknown Title",
|
||||
"youtube_url": youtube_url or "[YouTube URL not available]",
|
||||
}
|
||||
return self.render_template(template, variables)
|
||||
|
||||
def render_community_existing_version(
|
||||
self,
|
||||
name: Optional[str] = None,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""Render the "a version of the song you voted for already exists" email,
|
||||
sent to up-voters when a flagged requests-board pick is rejected in favour
|
||||
of an existing community karaoke version."""
|
||||
ns = "emails.templates.communityExistingVersion"
|
||||
template = f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.body")}
|
||||
{{youtube_url}}
|
||||
|
||||
{t(locale, f"{ns}.callToAction")}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"artist": artist or "Unknown Artist",
|
||||
"title": title or "Unknown Title",
|
||||
"youtube_url": youtube_url or "[link not available]",
|
||||
}
|
||||
return self.render_template(template, variables)
|
||||
|
||||
def upload_template(self, template_name: str, content: str) -> bool:
|
||||
"""
|
||||
Upload a template to GCS.
|
||||
|
||||
@@ -8,6 +8,7 @@ Handles:
|
||||
- User CRUD operations
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
@@ -32,6 +33,19 @@ from backend.models.user import (
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _safe_positive_int_env(name: str, default: int) -> int:
|
||||
"""Parse a positive-int env var, falling back to default on empty/invalid/<=0.
|
||||
|
||||
Used for BOARD_MAX_SIGNUPS_PER_IP — a bad value must not crash import or (if 0/
|
||||
negative) rate-limit every signup.
|
||||
"""
|
||||
try:
|
||||
value = int(os.getenv(name, str(default)))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return value if value > 0 else default
|
||||
|
||||
|
||||
# Collection names
|
||||
USERS_COLLECTION = "gen_users"
|
||||
MAGIC_LINKS_COLLECTION = "magic_links"
|
||||
@@ -220,6 +234,7 @@ class UserService:
|
||||
tenant_id: Optional[str] = None,
|
||||
device_fingerprint: Optional[str] = None,
|
||||
referral_code: Optional[str] = None,
|
||||
purpose: Optional[str] = None,
|
||||
) -> MagicLinkToken:
|
||||
"""
|
||||
Create a magic link token for email authentication.
|
||||
@@ -256,6 +271,7 @@ class UserService:
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
referral_code=referral_code,
|
||||
purpose=purpose,
|
||||
)
|
||||
|
||||
# Save to Firestore
|
||||
@@ -541,6 +557,12 @@ class UserService:
|
||||
# Maximum new signups allowed per IP address in the rate limit window
|
||||
MAX_SIGNUPS_PER_IP = 2
|
||||
SIGNUP_RATE_LIMIT_HOURS = 24
|
||||
# Higher cap for requests-board sign-ins: a shared venue WiFi can register many
|
||||
# voters, but we still keep a deterministic ceiling against scripted abuse (each
|
||||
# board account can later claim a welcome credit via /users/claim-welcome-credit).
|
||||
# Applies to the shared-IP check ONLY — the per-fingerprint cap stays strict, since
|
||||
# a venue is many devices on one IP, not many accounts on one device.
|
||||
BOARD_MAX_SIGNUPS_PER_IP = _safe_positive_int_env("BOARD_MAX_SIGNUPS_PER_IP", 30)
|
||||
|
||||
def count_recent_signups_from_ip(self, ip_address: str, hours: int = 24) -> int:
|
||||
"""
|
||||
@@ -607,18 +629,27 @@ class UserService:
|
||||
return 0
|
||||
|
||||
def is_signup_rate_limited(
|
||||
self, ip_address: Optional[str] = None, device_fingerprint: Optional[str] = None
|
||||
self,
|
||||
ip_address: Optional[str] = None,
|
||||
device_fingerprint: Optional[str] = None,
|
||||
max_signups: Optional[int] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Check if a signup should be rate limited based on IP and/or fingerprint.
|
||||
|
||||
Either signal hitting the limit triggers a block.
|
||||
Either signal hitting the limit triggers a block. `max_signups` overrides the
|
||||
per-IP cap ONLY — the requests board passes a higher limit (BOARD_MAX_SIGNUPS_PER_IP)
|
||||
so a whole venue on shared WiFi can sign in. The per-fingerprint cap always stays
|
||||
strict (self.MAX_SIGNUPS_PER_IP): a venue is many devices behind one IP, so raising
|
||||
the fingerprint cap would let one browser script many accounts.
|
||||
"""
|
||||
ip_limit = max_signups if max_signups is not None else self.MAX_SIGNUPS_PER_IP
|
||||
|
||||
if ip_address:
|
||||
ip_count = self.count_recent_signups_from_ip(
|
||||
ip_address, hours=self.SIGNUP_RATE_LIMIT_HOURS
|
||||
)
|
||||
if ip_count >= self.MAX_SIGNUPS_PER_IP:
|
||||
if ip_count >= ip_limit:
|
||||
return True
|
||||
|
||||
if device_fingerprint:
|
||||
|
||||
@@ -690,9 +690,25 @@ class WorkerService:
|
||||
return False
|
||||
|
||||
async def trigger_render_video_worker(self, job_id: str) -> bool:
|
||||
"""Trigger render video worker (post-review)."""
|
||||
"""
|
||||
Trigger render video worker (post-review).
|
||||
|
||||
When USE_CLOUD_RUN_JOBS_FOR_RENDER=true and ENABLE_CLOUD_TASKS=true,
|
||||
runs as a Cloud Run Job (reusing video-encoding-job with an args
|
||||
override) so the render orchestration survives Cloud Run Service
|
||||
deployment rollouts. As a BackgroundTask it was killed ~10s after
|
||||
SIGTERM whenever a deploy landed mid-render, freezing the job at
|
||||
rendering_video (incident 2026-09-13, job 41e06b90 — same class as
|
||||
incident 2026-03-08 which migrated the video worker to Cloud Run Jobs).
|
||||
"""
|
||||
self._bump_worker_generation(job_id)
|
||||
self._warmup_encoding_worker(job_id)
|
||||
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_render:
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="video-encoding-job",
|
||||
worker_module="render_video_worker",
|
||||
)
|
||||
return await self.trigger_worker("render-video", job_id)
|
||||
|
||||
def _bump_worker_generation(self, job_id: str) -> None:
|
||||
@@ -807,7 +823,9 @@ class WorkerService:
|
||||
|
||||
async def schedule_gdrive_validation(
|
||||
self,
|
||||
delay_seconds: int = GDRIVE_VALIDATION_DELAY_SECONDS
|
||||
delay_seconds: int = GDRIVE_VALIDATION_DELAY_SECONDS,
|
||||
brand_code: Optional[str] = None,
|
||||
expect_cdg: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
Schedule a delayed GDrive validation check.
|
||||
@@ -817,6 +835,9 @@ class WorkerService:
|
||||
|
||||
Args:
|
||||
delay_seconds: Delay before executing the validation (default: 5 minutes)
|
||||
brand_code: Optional brand code of the just-published track. When set,
|
||||
the validator additionally checks this track is present in all
|
||||
expected folders same-run (incident-hardening D2).
|
||||
|
||||
Returns:
|
||||
True if task was scheduled successfully, False otherwise
|
||||
@@ -864,13 +885,22 @@ class WorkerService:
|
||||
|
||||
dispatch_deadline_seconds = WORKER_DISPATCH_DEADLINES.get("gdrive-validation", 120)
|
||||
|
||||
# Carry the brand code so the validator can check this track's own
|
||||
# completeness same-run (incident-hardening D2). Absent → "{}".
|
||||
# expect_cdg tells the validator whether to require the CDG folder.
|
||||
body_bytes = b"{}"
|
||||
if brand_code:
|
||||
body_bytes = json.dumps(
|
||||
{"brand_code": brand_code, "expect_cdg": expect_cdg}
|
||||
).encode("utf-8")
|
||||
|
||||
# Build task payload
|
||||
task = {
|
||||
"http_request": {
|
||||
"http_method": tasks_v2.HttpMethod.POST,
|
||||
"url": f"{self._base_url}/api/internal/trigger-gdrive-validation",
|
||||
"headers": headers,
|
||||
"body": b"{}",
|
||||
"body": body_bytes,
|
||||
"oidc_token": {
|
||||
"service_account_email": f"karaoke-backend@{project}.iam.gserviceaccount.com",
|
||||
},
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
"""
|
||||
Shared logic for the YouTube description back-catalogue rewrite.
|
||||
|
||||
Used by BOTH:
|
||||
* the one-off CLI (scripts/youtube-descriptions/youtube_descriptions.py), and
|
||||
* the scheduled daily drain worker (backend/workers/youtube_description_backfill_worker.py)
|
||||
|
||||
so classification, targeting, rendering, and the update-body construction are
|
||||
identical no matter how the rewrite is driven. Rendering itself delegates to
|
||||
backend.services.youtube_description (single source of truth for the template).
|
||||
|
||||
Nothing here talks to the YouTube API — callers pass in already-fetched video
|
||||
snippet dicts (as returned by videos.list items) and act on the results.
|
||||
"""
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from backend.services.youtube_description import build_youtube_tags, render_youtube_description
|
||||
|
||||
# Data files (skip / force-include lists) ship inside the backend package so they
|
||||
# are available both locally and in the Cloud Run image.
|
||||
_DATA_DIR = Path(__file__).resolve().parent.parent / "data" / "youtube_backfill"
|
||||
SKIP_IDS_PATH = _DATA_DIR / "skip_ids.txt"
|
||||
INCLUDE_IDS_PATH = _DATA_DIR / "include_ids.txt"
|
||||
|
||||
UPDATE_COST = 50 # videos.update quota units
|
||||
DEFAULT_MUSIC_CATEGORY = "10"
|
||||
|
||||
# --- Classification patterns ---
|
||||
# "Artist - Title (Karaoke)" and variants ("(Official Karaoke)", "(Karaoke Version)").
|
||||
KARAOKE_TITLE_RE = re.compile(
|
||||
r"^\s*(?P<artist>.+?)\s*[-–—]\s*(?P<title>.+?)\s*\(\s*[^)]*karaoke[^)]*\)\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
FALLBACK_TITLE_RE = re.compile(r"^\s*(?P<artist>.+?)\s*[-–—]\s*(?P<title>.+?)\s*$")
|
||||
BRAND_CODE_RE = re.compile(r"\bNOMAD(?:NP)?-\d{3,}\b")
|
||||
|
||||
# Description substrings that signal "this is one of our karaoke uploads".
|
||||
KARAOKE_DESC_MARKERS = (
|
||||
"brand code: nomad",
|
||||
"nomadkaraoke.com",
|
||||
"created with nomad karaoke",
|
||||
"vocals removed",
|
||||
"karaoke (instrumental) version",
|
||||
"fiverr.com",
|
||||
"discord.gg/divebar",
|
||||
"discord.nomadkaraoke.com",
|
||||
"karaokenerds.com",
|
||||
"ai-powered vocal separation",
|
||||
)
|
||||
|
||||
# Only these snippet fields are sent back on update (others are read-only or would
|
||||
# be wiped). categoryId + title are required by the API on a snippet update.
|
||||
_MUTABLE_SNIPPET_FIELDS = {
|
||||
"title",
|
||||
"description",
|
||||
"categoryId",
|
||||
"tags",
|
||||
"defaultLanguage",
|
||||
"defaultAudioLanguage",
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# List files
|
||||
# ----------------------------------------------------------------------------
|
||||
def _load_id_file(path: Path) -> set:
|
||||
ids = set()
|
||||
if path.exists():
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if line:
|
||||
ids.add(line.split("|", 1)[0].strip())
|
||||
return ids
|
||||
|
||||
|
||||
def load_skip_ids() -> set:
|
||||
return _load_id_file(SKIP_IDS_PATH)
|
||||
|
||||
|
||||
def load_include_overrides() -> Dict[str, Optional[Dict[str, str]]]:
|
||||
"""Parse include_ids.txt.
|
||||
|
||||
Each non-comment line is either a bare video ID, or
|
||||
``<id> | <Artist> | <Title>`` to override the parsed artist/title (used for
|
||||
genuine tracks whose title was truncated on YouTube). Returns a map of
|
||||
id -> {"artist", "song_title"} or None (no override).
|
||||
"""
|
||||
out: Dict[str, Optional[Dict[str, str]]] = {}
|
||||
if not INCLUDE_IDS_PATH.exists():
|
||||
return out
|
||||
for line in INCLUDE_IDS_PATH.read_text(encoding="utf-8").splitlines():
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if not line:
|
||||
continue
|
||||
if "|" in line:
|
||||
parts = [p.strip() for p in line.split("|")]
|
||||
out[parts[0]] = {
|
||||
"artist": parts[1] if len(parts) > 1 else "",
|
||||
"song_title": parts[2] if len(parts) > 2 else "",
|
||||
}
|
||||
else:
|
||||
out[line] = None
|
||||
return out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Classification
|
||||
# ----------------------------------------------------------------------------
|
||||
def classify(video: Dict) -> Dict:
|
||||
"""Classify a videos.list item dict. Returns a plain dict of findings."""
|
||||
snip = video.get("snippet", {})
|
||||
title = snip.get("title", "") or ""
|
||||
desc = snip.get("description", "") or ""
|
||||
low_title = title.lower()
|
||||
low_desc = desc.lower()
|
||||
|
||||
brand_match = BRAND_CODE_RE.search(desc)
|
||||
brand_code = brand_match.group(0) if brand_match else None
|
||||
|
||||
has_karaoke_title = "karaoke" in low_title
|
||||
has_marker = any(m in low_desc for m in KARAOKE_DESC_MARKERS)
|
||||
is_karaoke = has_karaoke_title or bool(brand_code) or has_marker
|
||||
|
||||
artist = song_title = None
|
||||
parse_conf = "none"
|
||||
m = KARAOKE_TITLE_RE.match(title)
|
||||
if m:
|
||||
artist = m.group("artist").strip()
|
||||
song_title = m.group("title").strip()
|
||||
parse_conf = "high"
|
||||
elif is_karaoke:
|
||||
m2 = FALLBACK_TITLE_RE.match(title)
|
||||
if m2:
|
||||
artist = m2.group("artist").strip()
|
||||
song_title = m2.group("title").strip()
|
||||
parse_conf = "medium"
|
||||
|
||||
if "ai-powered vocal separation" in low_desc:
|
||||
kind = "terse_new"
|
||||
elif "fiverr.com" in low_desc:
|
||||
kind = "fiverr"
|
||||
elif "brand code: nomad" in low_desc or "nomadkaraoke.com" in low_desc:
|
||||
kind = "nomad_recent"
|
||||
elif is_karaoke:
|
||||
kind = "other_karaoke"
|
||||
else:
|
||||
kind = "non_karaoke"
|
||||
|
||||
# Auto-eligible ONLY at high confidence (title explicitly ends in "(Karaoke)").
|
||||
# The medium fallback sweeps in demos/tutorials/appeals and "lyrics video WITH
|
||||
# vocals" uploads, so those are excluded and surfaced for review instead.
|
||||
eligible = bool(is_karaoke and artist and song_title and parse_conf == "high")
|
||||
|
||||
return {
|
||||
"video_id": video.get("id"),
|
||||
"yt_title": title,
|
||||
"artist": artist,
|
||||
"song_title": song_title,
|
||||
"brand_code": brand_code,
|
||||
"parse_confidence": parse_conf,
|
||||
"kind": kind,
|
||||
"is_karaoke": is_karaoke,
|
||||
"eligible": eligible,
|
||||
"category_id": snip.get("categoryId"),
|
||||
"current_description": desc,
|
||||
}
|
||||
|
||||
|
||||
def render_for(entry: Dict) -> str:
|
||||
return render_youtube_description(
|
||||
artist=entry.get("artist"),
|
||||
title=entry.get("song_title"),
|
||||
brand_code=entry.get("brand_code"),
|
||||
)
|
||||
|
||||
|
||||
def build_entries(
|
||||
videos_by_id: Dict[str, Dict],
|
||||
ordered_ids: List[str],
|
||||
skip_ids: Optional[set] = None,
|
||||
include_overrides: Optional[Dict] = None,
|
||||
) -> List[Dict]:
|
||||
"""Classify every video and decide which are rewrite targets.
|
||||
|
||||
Adds `in_skip_list`, `forced_include`, `target`, and `will_change` to each
|
||||
entry. `will_change` is the authoritative "should we update this" flag: it's
|
||||
True only for a target whose freshly-rendered description actually differs.
|
||||
"""
|
||||
skip_ids = skip_ids if skip_ids is not None else load_skip_ids()
|
||||
include_overrides = include_overrides if include_overrides is not None else load_include_overrides()
|
||||
|
||||
entries: List[Dict] = []
|
||||
for vid in ordered_ids:
|
||||
v = videos_by_id.get(vid)
|
||||
if not v:
|
||||
continue
|
||||
entry = classify(v)
|
||||
entry["in_skip_list"] = vid in skip_ids
|
||||
entry["forced_include"] = vid in include_overrides
|
||||
override = include_overrides.get(vid)
|
||||
if override:
|
||||
if override.get("artist"):
|
||||
entry["artist"] = override["artist"]
|
||||
if override.get("song_title"):
|
||||
entry["song_title"] = override["song_title"]
|
||||
entry["parse_confidence"] = "override"
|
||||
|
||||
is_target = (
|
||||
(entry["eligible"] or entry["forced_include"])
|
||||
and not entry["in_skip_list"]
|
||||
and bool(entry["artist"])
|
||||
and bool(entry["song_title"])
|
||||
)
|
||||
entry["target"] = is_target
|
||||
if is_target:
|
||||
new_desc = render_for(entry)
|
||||
entry["will_change"] = new_desc.strip() != entry["current_description"].strip()
|
||||
else:
|
||||
entry["will_change"] = False
|
||||
entries.append(entry)
|
||||
return entries
|
||||
|
||||
|
||||
def build_update_snippet(current_snippet: Dict, entry: Dict, enrich_tags: bool) -> Dict:
|
||||
"""Build the snippet body for videos.update.
|
||||
|
||||
Copies the existing mutable snippet fields (so title/category/language are
|
||||
preserved), swaps in the new description, and optionally refreshes tags.
|
||||
"""
|
||||
snippet = {k: v for k, v in current_snippet.items() if k in _MUTABLE_SNIPPET_FIELDS}
|
||||
snippet["description"] = render_for(entry)
|
||||
if not snippet.get("categoryId"):
|
||||
snippet["categoryId"] = DEFAULT_MUSIC_CATEGORY
|
||||
if enrich_tags:
|
||||
snippet["tags"] = build_youtube_tags(entry.get("artist"), entry.get("song_title"))
|
||||
return snippet
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# YouTube API helpers (shared by the CLI and the scheduled worker)
|
||||
# ----------------------------------------------------------------------------
|
||||
SCOPES = ["https://www.googleapis.com/auth/youtube"]
|
||||
|
||||
|
||||
def load_credentials_from_secret() -> Optional[Dict]:
|
||||
"""Load the youtube-oauth-credentials dict from Secret Manager (or None)."""
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
|
||||
return get_youtube_service().get_credentials_dict()
|
||||
|
||||
|
||||
def build_youtube(creds_dict: Dict):
|
||||
"""Build an authorized youtube v3 client from a credentials dict."""
|
||||
from google.auth.transport.requests import Request
|
||||
from google.oauth2.credentials import Credentials
|
||||
from googleapiclient.discovery import build
|
||||
|
||||
creds = Credentials(
|
||||
token=creds_dict.get("token"),
|
||||
refresh_token=creds_dict.get("refresh_token"),
|
||||
token_uri=creds_dict.get("token_uri"),
|
||||
client_id=creds_dict.get("client_id"),
|
||||
client_secret=creds_dict.get("client_secret"),
|
||||
scopes=creds_dict.get("scopes", SCOPES),
|
||||
)
|
||||
if not creds.token or creds.expired:
|
||||
creds.refresh(Request())
|
||||
return build("youtube", "v3", credentials=creds, cache_discovery=False)
|
||||
|
||||
|
||||
def get_uploads_playlist(youtube) -> str:
|
||||
resp = youtube.channels().list(part="contentDetails", mine=True).execute()
|
||||
items = resp.get("items", [])
|
||||
if not items:
|
||||
raise RuntimeError("No channel found for these credentials.")
|
||||
return items[0]["contentDetails"]["relatedPlaylists"]["uploads"]
|
||||
|
||||
|
||||
def iter_all_video_ids(youtube, playlist_id: str) -> List[str]:
|
||||
ids: List[str] = []
|
||||
token = None
|
||||
while True:
|
||||
resp = (
|
||||
youtube.playlistItems()
|
||||
.list(part="contentDetails", playlistId=playlist_id, maxResults=50, pageToken=token)
|
||||
.execute()
|
||||
)
|
||||
for it in resp.get("items", []):
|
||||
ids.append(it["contentDetails"]["videoId"])
|
||||
token = resp.get("nextPageToken")
|
||||
if not token:
|
||||
break
|
||||
return ids
|
||||
|
||||
|
||||
def _chunks(seq: List, n: int):
|
||||
for i in range(0, len(seq), n):
|
||||
yield seq[i : i + n]
|
||||
|
||||
|
||||
def fetch_snippets(youtube, ids: List[str]) -> Dict[str, Dict]:
|
||||
out: Dict[str, Dict] = {}
|
||||
for batch in _chunks(ids, 50):
|
||||
resp = youtube.videos().list(part="snippet,status", id=",".join(batch)).execute()
|
||||
for it in resp.get("items", []):
|
||||
out[it["id"]] = it
|
||||
return out
|
||||
|
||||
|
||||
def fetch_all_channel_entries(youtube) -> Tuple[List[Dict], Dict[str, Dict]]:
|
||||
"""Enumerate the whole channel; return (classified entries, raw videos-by-id).
|
||||
|
||||
Read-only. ~1 quota unit per 50 videos plus a couple for enumeration. The raw
|
||||
videos map is returned too so callers can reuse the already-fetched full
|
||||
snippets when applying updates (no extra reads).
|
||||
"""
|
||||
playlist_id = get_uploads_playlist(youtube)
|
||||
ids = iter_all_video_ids(youtube, playlist_id)
|
||||
videos = fetch_snippets(youtube, ids)
|
||||
return build_entries(videos, ids), videos
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
YouTube description + tags rendering (single source of truth).
|
||||
|
||||
Both the live upload pipeline (video_worker_orchestrator, youtube_queue_processor)
|
||||
and the bulk-rewrite maintenance tool (scripts/youtube-descriptions) render
|
||||
descriptions through this module so on-channel descriptions stay consistent with
|
||||
newly published ones.
|
||||
|
||||
The canonical template lives in ``Settings.default_youtube_description``
|
||||
(``backend/config.py``, overridable via the ``DEFAULT_YOUTUBE_DESCRIPTION`` env
|
||||
var). It may contain these placeholders, all optional:
|
||||
|
||||
{title} - song title
|
||||
{artist} - artist name
|
||||
{artist_hashtag} - artist name reduced to a valid hashtag (e.g. "#Coldplay")
|
||||
{brand_code} - the NOMAD-#### brand code line
|
||||
|
||||
Templates without placeholders still work: legacy/tenant-custom templates that
|
||||
predate placeholders keep the historical behaviour of appending
|
||||
``\n\nBrand Code: <code>`` when a brand code is available.
|
||||
"""
|
||||
import re
|
||||
from typing import List, Optional
|
||||
|
||||
# Total length budget for the YouTube ``tags`` field (API rejects > 500 chars,
|
||||
# counted as the sum of tag lengths plus separators). Stay comfortably under.
|
||||
_MAX_TAGS_TOTAL_CHARS = 460
|
||||
|
||||
|
||||
def hashtagify(text: Optional[str]) -> str:
|
||||
"""Reduce a string to the characters that are valid inside a hashtag.
|
||||
|
||||
Keeps unicode word characters (letters, digits, underscore) and drops
|
||||
everything else, so ``"P!nk"`` -> ``"Pnk"`` and ``"Twenty One Pilots"`` ->
|
||||
``"TwentyOnePilots"``. Returns ``""`` when nothing usable remains.
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
return re.sub(r"[^\w]", "", text, flags=re.UNICODE)
|
||||
|
||||
|
||||
def _collapse_blank_lines(text: str) -> str:
|
||||
"""Collapse runs of 3+ newlines down to a blank-line separator."""
|
||||
return re.sub(r"\n{3,}", "\n\n", text)
|
||||
|
||||
|
||||
def render_youtube_description(
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
template: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Render a YouTube description from the template + per-video values.
|
||||
|
||||
Args:
|
||||
artist: Artist name (may be empty/unknown).
|
||||
title: Song title (may be empty/unknown).
|
||||
brand_code: NOMAD-#### style code, or falsy to omit the brand-code line.
|
||||
template: Override template. Defaults to
|
||||
``Settings.default_youtube_description``.
|
||||
|
||||
Returns:
|
||||
The fully rendered description string, stripped of trailing whitespace.
|
||||
"""
|
||||
if template is None:
|
||||
# Lazy import to avoid any import-time coupling with config.
|
||||
from backend.config import get_settings
|
||||
|
||||
template = get_settings().default_youtube_description or ""
|
||||
|
||||
result = template
|
||||
|
||||
# Simple token substitution (avoid str.format so stray braces in custom
|
||||
# templates never raise).
|
||||
result = result.replace("{artist}", artist or "")
|
||||
result = result.replace("{title}", title or "")
|
||||
|
||||
artist_tag = hashtagify(artist)
|
||||
if artist_tag:
|
||||
result = result.replace("{artist_hashtag}", artist_tag)
|
||||
else:
|
||||
# Drop the artist hashtag entirely, including a leading separator space.
|
||||
result = result.replace(" #{artist_hashtag}", "")
|
||||
result = result.replace("#{artist_hashtag}", "")
|
||||
result = result.replace("{artist_hashtag}", "")
|
||||
|
||||
if "{brand_code}" in result:
|
||||
if brand_code:
|
||||
result = result.replace("{brand_code}", brand_code)
|
||||
else:
|
||||
# Remove any line carrying the placeholder so we don't leave a
|
||||
# dangling "Brand Code:" label.
|
||||
result = "\n".join(
|
||||
line for line in result.split("\n") if "{brand_code}" not in line
|
||||
)
|
||||
elif brand_code:
|
||||
# Legacy template without a placeholder: preserve historical append.
|
||||
result = f"{result}\n\nBrand Code: {brand_code}"
|
||||
|
||||
return _collapse_blank_lines(result).strip()
|
||||
|
||||
|
||||
def build_youtube_tags(artist: Optional[str], title: Optional[str]) -> List[str]:
|
||||
"""Build a de-duplicated, length-capped YouTube tags list.
|
||||
|
||||
Richer than the historical ``["karaoke", artist, title]`` for discoverability,
|
||||
while respecting YouTube's ~500 char total tags budget.
|
||||
"""
|
||||
artist = (artist or "").strip()
|
||||
title = (title or "").strip()
|
||||
|
||||
candidates = [
|
||||
"karaoke",
|
||||
"instrumental",
|
||||
"lyrics",
|
||||
"karaoke version",
|
||||
"sing along",
|
||||
"backing track",
|
||||
artist,
|
||||
title,
|
||||
f"{artist} karaoke" if artist else "",
|
||||
f"{artist} {title} karaoke" if artist and title else "",
|
||||
]
|
||||
|
||||
tags: List[str] = []
|
||||
seen = set()
|
||||
total = 0
|
||||
for tag in candidates:
|
||||
tag = tag.strip()
|
||||
if not tag:
|
||||
continue
|
||||
key = tag.lower()
|
||||
if key in seen:
|
||||
continue
|
||||
# +1 approximates the separator cost the API counts between tags.
|
||||
cost = len(tag) + 1
|
||||
if total + cost > _MAX_TAGS_TOTAL_CHARS:
|
||||
continue
|
||||
seen.add(key)
|
||||
tags.append(tag)
|
||||
total += cost
|
||||
|
||||
return tags
|
||||
@@ -0,0 +1,300 @@
|
||||
"""Emulator-backed tests for SongRequestService — exercises REAL Firestore transactions.
|
||||
|
||||
Covers the vote arithmetic (create / move / flip / toggle-off), the one-vote-per-day
|
||||
rule, submit dedupe + auto-upvote, and ranking. Skipped unless the Firestore emulator
|
||||
is running (see emulator/conftest.py).
|
||||
"""
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from backend.models.song_request import SongRequest
|
||||
from backend.services.match_judge.verdict import MatchVerdict, KIND_COSMETIC
|
||||
from backend.services import song_request_service as srs
|
||||
from backend.services.song_request_service import SongRequestService
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def service(monkeypatch):
|
||||
# Isolate each test run in its own collections so parallel/rerun state can't bleed.
|
||||
suffix = uuid.uuid4().hex[:8]
|
||||
monkeypatch.setattr(srs, "REQUESTS_COLLECTION", f"test_song_requests_{suffix}")
|
||||
monkeypatch.setattr(srs, "VOTES_COLLECTION", f"test_song_request_votes_{suffix}")
|
||||
monkeypatch.setattr(srs, "DAILY_PICK_COLLECTION", f"test_daily_pick_{suffix}")
|
||||
return SongRequestService()
|
||||
|
||||
|
||||
def _cosmetic(artist, title):
|
||||
return MatchVerdict(
|
||||
kind=KIND_COSMETIC, confident=True,
|
||||
canonical_artist=artist, canonical_title=title, engine="catalog",
|
||||
)
|
||||
|
||||
|
||||
async def _submit(service, email, artist, title, canon_artist=None, canon_title=None):
|
||||
verdict = _cosmetic(canon_artist or artist, canon_title or title)
|
||||
with patch("backend.services.match_judge.service.judge_match", new=AsyncMock(return_value=verdict)):
|
||||
return await service.submit_request(email, artist, title)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submit_creates_with_auto_upvote(service):
|
||||
req, existed, ca, ct = await _submit(service, "u1@x.com", "beatles", "hey jude", "The Beatles", "Hey Jude")
|
||||
assert existed is False
|
||||
assert (req.artist, req.title) == ("The Beatles", "Hey Jude")
|
||||
assert req.vote_count == 1 # submitter's endorsement
|
||||
daily = service.get_daily_vote("u1@x.com")
|
||||
assert daily and daily.request_id == req.id and daily.value == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resubmit_same_song_dedupes_and_upvotes(service):
|
||||
req1, _, _, _ = await _submit(service, "u1@x.com", "The Beatles", "Hey Jude")
|
||||
# Different user submits the same song (with messier input that canonicalizes equal)
|
||||
req2, existed, _, _ = await _submit(service, "u2@x.com", " beatles ", "hey jude", "The Beatles", "Hey Jude")
|
||||
assert existed is True
|
||||
assert req2.id == req1.id
|
||||
assert req2.vote_count == 2 # u1 (auto) + u2 (dedupe upvote)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resubmit_own_song_is_idempotent_not_toggle_off(service):
|
||||
# Submitting a song you already up-voted today must NOT toggle the vote off.
|
||||
req1, _, _, _ = await _submit(service, "u1@x.com", "The Beatles", "Hey Jude")
|
||||
assert req1.vote_count == 1
|
||||
req2, existed, _, _ = await _submit(service, "u1@x.com", "The Beatles", "Hey Jude")
|
||||
assert existed is True
|
||||
assert req2.id == req1.id
|
||||
assert req2.vote_count == 1 # still 1 — the up-vote was preserved, not removed
|
||||
assert service.get_daily_vote("u1@x.com").request_id == req1.id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_one_vote_per_day_moves_not_adds(service):
|
||||
a, _, _, _ = await _submit(service, "owner@x.com", "Artist A", "Song A")
|
||||
b, _, _, _ = await _submit(service, "owner2@x.com", "Artist B", "Song B")
|
||||
voter = "voter@x.com"
|
||||
service.cast_vote(voter, a.id, "up")
|
||||
assert service.get_request(a.id).vote_count == 2 # owner auto + voter
|
||||
# Same voter votes on B the same day → their single daily vote MOVES off A onto B
|
||||
service.cast_vote(voter, b.id, "up")
|
||||
assert service.get_request(a.id).vote_count == 1 # back to just owner
|
||||
assert service.get_request(b.id).vote_count == 2 # owner2 auto + voter
|
||||
daily = service.get_daily_vote(voter)
|
||||
assert daily.request_id == b.id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_toggle_off_frees_daily_vote(service):
|
||||
a, _, _, _ = await _submit(service, "owner@x.com", "Artist A", "Song A")
|
||||
voter = "voter@x.com"
|
||||
service.cast_vote(voter, a.id, "up")
|
||||
assert service.get_request(a.id).vote_count == 2
|
||||
service.cast_vote(voter, a.id, "up") # same request + direction → toggle off
|
||||
assert service.get_request(a.id).vote_count == 1
|
||||
assert service.get_daily_vote(voter) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flip_direction_same_request(service):
|
||||
a, _, _, _ = await _submit(service, "owner@x.com", "Artist A", "Song A")
|
||||
voter = "voter@x.com"
|
||||
service.cast_vote(voter, a.id, "up")
|
||||
assert service.get_request(a.id).vote_count == 2 # owner(+1) + up(+1)
|
||||
service.cast_vote(voter, a.id, "down") # flip up→down: net change -2
|
||||
assert service.get_request(a.id).vote_count == 0 # owner(+1) + down(-1)
|
||||
daily = service.get_daily_vote(voter)
|
||||
assert daily.value == -1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ranking_orders_by_votes(service):
|
||||
low, _, _, _ = await _submit(service, "o1@x.com", "Low", "Song")
|
||||
high, _, _, _ = await _submit(service, "o2@x.com", "High", "Song")
|
||||
# Push "high" ahead with extra votes from distinct voters
|
||||
service.cast_vote("v1@x.com", high.id, "up")
|
||||
service.cast_vote("v2@x.com", high.id, "up")
|
||||
active = service.list_active()
|
||||
ids = [r.id for r in active]
|
||||
assert ids.index(high.id) < ids.index(low.id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vote_on_missing_request_raises(service):
|
||||
from backend.services.song_request_service import RequestNotFound
|
||||
with pytest.raises(RequestNotFound):
|
||||
service.cast_vote("v@x.com", "does-not-exist", "up")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Phase 2 — daily picker, ownership handoff, publish fan-out
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_claim_day_is_single_winner(service):
|
||||
lock1, new1 = service.claim_day("2026-09-03")
|
||||
lock2, new2 = service.claim_day("2026-09-03")
|
||||
assert new1 is True and new2 is False
|
||||
assert lock1.date == lock2.date == "2026-09-03"
|
||||
# Different day is independently claimable.
|
||||
_, new3 = service.claim_day("2026-09-04")
|
||||
assert new3 is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_and_get_lock(service):
|
||||
service.claim_day("2026-09-03")
|
||||
service.update_lock("2026-09-03", phase="done", request_id="req1", job_id="j1")
|
||||
lock = service.get_lock("2026-09-03")
|
||||
assert lock.phase == "done" and lock.request_id == "req1" and lock.job_id == "j1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pick_eligible_skips_negative_and_ranks(service):
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
b, _, _, _ = await _submit(service, "o2@x.com", "Artist B", "Song B")
|
||||
# Give B more votes → B should rank first.
|
||||
service.cast_vote("v1@x.com", b.id, "up")
|
||||
assert service.pick_eligible().id == b.id
|
||||
# Drive A negative → still eligible-skipping keeps B; then make B negative too.
|
||||
service.cast_vote("v2@x.com", a.id, "down") # A: owner(+1) + down(-1) = 0
|
||||
service.cast_vote("v3@x.com", a.id, "down") # A: -1 now
|
||||
assert service.pick_eligible().id == b.id
|
||||
assert service.get_request(a.id).vote_count < 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pick_eligible_none_when_all_negative(service):
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
service.cast_vote("v1@x.com", a.id, "down") # 0
|
||||
service.cast_vote("v2@x.com", a.id, "down") # -1
|
||||
assert service.get_request(a.id).vote_count < 0
|
||||
assert service.pick_eligible() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_transition_status_guards_on_current(service):
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
assert service.transition_status(a.id, "open", "queued") is True
|
||||
assert service.get_request(a.id).status == "queued"
|
||||
# Wrong expected_from → no-op.
|
||||
assert service.transition_status(a.id, "open", "in_progress") is False
|
||||
assert service.get_request(a.id).status == "queued"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_assign_owner_tracks_attempts(service):
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
service.assign_owner(a.id, "o1@x.com")
|
||||
r = service.get_request(a.id)
|
||||
assert r.owner_email == "o1@x.com" and r.handoff_attempts == 1
|
||||
assert r.attempted_owners == ["o1@x.com"]
|
||||
# Re-assigning the SAME owner does not double-count.
|
||||
service.assign_owner(a.id, "o1@x.com")
|
||||
assert service.get_request(a.id).handoff_attempts == 1
|
||||
# A new owner bumps the count.
|
||||
service.assign_owner(a.id, "v2@x.com")
|
||||
r = service.get_request(a.id)
|
||||
assert r.owner_email == "v2@x.com" and r.handoff_attempts == 2
|
||||
assert r.attempted_owners == ["o1@x.com", "v2@x.com"]
|
||||
# Compare-and-set: a stale handoff expecting the OLD owner is rejected.
|
||||
assert service.assign_owner(a.id, "v3@x.com", expected_owner="o1@x.com") is False
|
||||
assert service.get_request(a.id).owner_email == "v2@x.com" # unchanged
|
||||
# CAS with the current owner succeeds.
|
||||
assert service.assign_owner(a.id, "v3@x.com", expected_owner="v2@x.com") is True
|
||||
assert service.get_request(a.id).owner_email == "v3@x.com"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_upvoters_oldest_first_positive_only(service):
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A") # o1 auto-upvote
|
||||
service.cast_vote("v2@x.com", a.id, "up")
|
||||
service.cast_vote("v3@x.com", a.id, "down") # negative — excluded
|
||||
voters = service.list_upvoters(a.id)
|
||||
assert "o1@x.com" in voters and "v2@x.com" in voters
|
||||
assert "v3@x.com" not in voters
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_by_job_id_and_mark_published(service):
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
service.set_job_id(a.id, "job-42")
|
||||
assert service.get_by_job_id("job-42").id == a.id
|
||||
service.mark_published(a.id, "https://youtu.be/xyz")
|
||||
r = service.get_request(a.id)
|
||||
assert r.status == "published" and r.youtube_url == "https://youtu.be/xyz"
|
||||
service.add_notified_voters(a.id, ["v1@x.com", "v2@x.com"])
|
||||
service.add_notified_voters(a.id, ["v2@x.com", "v3@x.com"]) # ArrayUnion dedupes
|
||||
assert set(service.get_request(a.id).notified_voters) == {"v1@x.com", "v2@x.com", "v3@x.com"}
|
||||
service.mark_voters_notified(a.id)
|
||||
assert service.get_request(a.id).voters_notified is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_in_progress_and_stalled(service):
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
service.transition_status(a.id, "open", "in_progress")
|
||||
assert [r.id for r in service.list_in_progress()] == [a.id]
|
||||
service.mark_stalled(a.id)
|
||||
assert service.get_request(a.id).status == "stalled"
|
||||
assert service.list_in_progress() == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Existing-community-version review flow (A/B follow-up)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_pick_candidates_excludes_review_states(service):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
b, _, _, _ = await _submit(service, "o2@x.com", "Artist B", "Song B")
|
||||
c, _, _, _ = await _submit(service, "o3@x.com", "Artist C", "Song C")
|
||||
# Flag A pending; snooze B into the future; C stays clean.
|
||||
service.set_review_pending(a.id, {"best_youtube_url": "https://y/x", "tracks": []})
|
||||
service.snooze_review(b.id, datetime.now(timezone.utc) + timedelta(days=10))
|
||||
ids = [r.id for r in service.list_pick_candidates()]
|
||||
assert c.id in ids
|
||||
assert a.id not in ids # pending
|
||||
assert b.id not in ids # snoozed (future)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_expired_snooze_becomes_pickable_again(service):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
service.snooze_review(a.id, datetime.now(timezone.utc) - timedelta(days=1)) # already expired
|
||||
assert a.id in [r.id for r in service.list_pick_candidates()]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_set_review_pending_idempotent(service):
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
versions = {"best_youtube_url": "https://y/x", "tracks": [{"brand_name": "Z", "youtube_url": "https://y/x"}]}
|
||||
assert service.set_review_pending(a.id, versions) is True # newly flagged
|
||||
assert service.set_review_pending(a.id, versions) is False # already pending
|
||||
r = service.get_request(a.id)
|
||||
assert r.review_state == "pending" and r.community_versions["best_youtube_url"] == "https://y/x"
|
||||
assert a.id in [x.id for x in service.list_pending_reviews()]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_snooze_clear_and_reject(service):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
service.set_review_pending(a.id, {"best_youtube_url": None, "tracks": []})
|
||||
# keep → snoozed, off the pending queue
|
||||
service.snooze_review(a.id, datetime.now(timezone.utc) + timedelta(days=30))
|
||||
assert service.get_request(a.id).review_state == "snoozed"
|
||||
assert service.list_pending_reviews() == []
|
||||
# clear → back to no review flag
|
||||
service.clear_review(a.id)
|
||||
assert service.get_request(a.id).review_state is None
|
||||
# reject → status rejected, off the board
|
||||
service.reject_request(a.id)
|
||||
r = service.get_request(a.id)
|
||||
assert r.status == "rejected" and r.review_state is None
|
||||
assert a.id not in [x.id for x in service.list_active()]
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# GCE encode worker — golden response fixtures
|
||||
|
||||
Real-shaped responses returned by the GCE encoding worker's `encode_videos`
|
||||
(the value `GCEEncodingBackend.encode()` consumes), captured/authored as golden
|
||||
JSON so the encode→publish seam is tested against the *actual* contract rather
|
||||
than hand-authored per-test mocks. Each conforms to the `GceEncodeResponse`
|
||||
TypedDict in `backend/services/encoding_interface.py`.
|
||||
|
||||
| Fixture | Shape | What it exercises |
|
||||
|---|---|---|
|
||||
| `success.json` | `complete`, all 4 requested formats | Happy path. Uses the NOMAD-1632 title ("Portrait of Jennie") so classification must key off the trailing format tag, not the title text. |
|
||||
| `cached.json` | `complete`, full set incl. portrait/with-vocals/title/end/CDG | A cached hit returning every additive final; exercises every classifier branch. |
|
||||
| `empty.json` | `complete`, `output_files: []` | Stale/cached-but-deleted job. Must be treated as **recoverable** (re-encode), NOT a partial/defective result. This shape caused Failure B. |
|
||||
| `partial.json` | `complete`, missing `mp4_720p` | Failure A: the completeness guard must trip and refuse to publish. |
|
||||
| `malformed.json` | `complete`, stray / wrong-extension names | Nothing classifies into a slot → treated as empty (not crash, not mis-slotted). |
|
||||
|
||||
Replayed by `backend/tests/test_encoding_contract.py` (contract test) and driven
|
||||
through the real orchestrator by `TestEncodePublishSeam` in
|
||||
`backend/tests/test_video_worker_orchestrator.py`.
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": [
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mkv",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Portrait 1080x1920).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (With Vocals).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Title).mov",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (End).mov",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke CDG).zip"
|
||||
]
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": []
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": [
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/notes.txt",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole 720p demo.txt",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).webm",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/thumbnail.jpg"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": [
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mkv",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 4k).mp4"
|
||||
]
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": [
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mkv",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4"
|
||||
]
|
||||
}
|
||||
@@ -160,6 +160,70 @@ def test_apply_all_flags_stale() -> None:
|
||||
assert out["applied_ids"] == []
|
||||
|
||||
|
||||
# --- undo_out / undo_info ---
|
||||
|
||||
def test_apply_suggestion_populates_undo_out_for_replace() -> None:
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(
|
||||
_segments(), _sug("replace", ["w1"], "was", original_text="am"), undo_out=undo
|
||||
)
|
||||
assert result is not None
|
||||
assert undo["op"] == "replace"
|
||||
assert undo["segment_id"] == "s0"
|
||||
assert undo["prev_word_id"] == "w0"
|
||||
assert undo["removed_words"] == [_word("w1", "am", 0.3, 0.6)]
|
||||
assert undo["new_word_ids"] == [result[0]["words"][1]["id"]]
|
||||
assert undo["removed_segment"] is None
|
||||
|
||||
|
||||
def test_apply_suggestion_populates_undo_out_for_delete_whole_segment() -> None:
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(_segments(), _sug("delete", ["w4"]), undo_out=undo)
|
||||
assert result is not None
|
||||
assert undo["op"] == "delete"
|
||||
assert undo["new_word_ids"] == []
|
||||
assert undo["removed_words"] == [_word("w4", "gasoline", 2.0, 2.8)]
|
||||
assert undo["removed_segment"] == {"segment": _segments()[1], "index": 1}
|
||||
|
||||
|
||||
def test_apply_all_suggestions_reports_undo_info_per_applied_id() -> None:
|
||||
out = apply_all_suggestions(_segments(), [_sug("replace", ["w1"], "was", id="a")])
|
||||
assert out["applied_ids"] == ["a"]
|
||||
assert set(out["undo_info"].keys()) == {"a"}
|
||||
assert out["undo_info"]["a"]["op"] == "replace"
|
||||
|
||||
|
||||
def test_apply_suggestion_populates_undo_out_for_insert_after() -> None:
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(
|
||||
_segments(), _sug("insert_after", ["w3"], "burning"), undo_out=undo
|
||||
)
|
||||
assert result is not None
|
||||
new_word = result[0]["words"][4]
|
||||
assert undo == {
|
||||
"op": "insert_after",
|
||||
"new_word_ids": [new_word["id"]],
|
||||
"removed_words": [],
|
||||
"segment_id": "s0",
|
||||
"prev_word_id": "w3",
|
||||
"removed_segment": None,
|
||||
}
|
||||
|
||||
|
||||
def test_apply_suggestion_populates_undo_out_for_partial_delete() -> None:
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(_segments(), _sug("delete", ["w0"]), undo_out=undo)
|
||||
assert result is not None
|
||||
assert undo == {
|
||||
"op": "delete",
|
||||
"new_word_ids": [],
|
||||
"removed_words": [_word("w0", "I", 0.0, 0.3)],
|
||||
"segment_id": "s0",
|
||||
"prev_word_id": None,
|
||||
"removed_segment": None,
|
||||
}
|
||||
|
||||
|
||||
def test_p1_self_conflict_produces_detectable_duplicate() -> None:
|
||||
# Corpus f6439692: overlapping suggestions (conflict_group=null) both add
|
||||
# "you're" -> "fire, you're you're gasoline". The apply engine mirrors the
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Tests for the board-specific signup rate limit (IP cap raised, fingerprint strict)."""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from backend.services.user_service import UserService, _safe_positive_int_env
|
||||
|
||||
|
||||
def _service(ip_count=0, fp_count=0):
|
||||
svc = UserService.__new__(UserService) # bypass __init__ (no real Firestore client)
|
||||
svc.count_recent_signups_from_ip = MagicMock(return_value=ip_count)
|
||||
svc.count_recent_signups_from_fingerprint = MagicMock(return_value=fp_count)
|
||||
return svc
|
||||
|
||||
|
||||
def test_default_ip_cap_blocks_at_two():
|
||||
svc = _service(ip_count=2)
|
||||
assert svc.is_signup_rate_limited(ip_address="1.2.3.4") is True
|
||||
svc = _service(ip_count=1)
|
||||
assert svc.is_signup_rate_limited(ip_address="1.2.3.4") is False
|
||||
|
||||
|
||||
def test_board_override_raises_ip_cap():
|
||||
# 10 prior signups from this IP: blocked by default (2), allowed under board cap (30).
|
||||
svc = _service(ip_count=10)
|
||||
assert svc.is_signup_rate_limited(ip_address="1.2.3.4") is True
|
||||
assert svc.is_signup_rate_limited(ip_address="1.2.3.4", max_signups=30) is False
|
||||
|
||||
|
||||
def test_board_override_does_not_relax_fingerprint_cap():
|
||||
# Same browser (fingerprint) with 5 prior signups is blocked even under the board
|
||||
# IP override — a venue is many devices on one IP, not many accounts on one device.
|
||||
svc = _service(ip_count=0, fp_count=5)
|
||||
assert svc.is_signup_rate_limited(device_fingerprint="fp", max_signups=30) is True
|
||||
|
||||
|
||||
def test_safe_positive_int_env(monkeypatch):
|
||||
monkeypatch.delenv("BOARD_MAX_SIGNUPS_PER_IP", raising=False)
|
||||
assert _safe_positive_int_env("BOARD_MAX_SIGNUPS_PER_IP", 30) == 30
|
||||
monkeypatch.setenv("BOARD_MAX_SIGNUPS_PER_IP", "50")
|
||||
assert _safe_positive_int_env("BOARD_MAX_SIGNUPS_PER_IP", 30) == 50
|
||||
for bad in ("", "abc", "0", "-5"):
|
||||
monkeypatch.setenv("BOARD_MAX_SIGNUPS_PER_IP", bad)
|
||||
assert _safe_positive_int_env("BOARD_MAX_SIGNUPS_PER_IP", 30) == 30
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Unit tests for the daily free-community-track picker orchestration.
|
||||
|
||||
Mocks the service/user/job/KaraokeNerds layers so we exercise run_daily_pick's
|
||||
control flow: kill-switch shadowing, empty board, day-lock idempotency, credit
|
||||
grant guards, and the existing-community-version candidate loop (flag dups →
|
||||
make the first clean one). Firestore-level pieces are covered by emulator tests.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.song_request import DailyCommunityPick, SongRequest
|
||||
from backend.workers import community_daily_pick as cdp
|
||||
|
||||
|
||||
def _request(**over):
|
||||
base = dict(
|
||||
id="req1", artist="A", title="T", artist_raw="A", title_raw="T",
|
||||
dedupe_key="a|t", submitted_by="owner@x.com", source="human",
|
||||
status="open", vote_count=5,
|
||||
)
|
||||
base.update(over)
|
||||
return SongRequest(**base)
|
||||
|
||||
|
||||
def _make_service(candidates=None, lock=None, claimed_new=True, registry=None):
|
||||
"""Build a mock SongRequestService.
|
||||
|
||||
candidates: what list_pick_candidates returns (ranked).
|
||||
registry: id -> SongRequest for get_request lookups (defaults to candidates).
|
||||
"""
|
||||
candidates = candidates or []
|
||||
reg = dict(registry) if registry else {r.id: r for r in candidates}
|
||||
svc = MagicMock()
|
||||
svc.claim_day.return_value = (lock or DailyCommunityPick(date="2026-09-03"), claimed_new)
|
||||
svc.list_pick_candidates.return_value = candidates
|
||||
svc.get_request.side_effect = lambda rid: reg.get(rid)
|
||||
svc.set_review_pending.return_value = True # newly flagged
|
||||
return svc
|
||||
|
||||
|
||||
def _settings(enabled=True):
|
||||
return SimpleNamespace(
|
||||
community_daily_pick_enabled=enabled,
|
||||
default_enable_cdg=True, default_enable_txt=True, default_brand_prefix="NOMAD",
|
||||
default_enable_youtube_upload=True, default_youtube_description="desc",
|
||||
default_discord_webhook_url=None, default_dropbox_path=None,
|
||||
default_gdrive_folder_id=None,
|
||||
)
|
||||
|
||||
|
||||
def _community(has_map=None):
|
||||
"""AsyncMock for check_community_versions. has_map: artist->bool has_community."""
|
||||
has_map = has_map or {}
|
||||
|
||||
async def _check(artist, title):
|
||||
if has_map.get(artist):
|
||||
return {"has_community": True, "best_youtube_url": "https://youtu.be/x",
|
||||
"songs": [{"community_tracks": [{"brand_name": "Foo", "youtube_url": "https://youtu.be/x"}]}]}
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
return AsyncMock(side_effect=_check)
|
||||
|
||||
|
||||
def _run(svc, settings, community=None, user=None, made=True):
|
||||
"""Context-managed patches; returns the coroutine to await."""
|
||||
community = community or _community()
|
||||
user = user or MagicMock()
|
||||
if user.add_credits.return_value is None or not isinstance(user.add_credits.return_value, tuple):
|
||||
user.add_credits.return_value = (True, 5, "ok")
|
||||
stack = [
|
||||
patch.object(cdp, "get_song_request_service", return_value=svc),
|
||||
patch.object(cdp, "get_settings", return_value=settings),
|
||||
patch.object(cdp, "get_user_service", return_value=user),
|
||||
patch("backend.services.karaokenerds_service.check_community_versions", community),
|
||||
patch.object(cdp, "_email_admin_flagged", MagicMock()),
|
||||
]
|
||||
if made:
|
||||
stack.append(patch.object(cdp, "_create_community_job", return_value="job123"))
|
||||
stack.append(patch.object(cdp, "_search_and_download", new=AsyncMock(return_value=True)))
|
||||
return stack
|
||||
|
||||
|
||||
async def _exec(stack, dry_run=False):
|
||||
for p in stack:
|
||||
p.start()
|
||||
try:
|
||||
return await cdp.run_daily_pick(dry_run=dry_run)
|
||||
finally:
|
||||
for p in reversed(stack):
|
||||
p.stop()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_kill_switch_off_shadows_no_side_effects():
|
||||
svc = _make_service(candidates=[_request()])
|
||||
user = MagicMock()
|
||||
result = await _exec(_run(svc, _settings(enabled=False), user=user, made=False))
|
||||
assert result["status"] == "shadow" and result["reason"] == "kill_switch_off"
|
||||
user.add_credits.assert_not_called()
|
||||
svc.claim_day.assert_not_called()
|
||||
svc.set_review_pending.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dry_run_shadows_even_when_enabled():
|
||||
svc = _make_service(candidates=[_request()])
|
||||
result = await _exec(_run(svc, _settings(enabled=True), made=False), dry_run=True)
|
||||
assert result["status"] == "shadow" and result["reason"] == "dry_run"
|
||||
assert result["request_id"] == "req1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_board_makes_nothing():
|
||||
svc = _make_service(candidates=[])
|
||||
result = await _exec(_run(svc, _settings(enabled=True), made=False))
|
||||
assert result["status"] == "empty"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_already_resolved_day_is_noop():
|
||||
lock = DailyCommunityPick(date="2026-09-03", phase="done", request_id="req1", job_id="j1")
|
||||
svc = _make_service(candidates=[_request()], lock=lock, claimed_new=False)
|
||||
result = await _exec(_run(svc, _settings(enabled=True), made=False))
|
||||
assert result["status"] == "already_done"
|
||||
svc.list_pick_candidates.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_make_success_grants_credit_and_creates_job():
|
||||
req = _request()
|
||||
svc = _make_service(candidates=[req])
|
||||
user = MagicMock()
|
||||
user.add_credits.return_value = (True, 5, "ok")
|
||||
result = await _exec(_run(svc, _settings(enabled=True), user=user))
|
||||
assert result["status"] == "made" and result["job_id"] == "job123"
|
||||
user.add_credits.assert_called_once()
|
||||
svc.mark_credit_granted.assert_called_once_with("req1")
|
||||
svc.set_job_id.assert_called_once_with("req1", "job123")
|
||||
svc.assign_owner.assert_called_once_with("req1", "owner@x.com")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flags_dup_and_makes_next_clean():
|
||||
dup = _request(id="dup", artist="DupArtist", title="Has Version", vote_count=9)
|
||||
clean = _request(id="clean", artist="CleanArtist", title="No Version", vote_count=3)
|
||||
svc = _make_service(candidates=[dup, clean])
|
||||
community = _community({"DupArtist": True}) # only the dup has a community version
|
||||
result = await _exec(_run(svc, _settings(enabled=True), community=community))
|
||||
assert result["status"] == "made" and result["request_id"] == "clean"
|
||||
# The dup was flagged pending; the clean one was made.
|
||||
svc.set_review_pending.assert_called_once()
|
||||
assert svc.set_review_pending.call_args.args[0] == "dup"
|
||||
assert result["flagged"] == ["dup"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_all_dups_makes_nothing_but_flags():
|
||||
a = _request(id="a", artist="A1", title="t", vote_count=9)
|
||||
b = _request(id="b", artist="B1", title="t", vote_count=3)
|
||||
svc = _make_service(candidates=[a, b])
|
||||
community = _community({"A1": True, "B1": True})
|
||||
result = await _exec(_run(svc, _settings(enabled=True), community=community, made=False))
|
||||
assert result["status"] == "empty"
|
||||
assert set(result["flagged"]) == {"a", "b"}
|
||||
assert svc.set_review_pending.call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_credit_grant_is_idempotent_on_resume():
|
||||
req = _request(community_credit_granted=True, status="queued")
|
||||
svc = _make_service(candidates=[req])
|
||||
user = MagicMock()
|
||||
await _exec(_run(svc, _settings(enabled=True), user=user))
|
||||
user.add_credits.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resume_finishes_locked_request_without_recheck():
|
||||
# Lock already recorded request_id → resume making it, skip candidate loop.
|
||||
req = _request(id="locked", community_credit_granted=True, job_id="existing", status="in_progress")
|
||||
lock = DailyCommunityPick(date="2026-09-03", phase="job_created", request_id="locked")
|
||||
svc = _make_service(candidates=[], lock=lock, claimed_new=False, registry={"locked": req})
|
||||
community = _community()
|
||||
result = await _exec(_run(svc, _settings(enabled=True), community=community))
|
||||
assert result["status"] == "made" and result["job_id"] == "existing"
|
||||
svc.list_pick_candidates.assert_not_called()
|
||||
community.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_credit_grant_failure_aborts_before_job():
|
||||
req = _request()
|
||||
svc = _make_service(candidates=[req])
|
||||
user = MagicMock()
|
||||
user.add_credits.return_value = (False, 0, "denied")
|
||||
with patch.object(cdp, "_create_community_job", return_value="job123") as mk:
|
||||
stack = _run(svc, _settings(enabled=True), user=user, made=False)
|
||||
result = await _exec(stack)
|
||||
assert result["status"] == "error" and result["step"] == "grant_credit"
|
||||
mk.assert_not_called()
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Unit tests for the 24h ownership handoff worker."""
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.models.song_request import SongRequest
|
||||
from backend.workers import community_handoff as ch
|
||||
|
||||
OLD = "2020-01-01T00:00:00+00:00"
|
||||
|
||||
|
||||
def _req(**over):
|
||||
base = dict(
|
||||
id="req1", artist="A", title="T", artist_raw="A", title_raw="T",
|
||||
dedupe_key="a|t", submitted_by="owner@x.com", source="human",
|
||||
status="in_progress", vote_count=3, job_id="j1",
|
||||
owner_email="owner@x.com", owner_assigned_at=OLD,
|
||||
attempted_owners=["owner@x.com"], handoff_attempts=1,
|
||||
)
|
||||
base.update(over)
|
||||
return SongRequest(**base)
|
||||
|
||||
|
||||
def _settings():
|
||||
return SimpleNamespace(community_handoff_hours=24, community_handoff_max_attempts=5)
|
||||
|
||||
|
||||
def _patched(svc, job_status=JobStatus.AWAITING_REVIEW):
|
||||
svc.assign_owner.return_value = True # CAS succeeds by default
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = SimpleNamespace(status=job_status, job_id="j1")
|
||||
email = MagicMock()
|
||||
user = MagicMock()
|
||||
user.get_user.return_value = SimpleNamespace(locale="en")
|
||||
return patch.multiple(
|
||||
ch,
|
||||
get_song_request_service=MagicMock(return_value=svc),
|
||||
JobManager=MagicMock(return_value=jm),
|
||||
get_email_service=MagicMock(return_value=email),
|
||||
get_user_service=MagicMock(return_value=user),
|
||||
get_settings=MagicMock(return_value=_settings()),
|
||||
), jm, email
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reassigns_to_next_untried_voter():
|
||||
svc = MagicMock()
|
||||
svc.list_in_progress.return_value = [_req()]
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com", "v3@x.com"]
|
||||
ctx, jm, email = _patched(svc)
|
||||
with ctx:
|
||||
result = await ch.process_community_handoffs()
|
||||
assert result["handed_off"] == 1 and result["parked"] == 0
|
||||
jm.update_job.assert_called_once_with("j1", {"user_email": "v2@x.com"})
|
||||
svc.assign_owner.assert_called_once_with("req1", "v2@x.com", expected_owner="owner@x.com")
|
||||
email.send_review_reminder.assert_called_once()
|
||||
svc.mark_stalled.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_when_owner_changed_mid_run():
|
||||
# CAS fails (a fresher run already moved the request) → don't touch the job.
|
||||
svc = MagicMock()
|
||||
svc.list_in_progress.return_value = [_req()]
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com"]
|
||||
ctx, jm, email = _patched(svc)
|
||||
svc.assign_owner.return_value = False
|
||||
with ctx:
|
||||
result = await ch.process_community_handoffs()
|
||||
assert result["handed_off"] == 0
|
||||
jm.update_job.assert_not_called()
|
||||
email.send_review_reminder.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_parks_when_cap_reached():
|
||||
svc = MagicMock()
|
||||
svc.list_in_progress.return_value = [_req(handoff_attempts=5)]
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com", "v3@x.com", "v4@x.com", "v5@x.com", "v6@x.com"]
|
||||
ctx, jm, email = _patched(svc)
|
||||
with ctx:
|
||||
result = await ch.process_community_handoffs()
|
||||
assert result["parked"] == 1 and result["handed_off"] == 0
|
||||
svc.mark_stalled.assert_called_once_with("req1")
|
||||
jm.update_job.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_parks_when_no_untried_voters():
|
||||
svc = MagicMock()
|
||||
svc.list_in_progress.return_value = [_req(attempted_owners=["owner@x.com", "v2@x.com"])]
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com"]
|
||||
ctx, jm, email = _patched(svc)
|
||||
with ctx:
|
||||
result = await ch.process_community_handoffs()
|
||||
assert result["parked"] == 1
|
||||
svc.mark_stalled.assert_called_once_with("req1")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_when_owner_clock_not_expired():
|
||||
svc = MagicMock()
|
||||
fresh = datetime.now(timezone.utc).isoformat()
|
||||
svc.list_in_progress.return_value = [_req(owner_assigned_at=fresh)]
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com"]
|
||||
ctx, jm, email = _patched(svc)
|
||||
with ctx:
|
||||
result = await ch.process_community_handoffs()
|
||||
assert result["handed_off"] == 0 and result["parked"] == 0
|
||||
jm.update_job.assert_not_called()
|
||||
svc.mark_stalled.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_when_job_not_owner_blocked():
|
||||
# Job is still processing (not the owner's fault) → no handoff.
|
||||
svc = MagicMock()
|
||||
svc.list_in_progress.return_value = [_req()]
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com"]
|
||||
ctx, jm, email = _patched(svc, job_status=JobStatus.SEPARATING_STAGE1)
|
||||
with ctx:
|
||||
result = await ch.process_community_handoffs()
|
||||
assert result["checked"] == 0 and result["handed_off"] == 0
|
||||
jm.update_job.assert_not_called()
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Unit tests for the admin community-review action endpoint (make/reject/keep)."""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from backend.api.routes.admin import (
|
||||
CommunityReviewActionBody,
|
||||
action_community_review,
|
||||
)
|
||||
from backend.models.song_request import SongRequest
|
||||
|
||||
|
||||
def _req(**over):
|
||||
base = dict(
|
||||
id="req1", artist="A", title="T", artist_raw="A", title_raw="T",
|
||||
dedupe_key="a|t", submitted_by="owner@x.com", source="human",
|
||||
status="open", vote_count=3, review_state="pending",
|
||||
community_versions={"best_youtube_url": "https://youtu.be/x", "tracks": []},
|
||||
)
|
||||
base.update(over)
|
||||
return SongRequest(**base)
|
||||
|
||||
|
||||
def _settings():
|
||||
return SimpleNamespace(community_review_snooze_days=30)
|
||||
|
||||
|
||||
def _patches(svc, notifier=None, provision=None):
|
||||
ps = [
|
||||
patch("backend.services.song_request_service.get_song_request_service", MagicMock(return_value=svc)),
|
||||
patch("backend.config.get_settings", MagicMock(return_value=_settings())),
|
||||
]
|
||||
if notifier is not None:
|
||||
ps.append(patch("backend.services.job_notification_service.get_job_notification_service",
|
||||
MagicMock(return_value=notifier)))
|
||||
if provision is not None:
|
||||
ps.append(patch("backend.workers.community_daily_pick._provision_and_start", provision))
|
||||
return ps
|
||||
|
||||
|
||||
async def _call(ps, request_id, action):
|
||||
for p in ps:
|
||||
p.start()
|
||||
try:
|
||||
return await action_community_review(
|
||||
request_id, CommunityReviewActionBody(action=action), auth_data=("admin", None, 0)
|
||||
)
|
||||
finally:
|
||||
for p in reversed(ps):
|
||||
p.stop()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_snoozes():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req()
|
||||
res = await _call(_patches(svc), "req1", "keep")
|
||||
assert res.status == "snoozed"
|
||||
svc.snooze_review.assert_called_once()
|
||||
assert svc.snooze_review.call_args.args[0] == "req1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_notifies_upvoters():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req()
|
||||
svc.list_upvoters.return_value = ["v1@x.com", "v2@x.com"]
|
||||
notifier = MagicMock()
|
||||
notifier.send_community_existing_version_email = AsyncMock(return_value=True)
|
||||
res = await _call(_patches(svc, notifier=notifier), "req1", "reject")
|
||||
assert res.status == "rejected"
|
||||
svc.reject_request.assert_called_once_with("req1")
|
||||
urls = {c.kwargs["youtube_url"] for c in notifier.send_community_existing_version_email.call_args_list}
|
||||
assert urls == {"https://youtu.be/x"}
|
||||
assert notifier.send_community_existing_version_email.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_make_provisions_job():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req()
|
||||
provision = AsyncMock(return_value={"status": "made", "job_id": "j9"})
|
||||
res = await _call(_patches(svc, provision=provision), "req1", "make")
|
||||
assert res.status == "made"
|
||||
svc.clear_review.assert_called_once_with("req1")
|
||||
provision.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_not_pending_returns_404():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req(review_state=None)
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await _call(_patches(svc), "req1", "keep")
|
||||
assert exc.value.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_make_failure_raises_500():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req()
|
||||
provision = AsyncMock(return_value={"status": "error", "step": "grant_credit", "message": "denied"})
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await _call(_patches(svc, provision=provision), "req1", "make")
|
||||
assert exc.value.status_code == 500
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Unit tests for the requests-board publish fan-out in the YouTube queue processor."""
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.song_request import SongRequest
|
||||
from backend.workers import youtube_queue_processor as yqp
|
||||
|
||||
|
||||
def _req(**over):
|
||||
base = dict(
|
||||
id="req1", artist="A", title="T", artist_raw="A", title_raw="T",
|
||||
dedupe_key="a|t", submitted_by="owner@x.com", source="human",
|
||||
status="in_progress", vote_count=3, job_id="j1", owner_email="owner@x.com",
|
||||
)
|
||||
base.update(over)
|
||||
return SongRequest(**base)
|
||||
|
||||
|
||||
def _ctx(svc, notifier):
|
||||
return patch.multiple(
|
||||
"backend.services.song_request_service",
|
||||
get_song_request_service=MagicMock(return_value=svc),
|
||||
), patch(
|
||||
"backend.services.job_notification_service.get_job_notification_service",
|
||||
MagicMock(return_value=notifier),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_community_job_is_ignored():
|
||||
svc = MagicMock()
|
||||
svc.get_by_job_id.return_value = None
|
||||
notifier = MagicMock()
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
svc.mark_published.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publishes_and_fans_out_excluding_owner():
|
||||
svc = MagicMock()
|
||||
svc.get_by_job_id.return_value = _req(voters_notified=False)
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com", "v3@x.com"]
|
||||
notifier = MagicMock()
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=True)
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
svc.mark_published.assert_called_once_with("req1", "https://youtu.be/x")
|
||||
# Owner excluded (already got the completion email); two voters emailed.
|
||||
emailed = {c.kwargs["to_email"] for c in notifier.send_community_track_live_email.call_args_list}
|
||||
assert emailed == {"v2@x.com", "v3@x.com"}
|
||||
# Each success is recorded immediately (crash-safe), then the all-done flag.
|
||||
assert [c.args for c in svc.add_notified_voters.call_args_list] == [
|
||||
("req1", ["v2@x.com"]), ("req1", ["v3@x.com"]),
|
||||
]
|
||||
svc.mark_voters_notified.assert_called_once_with("req1")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_already_notified_voters_and_retries_failures():
|
||||
# v2 already notified; v3 fails this run → not marked fully-notified, v3 retried later.
|
||||
svc = MagicMock()
|
||||
svc.get_by_job_id.return_value = _req(voters_notified=False, notified_voters=["v2@x.com"])
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com", "v3@x.com"]
|
||||
notifier = MagicMock()
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=False) # v3 send fails
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
# Only the un-notified voter (v3) is attempted; v2 skipped.
|
||||
emailed = {c.kwargs["to_email"] for c in notifier.send_community_track_live_email.call_args_list}
|
||||
assert emailed == {"v3@x.com"}
|
||||
svc.add_notified_voters.assert_not_called() # v3 send failed → nothing recorded
|
||||
svc.mark_voters_notified.assert_not_called() # partial → leave flag unset for retry
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_already_notified_does_not_resend():
|
||||
svc = MagicMock()
|
||||
svc.get_by_job_id.return_value = _req(voters_notified=True)
|
||||
notifier = MagicMock()
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=True)
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
svc.mark_published.assert_called_once() # republish (mark) is safe/idempotent
|
||||
notifier.send_community_track_live_email.assert_not_called()
|
||||
svc.mark_voters_notified.assert_not_called()
|
||||
@@ -98,7 +98,7 @@ class TestDiscordNotificationServicePostMessage:
|
||||
assert result is True
|
||||
mock_post.assert_called_once_with(
|
||||
url,
|
||||
json={"content": "Test message"},
|
||||
json={"content": "Test message", "allowed_mentions": {"parse": []}},
|
||||
timeout=30
|
||||
)
|
||||
|
||||
@@ -117,7 +117,7 @@ class TestDiscordNotificationServicePostMessage:
|
||||
assert result is True
|
||||
mock_post.assert_called_once_with(
|
||||
custom_url,
|
||||
json={"content": "Test message"},
|
||||
json={"content": "Test message", "allowed_mentions": {"parse": []}},
|
||||
timeout=30
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Contract test: replay golden GCE worker responses through the real encode path.
|
||||
|
||||
This is the "kill mock drift" backstop (hardening plan P3). Every encoding mock
|
||||
in the suite is hand-authored, and the real "cached / empty" response shape was
|
||||
simply never in the corpus — the textbook cause of NOMAD-1632's Failure B. Here
|
||||
we capture the *real* worker response shapes as golden JSON fixtures
|
||||
(``backend/tests/fixtures/encoding/``) and replay them through the real
|
||||
``classify_encoded_output`` and ``GCEEncodingBackend.encode()`` so the classifier
|
||||
and the completeness guard are exercised against the actual contract.
|
||||
|
||||
Kept lightweight and deterministic: no network, no GCS, no filesystem writes —
|
||||
the only boundary patched is the worker call (``encode_videos``).
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from backend.services.encoding_interface import (
|
||||
GceEncodeResponse,
|
||||
GCEEncodingBackend,
|
||||
EncodingInput,
|
||||
classify_encoded_output,
|
||||
)
|
||||
|
||||
FIXTURES_DIR = Path(__file__).parent / "fixtures" / "encoding"
|
||||
|
||||
# The four formats GCEEncodingBackend.encode() always requests (and the guard
|
||||
# enforces). Keep in sync with encoding_interface.encode().
|
||||
REQUESTED_FORMATS = {"mp4_4k_lossless", "mp4_4k_lossy", "mkv_4k", "mp4_720p"}
|
||||
|
||||
|
||||
def _load(name: str) -> GceEncodeResponse:
|
||||
with open(FIXTURES_DIR / f"{name}.json") as fh:
|
||||
return json.load(fh)
|
||||
|
||||
|
||||
async def _run_encode(response: GceEncodeResponse):
|
||||
"""Drive the REAL encode() with a mocked worker returning ``response``."""
|
||||
backend = GCEEncodingBackend(logger=MagicMock())
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value=response)
|
||||
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/tmp/title.mov",
|
||||
karaoke_video_path="/tmp/karaoke.mkv",
|
||||
instrumental_audio_path="/tmp/audio.flac",
|
||||
artist="Nat King Cole",
|
||||
title="Portrait of Jennie",
|
||||
options={
|
||||
"job_id": "NOMAD-1632",
|
||||
"input_gcs_path": "gs://bucket/jobs/NOMAD-1632/",
|
||||
"output_gcs_path": "gs://bucket/jobs/NOMAD-1632/finals/",
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"backend.services.encoding_service.get_encoding_service",
|
||||
return_value=mock_service,
|
||||
):
|
||||
return await backend.encode(input_config)
|
||||
|
||||
|
||||
class TestEncodingResponseContract:
|
||||
"""Replay golden fixtures through the real classifier + encode()."""
|
||||
|
||||
ALL_FIXTURES = ["success", "cached", "empty", "partial", "malformed"]
|
||||
|
||||
@pytest.mark.parametrize("name", ALL_FIXTURES)
|
||||
def test_fixture_conforms_to_schema(self, name):
|
||||
"""Every fixture matches the GceEncodeResponse contract keys/types."""
|
||||
data = _load(name)
|
||||
assert set(data).issubset(set(GceEncodeResponse.__annotations__)), (
|
||||
f"{name}.json has keys outside GceEncodeResponse"
|
||||
)
|
||||
assert isinstance(data["status"], str)
|
||||
assert isinstance(data["output_files"], list)
|
||||
assert all(isinstance(p, str) for p in data["output_files"])
|
||||
|
||||
def test_classify_success_fixture(self):
|
||||
"""NOMAD-1632 regression: 'Portrait of Jennie' 720p must NOT misclassify
|
||||
as the portrait video — classification keys off the trailing tag."""
|
||||
files = _load("success")["output_files"]
|
||||
classified = {classify_encoded_output(p) for p in files}
|
||||
assert classified == REQUESTED_FORMATS
|
||||
# The 720p whose TITLE contains 'Portrait' maps to mp4_720p, not portrait_mp4.
|
||||
seven20 = next(p for p in files if "720p" in p)
|
||||
assert classify_encoded_output(seven20) == "mp4_720p"
|
||||
|
||||
def test_classify_cached_fixture_covers_all_branches(self):
|
||||
"""The cached full-set fixture exercises every classifier branch."""
|
||||
files = _load("cached")["output_files"]
|
||||
classified = {classify_encoded_output(p) for p in files}
|
||||
assert classified == REQUESTED_FORMATS | {
|
||||
"portrait_mp4",
|
||||
"with_vocals_mp4",
|
||||
"title_mov",
|
||||
"end_mov",
|
||||
"cdg_zip",
|
||||
}
|
||||
|
||||
def test_classify_malformed_fixture_classified_out(self):
|
||||
"""Stray / wrong-extension names classify to None (no false slotting)."""
|
||||
files = _load("malformed")["output_files"]
|
||||
assert all(classify_encoded_output(p) is None for p in files)
|
||||
# Specifically: a 720p tag with the wrong extension must be rejected.
|
||||
wrong_ext = next(p for p in files if p.endswith(".webm"))
|
||||
assert classify_encoded_output(wrong_ext) is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_success_fixture(self):
|
||||
out = await _run_encode(_load("success"))
|
||||
assert out.success is True
|
||||
assert out.lossy_720p_mp4_path is not None
|
||||
assert set(out.output_files) == REQUESTED_FORMATS
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_cached_fixture(self):
|
||||
out = await _run_encode(_load("cached"))
|
||||
assert out.success is True
|
||||
assert out.portrait_mp4_path is not None
|
||||
assert out.with_vocals_mp4_path is not None
|
||||
assert REQUESTED_FORMATS.issubset(set(out.output_files))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_empty_fixture_is_recoverable(self):
|
||||
"""Empty output_files must NOT trip the guard — it's recoverable
|
||||
(stale cache) and the orchestrator re-encodes. Failure B defense."""
|
||||
out = await _run_encode(_load("empty"))
|
||||
assert out.success is True
|
||||
assert out.output_files == {}
|
||||
assert out.error_message is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_partial_fixture_trips_guard(self):
|
||||
"""Partial (720p missing) must fail loud. Failure A defense."""
|
||||
out = await _run_encode(_load("partial"))
|
||||
assert out.success is False
|
||||
assert "mp4_720p" in out.error_message
|
||||
assert "incomplete" in out.error_message.lower()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_malformed_fixture_treated_as_empty(self):
|
||||
"""Nothing classifies into a slot → treated as empty (no guard trip,
|
||||
no crash), which the orchestrator then recovers from as a stale cache."""
|
||||
out = await _run_encode(_load("malformed"))
|
||||
assert out.success is True
|
||||
assert out.output_files == {}
|
||||
assert out.error_message is None
|
||||
@@ -16,10 +16,62 @@ from backend.services.encoding_interface import (
|
||||
EncodingBackend,
|
||||
LocalEncodingBackend,
|
||||
GCEEncodingBackend,
|
||||
classify_encoded_output,
|
||||
get_encoding_backend,
|
||||
)
|
||||
|
||||
|
||||
class TestClassifyEncodedOutput:
|
||||
"""Format classification must key off the trailing (format) parenthetical only,
|
||||
never the artist/title text — the NOMAD-1632 root cause."""
|
||||
|
||||
def test_720p_of_portrait_titled_song_is_not_misfiled_as_portrait(self):
|
||||
"""Regression for NOMAD-1632: 'Portrait of Jennie' 720p → mp4_720p, NOT portrait."""
|
||||
f = "Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4"
|
||||
assert classify_encoded_output(f) == "mp4_720p"
|
||||
|
||||
def test_real_portrait_video_classifies_as_portrait(self):
|
||||
f = "Nat King Cole - Portrait of Jennie (Final Karaoke Portrait 1080x1920).mp4"
|
||||
assert classify_encoded_output(f) == "portrait_mp4"
|
||||
|
||||
def test_4k_variants_of_portrait_titled_song(self):
|
||||
base = "Nat King Cole - Portrait of Jennie"
|
||||
assert classify_encoded_output(f"{base} (Final Karaoke Lossless 4k).mp4") == "mp4_4k_lossless"
|
||||
assert classify_encoded_output(f"{base} (Final Karaoke Lossless 4k).mkv") == "mkv_4k"
|
||||
assert classify_encoded_output(f"{base} (Final Karaoke Lossy 4k).mp4") == "mp4_4k_lossy"
|
||||
|
||||
def test_title_with_4k_or_720p_words_does_not_leak(self):
|
||||
"""A title literally containing '720p' must not steal the 4k lossy classification."""
|
||||
assert classify_encoded_output("DJ 720p - 4k Dreams (Final Karaoke Lossy 4k).mp4") == "mp4_4k_lossy"
|
||||
assert classify_encoded_output("DJ 720p - 4k Dreams (Final Karaoke Lossy 720p).mp4") == "mp4_720p"
|
||||
|
||||
def test_short_canonical_names(self):
|
||||
assert classify_encoded_output("jobs/x/finals/lossy_720p_mp4.mp4") == "mp4_720p"
|
||||
assert classify_encoded_output("jobs/x/finals/lossy_4k_mp4.mp4") == "mp4_4k_lossy"
|
||||
assert classify_encoded_output("jobs/x/finals/lossless_4k_mkv.mkv") == "mkv_4k"
|
||||
assert classify_encoded_output("jobs/x/finals/portrait_1080x1920.mp4") == "portrait_mp4"
|
||||
assert classify_encoded_output("jobs/x/packages/cdg_zip.zip") == "cdg_zip"
|
||||
assert classify_encoded_output("jobs/x/packages/txt_zip.zip") == "txt_zip"
|
||||
|
||||
def test_screens_and_unknown(self):
|
||||
assert classify_encoded_output("Artist - Title (Title).mov") == "title_mov"
|
||||
assert classify_encoded_output("Artist - Title (End).mov") == "end_mov"
|
||||
assert classify_encoded_output("Artist - Title (Karaoke).mp4") is None
|
||||
|
||||
def test_stray_files_do_not_slip_into_a_format_slot(self):
|
||||
"""Extension is pinned per format, and a file without a format parenthetical
|
||||
is unrecognised — so a stray file whose name merely contains a format word
|
||||
can't be misclassified and then falsely satisfy the completeness guard."""
|
||||
# Format word in the artist/title but wrong extension / no format tag.
|
||||
assert classify_encoded_output("Artist 720p notes.txt") is None
|
||||
assert classify_encoded_output("Artist - 720p Dreams.mp4") is None
|
||||
# Right tag, wrong extension.
|
||||
assert classify_encoded_output("Artist - Title (Final Karaoke Lossy 720p).mkv") is None
|
||||
assert classify_encoded_output("Artist - Title (Final Karaoke Lossless 4k).mov") is None
|
||||
# Short canonical name with a mismatched extension is rejected too.
|
||||
assert classify_encoded_output("jobs/x/finals/lossy_720p_mp4.mkv") is None
|
||||
|
||||
|
||||
class TestEncodingInput:
|
||||
"""Test EncodingInput dataclass."""
|
||||
|
||||
@@ -261,8 +313,12 @@ class TestGCEEncodingBackend:
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
# A healthy worker returns every requested format (see the completeness
|
||||
# guard in GCEEncodingBackend.encode).
|
||||
"output_files": {
|
||||
"mp4_4k_lossless": "gs://bucket/output/lossless.mp4",
|
||||
"mp4_4k_lossy": "gs://bucket/output/lossy.mp4",
|
||||
"mkv_4k": "gs://bucket/output/lossless.mkv",
|
||||
"mp4_720p": "gs://bucket/output/720p.mp4",
|
||||
}
|
||||
})
|
||||
@@ -288,6 +344,130 @@ class TestGCEEncodingBackend:
|
||||
assert output.encoding_backend == "gce"
|
||||
mock_service.encode_videos.assert_called_once()
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_portrait_titled_song_maps_720p(self, mock_get_service):
|
||||
"""Regression for NOMAD-1632: a song titled 'Portrait of Jennie' must still
|
||||
map its 720p to lossy_720p_mp4_path (not silently drop it as the portrait
|
||||
video), so the completeness guard passes and the 720p publishes."""
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"output_files": [
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mp4",
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mkv",
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 4k).mp4",
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4",
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Portrait 1080x1920).mp4",
|
||||
],
|
||||
})
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.mov",
|
||||
karaoke_video_path="/input/karaoke.mov",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
artist="Nat King Cole",
|
||||
title="Portrait of Jennie",
|
||||
options={
|
||||
"job_id": "j",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
output = await backend.encode(input_config)
|
||||
|
||||
assert output.success is True
|
||||
assert output.lossy_720p_mp4_path.endswith("(Final Karaoke Lossy 720p).mp4")
|
||||
assert output.portrait_mp4_path.endswith("(Final Karaoke Portrait 1080x1920).mp4")
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_fails_on_incomplete_output(self, mock_get_service):
|
||||
"""A worker that returns fewer formats than requested must fail loud.
|
||||
|
||||
Regression for the NOMAD-1632 MP4-720p sequence gap (2026-09-11): a
|
||||
fallback encoding worker returned the 4K + MKV finals but silently omitted
|
||||
the 720p, and the pipeline published an incomplete public release. Only the
|
||||
daily GDrive validator caught the gap ~24h later. The completeness guard
|
||||
must refuse a partial result so the job errors and is retried instead of
|
||||
publishing a track with no 720p.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
# Worker returned everything EXCEPT the 720p — exactly the NOMAD-1632 case.
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"output_files": [
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4",
|
||||
],
|
||||
})
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.mov",
|
||||
karaoke_video_path="/input/karaoke.mov",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
options={
|
||||
"job_id": "test-job",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
output = await backend.encode(input_config)
|
||||
|
||||
assert output.success is False
|
||||
assert "mp4_720p" in output.error_message
|
||||
# The formats that DID come back are still reported for debugging.
|
||||
assert output.output_files.get("mp4_4k_lossy")
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_empty_result_does_not_trip_completeness_guard(self, mock_get_service):
|
||||
"""An EMPTY result must NOT hard-fail via the completeness guard.
|
||||
|
||||
Regression for the v0.222.3 outage: a stale GCE job cache returns
|
||||
output_files=[] (finals deleted from GCS on an admin reset / re-run). The
|
||||
orchestrator recovers from this by downloading zero files, raising a
|
||||
"stale" RuntimeError, and re-encoding under a fresh job id. The guard must
|
||||
only fire on a PARTIAL result — an empty result must return success=True so
|
||||
that recovery path runs instead of a hard failure.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "cached",
|
||||
"output_files": [],
|
||||
})
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.mov",
|
||||
karaoke_video_path="/input/karaoke.mov",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
options={
|
||||
"job_id": "test-job",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
output = await backend.encode(input_config)
|
||||
|
||||
# Not blocked by the guard: the orchestrator's stale-cache re-encode handles it.
|
||||
assert output.success is True
|
||||
assert output.output_files == {}
|
||||
assert output.lossy_720p_mp4_path is None
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_failure(self, mock_get_service):
|
||||
@@ -353,9 +533,15 @@ class TestGCEEncodingBackend:
|
||||
when GCE worker returns a list instead of a dict.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
# Simulate GCE worker returning a list instead of dict
|
||||
# Simulate GCE worker returning a list instead of dict (with a complete
|
||||
# format set so the completeness guard passes and we isolate list handling).
|
||||
mock_service.encode_videos = AsyncMock(return_value=[
|
||||
{"output_files": {"mp4_4k_lossless": "gs://bucket/output/lossless.mp4"}}
|
||||
{"output_files": {
|
||||
"mp4_4k_lossless": "gs://bucket/output/lossless.mp4",
|
||||
"mp4_4k_lossy": "gs://bucket/output/lossy.mp4",
|
||||
"mkv_4k": "gs://bucket/output/lossless.mkv",
|
||||
"mp4_720p": "gs://bucket/output/720p.mp4",
|
||||
}}
|
||||
])
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
@@ -441,6 +627,9 @@ class TestGCEEncodingBackend:
|
||||
"status": "complete",
|
||||
"output_files": [
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4",
|
||||
"jobs/test/finals/Artist - Title (Title).mov",
|
||||
"jobs/test/finals/Artist - Title (End).mov",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Unit tests for near-real-time failure alerting (incident-hardening D1).
|
||||
|
||||
Covers the universal-net behaviour the spike-based error monitor can't provide:
|
||||
novel error signatures always alert, repeats within the window collapse, test/dev
|
||||
failures are skipped, and — critically — nothing here ever raises into the status
|
||||
write that triggers it.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services import ops_alerts
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# In-memory Firestore test double
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class _FakeSnap:
|
||||
def __init__(self, data):
|
||||
self._data = data
|
||||
self.exists = data is not None
|
||||
|
||||
def to_dict(self):
|
||||
return dict(self._data) if self._data is not None else None
|
||||
|
||||
|
||||
class _FakeDoc:
|
||||
def __init__(self, store, key):
|
||||
self._store = store
|
||||
self._key = key
|
||||
|
||||
def get(self):
|
||||
return _FakeSnap(self._store.get(self._key))
|
||||
|
||||
def set(self, data):
|
||||
self._store[self._key] = dict(data)
|
||||
|
||||
def update(self, data):
|
||||
self._store.setdefault(self._key, {}).update(data)
|
||||
|
||||
|
||||
class _FakeCollection:
|
||||
def __init__(self, store):
|
||||
self._store = store
|
||||
|
||||
def document(self, doc_id):
|
||||
return _FakeDoc(self._store, doc_id)
|
||||
|
||||
|
||||
class FakeFirestore:
|
||||
"""Mimics the subset of google.cloud.firestore.Client used by ops_alerts."""
|
||||
|
||||
def __init__(self, jobs=None):
|
||||
self._collections = {}
|
||||
# Seed the jobs collection so enrichment reads succeed.
|
||||
jobs_store = {}
|
||||
for job_id, doc in (jobs or {}).items():
|
||||
jobs_store[job_id] = doc
|
||||
self._collections["jobs"] = jobs_store
|
||||
|
||||
def collection(self, name):
|
||||
return _FakeCollection(self._collections.setdefault(name, {}))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def enabled(monkeypatch):
|
||||
monkeypatch.setenv("FAILURE_ALERTS_ENABLED", "true")
|
||||
# Deterministic throttle window for tests.
|
||||
monkeypatch.setenv("FAILURE_ALERT_THROTTLE_MINUTES", "30")
|
||||
monkeypatch.delenv("FAILURE_ALERT_SKIP_ENVIRONMENTS", raising=False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def captured(monkeypatch):
|
||||
"""Capture send_ops_alert calls instead of hitting Discord."""
|
||||
sent = []
|
||||
monkeypatch.setattr(ops_alerts, "send_ops_alert", lambda msg: sent.append(msg) or True)
|
||||
return sent
|
||||
|
||||
|
||||
def _job(environment="production", artist="A", title="B", brand="NOMAD-1632", error_message="boom"):
|
||||
return {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"request_metadata": {"environment": environment},
|
||||
"state_data": {"brand_code": brand},
|
||||
"error_message": error_message,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# send_ops_alert gating
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_send_ops_alert_disabled_returns_false(monkeypatch):
|
||||
monkeypatch.delenv("FAILURE_ALERTS_ENABLED", raising=False)
|
||||
monkeypatch.setattr(ops_alerts, "_is_enabled", lambda: False)
|
||||
assert ops_alerts.send_ops_alert("hi") is False
|
||||
|
||||
|
||||
def test_send_ops_alert_no_webhook_returns_false(monkeypatch):
|
||||
monkeypatch.setattr(ops_alerts, "_is_enabled", lambda: True)
|
||||
monkeypatch.setattr(ops_alerts, "_get_webhook_url", lambda: None)
|
||||
assert ops_alerts.send_ops_alert("hi") is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# notify_job_failed
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_novel_signature_alerts(enabled, captured):
|
||||
db = FakeFirestore(jobs={"job-1": _job(error_message="never seen this")})
|
||||
sent = ops_alerts.notify_job_failed(db, "jobs", "job-1", message="never seen this")
|
||||
assert sent is True
|
||||
assert len(captured) == 1
|
||||
assert "First time" in captured[0]
|
||||
assert "job-1" in captured[0]
|
||||
|
||||
|
||||
def test_repeat_within_window_is_suppressed(enabled, captured):
|
||||
db = FakeFirestore(jobs={
|
||||
"job-1": _job(),
|
||||
"job-2": _job(),
|
||||
})
|
||||
# Same error string -> same signature.
|
||||
ops_alerts.notify_job_failed(db, "jobs", "job-1", additional_fields={"error_message": "same err"})
|
||||
ops_alerts.notify_job_failed(db, "jobs", "job-2", additional_fields={"error_message": "same err"})
|
||||
assert len(captured) == 1 # second collapsed
|
||||
|
||||
|
||||
def test_distinct_signatures_each_alert(enabled, captured):
|
||||
db = FakeFirestore(jobs={"j1": _job(), "j2": _job()})
|
||||
ops_alerts.notify_job_failed(db, "jobs", "j1", additional_fields={"error_message": "error one"})
|
||||
ops_alerts.notify_job_failed(db, "jobs", "j2", additional_fields={"error_message": "totally different"})
|
||||
assert len(captured) == 2
|
||||
|
||||
|
||||
def test_test_environment_skipped(enabled, captured):
|
||||
db = FakeFirestore(jobs={"job-t": _job(environment="test")})
|
||||
sent = ops_alerts.notify_job_failed(db, "jobs", "job-t", message="boom")
|
||||
assert sent is False
|
||||
assert captured == []
|
||||
|
||||
|
||||
def test_disabled_environment_no_alert(monkeypatch, captured):
|
||||
monkeypatch.delenv("FAILURE_ALERTS_ENABLED", raising=False)
|
||||
monkeypatch.setattr(ops_alerts, "_is_enabled", lambda: False)
|
||||
db = FakeFirestore(jobs={"job-1": _job()})
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-1", message="boom") is False
|
||||
assert captured == []
|
||||
|
||||
|
||||
def test_best_effort_never_raises_on_broken_db(enabled, captured):
|
||||
class BrokenDB:
|
||||
def collection(self, name):
|
||||
raise RuntimeError("firestore exploded")
|
||||
|
||||
# Must not propagate. Enrichment + dedup both fail, so it fails OPEN and
|
||||
# still sends (missing a real outage is worse than an unenriched alert).
|
||||
result = ops_alerts.notify_job_failed(BrokenDB(), "jobs", "job-x", message="boom")
|
||||
assert result is True
|
||||
assert len(captured) == 1
|
||||
|
||||
|
||||
def test_fail_open_when_dedup_read_errors(enabled, captured, monkeypatch):
|
||||
"""If the dedup lookup fails we should still alert (missing an outage is worse)."""
|
||||
db = FakeFirestore(jobs={"job-1": _job()})
|
||||
monkeypatch.setattr(ops_alerts, "_should_alert", lambda *a, **k: (True, False, 0, None))
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-1", message="boom") is True
|
||||
assert len(captured) == 1
|
||||
|
||||
|
||||
def test_failed_delivery_does_not_suppress_next(enabled, monkeypatch):
|
||||
"""A failed Discord send must NOT advance the throttle window."""
|
||||
db = FakeFirestore(jobs={"job-1": _job(), "job-2": _job()})
|
||||
calls = []
|
||||
|
||||
def flaky_send(msg):
|
||||
calls.append(msg)
|
||||
return len(calls) > 1 # first send fails, second succeeds
|
||||
|
||||
monkeypatch.setattr(ops_alerts, "send_ops_alert", flaky_send)
|
||||
# First failure: send attempted but delivery fails → not acked.
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-1", additional_fields={"error_message": "same err"}) is False
|
||||
# Second failure, same signature, within window: because the first never
|
||||
# acked, this must still be attempted (not throttled away) and now succeed.
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-2", additional_fields={"error_message": "same err"}) is True
|
||||
assert len(calls) == 2
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Unit tests for the publish-boundary completeness invariant (incident-hardening G1).
|
||||
|
||||
These pin the exact behaviour that closes the NOMAD-1632 silent-partial class: a
|
||||
public GDrive release missing its 720p variant (or any expected output) must be
|
||||
reported as a shortfall, while a complete release — and any non-public job —
|
||||
reports nothing.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.services.publish_completeness import (
|
||||
compute_publish_shortfall,
|
||||
expected_gdrive_outputs,
|
||||
)
|
||||
|
||||
|
||||
def _config(gdrive_folder_id="folder-1", enable_cdg=True):
|
||||
return SimpleNamespace(
|
||||
gdrive_folder_id=gdrive_folder_id,
|
||||
enable_cdg=enable_cdg,
|
||||
artist="Nat King Cole",
|
||||
title="Portrait of Jennie",
|
||||
)
|
||||
|
||||
|
||||
def _result(gdrive_files, cdg_produced=True):
|
||||
"""A result whose CDG was produced by default (final_karaoke_cdg_zip set)."""
|
||||
return SimpleNamespace(
|
||||
gdrive_files=gdrive_files,
|
||||
brand_code="NOMAD-1632",
|
||||
final_karaoke_cdg_zip=("/tmp/x.zip" if cdg_produced else None),
|
||||
)
|
||||
|
||||
|
||||
class TestExpectedOutputs:
|
||||
def test_cdg_produced_expects_all_three(self):
|
||||
res = _result({}, cdg_produced=True)
|
||||
assert expected_gdrive_outputs(_config(enable_cdg=True), res) == ["mp4", "mp4_720p", "cdg"]
|
||||
|
||||
def test_cdg_not_produced_expects_two(self):
|
||||
res = _result({}, cdg_produced=False)
|
||||
assert expected_gdrive_outputs(_config(enable_cdg=True), res) == ["mp4", "mp4_720p"]
|
||||
|
||||
|
||||
class TestComputePublishShortfall:
|
||||
def test_complete_release_no_shortfall(self):
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({"mp4": "id1", "mp4_720p": "id2", "cdg": "id3"})
|
||||
assert compute_publish_shortfall(cfg, res) == []
|
||||
|
||||
def test_missing_720p_is_the_incident(self):
|
||||
"""The NOMAD-1632 case: 4K + CDG shipped, 720p silently skipped."""
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({"mp4": "id1", "cdg": "id3"})
|
||||
assert compute_publish_shortfall(cfg, res) == ["720p MP4"]
|
||||
|
||||
def test_missing_cdg_when_produced(self):
|
||||
"""CDG was produced but not distributed → real shortfall."""
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({"mp4": "id1", "mp4_720p": "id2"}, cdg_produced=True)
|
||||
assert compute_publish_shortfall(cfg, res) == ["CDG zip"]
|
||||
|
||||
def test_lyricless_skip_does_not_require_cdg(self):
|
||||
"""enable_cdg True but no CDG produced (lyric-less track) → no false alarm."""
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({"mp4": "id1", "mp4_720p": "id2"}, cdg_produced=False)
|
||||
assert compute_publish_shortfall(cfg, res) == []
|
||||
|
||||
def test_cdg_not_expected_when_disabled(self):
|
||||
cfg = _config(enable_cdg=False)
|
||||
res = _result({"mp4": "id1", "mp4_720p": "id2"}, cdg_produced=False)
|
||||
assert compute_publish_shortfall(cfg, res) == []
|
||||
|
||||
def test_empty_distribution_lists_all_expected(self):
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({}, cdg_produced=True)
|
||||
assert compute_publish_shortfall(cfg, res) == ["lossy 4K MP4", "720p MP4", "CDG zip"]
|
||||
|
||||
def test_empty_string_id_counts_as_missing(self):
|
||||
cfg = _config(enable_cdg=False)
|
||||
res = _result({"mp4": "id1", "mp4_720p": ""}, cdg_produced=False)
|
||||
assert compute_publish_shortfall(cfg, res) == ["720p MP4"]
|
||||
|
||||
def test_non_public_job_never_flags(self):
|
||||
"""No gdrive_folder_id → not a public-share release → always clean."""
|
||||
cfg = _config(gdrive_folder_id=None, enable_cdg=True)
|
||||
res = _result({})
|
||||
assert compute_publish_shortfall(cfg, res) == []
|
||||
|
||||
def test_none_gdrive_files_is_safe(self):
|
||||
cfg = _config(enable_cdg=False)
|
||||
res = _result(None, cdg_produced=False)
|
||||
assert compute_publish_shortfall(cfg, res) == ["lossy 4K MP4", "720p MP4"]
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
Tests for the render video worker CLI entry point (Cloud Run Jobs execution).
|
||||
|
||||
The render worker runs as a Cloud Run Job (video-encoding-job with an args
|
||||
override) so it survives Cloud Run Service deployment rollouts — as a
|
||||
BackgroundTask it was killed ~10s after SIGTERM whenever a deploy landed
|
||||
mid-render (incident 2026-09-13, job 41e06b90).
|
||||
|
||||
Exit-code contract (deliberately different from video_worker): the Cloud Run
|
||||
Job template has max_retries=2 and process_render_video handles every expected
|
||||
failure internally (park / fail_job / supersede-discard). A clean return —
|
||||
True OR False — must exit 0 so Cloud Run never re-runs the worker against a
|
||||
job that already moved to a non-render state. Only an escaped exception
|
||||
(crash before state was handled) exits 1 to request a Cloud Run retry.
|
||||
"""
|
||||
import sys
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.workers.render_video_worker import main
|
||||
|
||||
|
||||
def _run_main_with_args(job_id="job123"):
|
||||
return patch.object(sys, "argv", ["render_video_worker", "--job-id", job_id])
|
||||
|
||||
|
||||
class TestRenderVideoWorkerCli:
|
||||
def test_main_exits_zero_on_success(self):
|
||||
with _run_main_with_args(), \
|
||||
patch("backend.workers.render_video_worker.process_render_video",
|
||||
new=AsyncMock(return_value=True)):
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
main()
|
||||
assert exc_info.value.code == 0
|
||||
|
||||
def test_main_exits_zero_on_handled_failure(self):
|
||||
"""False means the worker already parked/failed/superseded the job —
|
||||
a Cloud Run retry would re-enter a job in a non-render state."""
|
||||
with _run_main_with_args(), \
|
||||
patch("backend.workers.render_video_worker.process_render_video",
|
||||
new=AsyncMock(return_value=False)):
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
main()
|
||||
assert exc_info.value.code == 0
|
||||
|
||||
def test_main_exits_nonzero_on_crash(self):
|
||||
"""An escaped exception means job state was NOT handled — exit 1 so
|
||||
Cloud Run's max_retries can re-run the worker."""
|
||||
with _run_main_with_args(), \
|
||||
patch("backend.workers.render_video_worker.process_render_video",
|
||||
new=AsyncMock(side_effect=RuntimeError("boom"))):
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
main()
|
||||
assert exc_info.value.code == 1
|
||||
|
||||
def test_main_passes_job_id(self):
|
||||
mock_worker = AsyncMock(return_value=True)
|
||||
with _run_main_with_args("abc999"), \
|
||||
patch("backend.workers.render_video_worker.process_render_video",
|
||||
new=mock_worker):
|
||||
with pytest.raises(SystemExit):
|
||||
main()
|
||||
mock_worker.assert_awaited_once_with("abc999")
|
||||
|
||||
def test_main_requires_job_id(self):
|
||||
with patch.object(sys, "argv", ["render_video_worker"]):
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
main()
|
||||
# argparse exits 2 on missing required argument
|
||||
assert exc_info.value.code == 2
|
||||
@@ -104,6 +104,9 @@ class TestIsDuetPropagation:
|
||||
job.style_assets = {}
|
||||
job.prep_only = False
|
||||
job.subtitle_offset_ms = 0
|
||||
# Real dispatch state — the worker itself transitions to
|
||||
# RENDERING_VIDEO (and skips jobs already in it / terminal).
|
||||
job.status = JobStatus.REVIEW_COMPLETE
|
||||
return job
|
||||
|
||||
def test_is_duet_true_passed_to_output_config_local_path(self):
|
||||
|
||||
@@ -23,7 +23,11 @@ from backend.models.job import JobStatus
|
||||
from backend.workers.registry import worker_registry
|
||||
|
||||
|
||||
def _build_minimal_job(status=JobStatus.RENDERING_VIDEO):
|
||||
def _build_minimal_job(status=JobStatus.REVIEW_COMPLETE):
|
||||
# Default matches the real entry state: the worker is dispatched with the
|
||||
# job in REVIEW_COMPLETE and transitions to RENDERING_VIDEO itself. A job
|
||||
# already in RENDERING_VIDEO at entry is skipped by the worker-side
|
||||
# idempotency gate (duplicate trigger / Cloud Run Job retry protection).
|
||||
job = MagicMock()
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Title"
|
||||
@@ -61,7 +65,15 @@ async def test_worker_registers_and_unregisters_on_success():
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_job_manager.transition_to_state.return_value = True
|
||||
|
||||
# Mirror real transitions on the shared mock so the supersession fence's
|
||||
# mid-render re-reads see RENDERING_VIDEO (a frozen REVIEW_COMPLETE would
|
||||
# read as "status reset" and discard the render).
|
||||
def _transition(job_id=None, new_status=None, **kwargs):
|
||||
job.status = new_status
|
||||
return True
|
||||
|
||||
mock_job_manager.transition_to_state.side_effect = _transition
|
||||
|
||||
mock_encoding_service = MagicMock()
|
||||
mock_encoding_service.is_enabled = True
|
||||
@@ -226,3 +238,56 @@ def test_park_active_render_jobs_continues_after_per_job_failure():
|
||||
|
||||
# The successful job should still have been parked
|
||||
assert parked == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_worker_skips_job_in_terminal_state():
|
||||
"""A stale/duplicate trigger for a finished job must never resurrect it.
|
||||
|
||||
The Cloud Run Job dispatch path bypasses the HTTP endpoint's
|
||||
_check_worker_idempotency guard, so the worker enforces this itself.
|
||||
"""
|
||||
from backend.workers import render_video_worker as rvw
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = _build_minimal_job(JobStatus.COMPLETE)
|
||||
|
||||
with patch.object(rvw, "JobManager", return_value=mock_job_manager), \
|
||||
patch.object(rvw, "StorageService"), \
|
||||
patch.object(rvw, "get_settings"), \
|
||||
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(rvw, "setup_job_logging", return_value=MagicMock()):
|
||||
result = await rvw.process_render_video("done-job")
|
||||
|
||||
assert result is False
|
||||
# Must not touch job state at all
|
||||
mock_job_manager.transition_to_state.assert_not_called()
|
||||
mock_job_manager.fail_job.assert_not_called()
|
||||
mock_job_manager.update_state_data.assert_not_called()
|
||||
# And must not leak a registry entry
|
||||
assert worker_registry.get_active_workers() == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_worker_skips_job_already_rendering():
|
||||
"""Re-entry on a job already in RENDERING_VIDEO (duplicate trigger, or a
|
||||
Cloud Run Job max_retries re-run after a crash) must be a clean no-op —
|
||||
NOT a hard fail via the same-state InvalidStateTransition path. A live
|
||||
render must not be disrupted; a dead one is recovered by the
|
||||
rendering_video_stuck sweep."""
|
||||
from backend.workers import render_video_worker as rvw
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = _build_minimal_job(JobStatus.RENDERING_VIDEO)
|
||||
|
||||
with patch.object(rvw, "JobManager", return_value=mock_job_manager), \
|
||||
patch.object(rvw, "StorageService"), \
|
||||
patch.object(rvw, "get_settings"), \
|
||||
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(rvw, "setup_job_logging", return_value=MagicMock()):
|
||||
result = await rvw.process_render_video("mid-render-job")
|
||||
|
||||
assert result is False
|
||||
mock_job_manager.transition_to_state.assert_not_called()
|
||||
mock_job_manager.fail_job.assert_not_called()
|
||||
assert worker_registry.get_active_workers() == {}
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Unit tests for the public song-request voting board routes (mocked service)."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes import requests_board
|
||||
from backend.api.routes.requests_board import optional_user_email
|
||||
from backend.models.song_request import SongRequest, Vote
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.services.song_request_service import RequestNotFound, SubmissionRateLimited
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
# Import at fixture time (not module level): some earlier test modules reload
|
||||
# backend.main / backend.api.dependencies, so a module-level capture would go stale.
|
||||
from backend.main import app as _app
|
||||
return _app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
# Override the require_auth object THIS router actually uses. The conftest autouse
|
||||
# fixture overrides dependencies.require_auth, but earlier tests that reload backend
|
||||
# modules can make that a different object than our router captured at import — so we
|
||||
# override our router's own reference, which is reload-proof.
|
||||
async def _mock_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.LIMITED, remaining_uses=999,
|
||||
message="test", is_admin=False, user_email="test@example.com",
|
||||
)
|
||||
app.dependency_overrides[requests_board.require_auth] = _mock_auth
|
||||
c = TestClient(app)
|
||||
yield c
|
||||
app.dependency_overrides.pop(requests_board.require_auth, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers():
|
||||
return {"Authorization": "Bearer test-token"}
|
||||
|
||||
|
||||
def _req(**kw) -> SongRequest:
|
||||
defaults = dict(
|
||||
id="r1",
|
||||
artist="The Beatles",
|
||||
title="Hey Jude",
|
||||
artist_raw="beatles",
|
||||
title_raw="hey jude",
|
||||
dedupe_key="the beatles|hey jude",
|
||||
submitted_by="test@example.com",
|
||||
source="human",
|
||||
status="open",
|
||||
vote_count=1,
|
||||
created_at=datetime(2026, 9, 2, tzinfo=timezone.utc),
|
||||
updated_at=datetime(2026, 9, 2, tzinfo=timezone.utc),
|
||||
)
|
||||
defaults.update(kw)
|
||||
return SongRequest(**defaults)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_service(monkeypatch):
|
||||
svc = MagicMock()
|
||||
monkeypatch.setattr(requests_board, "get_song_request_service", lambda: svc)
|
||||
return svc
|
||||
|
||||
|
||||
def test_submit_created(client, auth_headers, fake_service):
|
||||
fake_service.submit_request = AsyncMock(
|
||||
return_value=(_req(vote_count=1), False, "The Beatles", "Hey Jude")
|
||||
)
|
||||
fake_service.get_daily_vote.return_value = Vote(
|
||||
voter_email="test@example.com", voted_date="2026-09-02", request_id="r1", value=1
|
||||
)
|
||||
resp = client.post(
|
||||
"/api/requests-board/requests",
|
||||
json={"artist": "beatles", "title": "hey jude"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "created"
|
||||
assert data["canonical_artist"] == "The Beatles"
|
||||
assert data["was_corrected"] is True # "beatles" != "The Beatles"
|
||||
assert data["request"]["your_vote"] == 1
|
||||
# Never leak the submitter email
|
||||
assert "submitted_by" not in data["request"]
|
||||
|
||||
|
||||
def test_submit_dedupes_to_existing(client, auth_headers, fake_service):
|
||||
fake_service.submit_request = AsyncMock(
|
||||
return_value=(_req(vote_count=2), True, "The Beatles", "Hey Jude")
|
||||
)
|
||||
fake_service.get_daily_vote.return_value = None
|
||||
resp = client.post(
|
||||
"/api/requests-board/requests",
|
||||
json={"artist": "The Beatles", "title": "Hey Jude"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["status"] == "already_exists"
|
||||
assert resp.json()["request"]["vote_count"] == 2
|
||||
|
||||
|
||||
def test_submit_rate_limited(client, auth_headers, fake_service):
|
||||
fake_service.submit_request = AsyncMock(side_effect=SubmissionRateLimited())
|
||||
resp = client.post(
|
||||
"/api/requests-board/requests",
|
||||
json={"artist": "a", "title": "b"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert resp.status_code == 429
|
||||
|
||||
|
||||
def test_vote_ok(client, auth_headers, fake_service):
|
||||
fake_service.cast_vote.return_value = Vote(
|
||||
voter_email="test@example.com", voted_date="2026-09-02", request_id="r1", value=1
|
||||
)
|
||||
fake_service.get_request.return_value = _req(vote_count=5)
|
||||
fake_service.get_daily_vote.return_value = Vote(
|
||||
voter_email="test@example.com", voted_date="2026-09-02", request_id="r1", value=1
|
||||
)
|
||||
resp = client.post("/api/requests-board/requests/r1/vote", json={"direction": "up"}, headers=auth_headers)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["vote_count"] == 5
|
||||
assert resp.json()["your_vote"] == 1
|
||||
|
||||
|
||||
def test_vote_missing_request(client, auth_headers, fake_service):
|
||||
fake_service.cast_vote.side_effect = RequestNotFound("r1")
|
||||
resp = client.post("/api/requests-board/requests/r1/vote", json={"direction": "down"}, headers=auth_headers)
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_list_public_no_viewer(client, app, fake_service):
|
||||
"""GET /requests is public; with no viewer there is no per-user annotation."""
|
||||
app.dependency_overrides[optional_user_email] = lambda: None
|
||||
try:
|
||||
fake_service.list_active.return_value = [_req(id="r1", vote_count=3), _req(id="r2", vote_count=1)]
|
||||
fake_service.list_published.return_value = []
|
||||
resp = client.get("/api/requests-board/requests")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert [r["id"] for r in data["requests"]] == ["r1", "r2"]
|
||||
assert data["voted_today"] is None
|
||||
assert all(r["your_vote"] is None for r in data["requests"])
|
||||
assert all("submitted_by" not in r for r in data["requests"])
|
||||
finally:
|
||||
app.dependency_overrides.pop(optional_user_email, None)
|
||||
|
||||
|
||||
def test_list_annotates_viewer_vote(client, app, fake_service):
|
||||
app.dependency_overrides[optional_user_email] = lambda: "test@example.com"
|
||||
try:
|
||||
fake_service.list_active.return_value = [_req(id="r1"), _req(id="r2")]
|
||||
fake_service.list_published.return_value = []
|
||||
fake_service.get_daily_vote.return_value = Vote(
|
||||
voter_email="test@example.com", voted_date="2026-09-02", request_id="r2", value=-1
|
||||
)
|
||||
resp = client.get("/api/requests-board/requests")
|
||||
data = resp.json()
|
||||
assert data["voted_today"] is True
|
||||
assert data["your_vote_request_id"] == "r2"
|
||||
by_id = {r["id"]: r for r in data["requests"]}
|
||||
assert by_id["r2"]["your_vote"] == -1
|
||||
assert by_id["r1"]["your_vote"] is None
|
||||
finally:
|
||||
app.dependency_overrides.pop(optional_user_email, None)
|
||||
|
||||
|
||||
def test_me_status(client, auth_headers, fake_service):
|
||||
fake_service.get_daily_vote.return_value = Vote(
|
||||
voter_email="test@example.com", voted_date="2026-09-02", request_id="r9", value=1
|
||||
)
|
||||
resp = client.get("/api/requests-board/me", headers=auth_headers)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == {"voted_today": True, "request_id": "r9", "value": 1}
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Tests for board sign-in plumbing: the convert-to-gen credit claim + purpose field."""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes import users as users_routes
|
||||
from backend.models.user import SendMagicLinkRequest
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
# Fixture-time import — see note in test_requests_board_routes.py (earlier modules
|
||||
# reload backend.main / dependencies, so a module-level capture would go stale).
|
||||
from backend.main import app as _app
|
||||
return _app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
# Override the require_auth object the users router actually uses (reload-proof).
|
||||
async def _mock_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.LIMITED, remaining_uses=999,
|
||||
message="test", is_admin=False, user_email="test@example.com",
|
||||
)
|
||||
app.dependency_overrides[users_routes.require_auth] = _mock_auth
|
||||
c = TestClient(app)
|
||||
yield c
|
||||
app.dependency_overrides.pop(users_routes.require_auth, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers():
|
||||
return {"Authorization": "Bearer test-token"}
|
||||
|
||||
|
||||
def test_send_magic_link_request_accepts_purpose():
|
||||
req = SendMagicLinkRequest(email="a@b.com", purpose="requests_board")
|
||||
assert req.purpose == "requests_board"
|
||||
# Backwards compatible: purpose is optional
|
||||
assert SendMagicLinkRequest(email="a@b.com").purpose is None
|
||||
|
||||
|
||||
def _override_user_service(app, svc):
|
||||
app.dependency_overrides[get_user_service] = lambda: svc
|
||||
|
||||
|
||||
def test_claim_welcome_credit_grants(client, app, auth_headers):
|
||||
svc = MagicMock()
|
||||
svc.grant_welcome_credits_if_eligible.return_value = (True, "granted")
|
||||
svc.get_user.return_value = MagicMock(credits=1)
|
||||
svc.NEW_USER_FREE_CREDITS = 1
|
||||
_override_user_service(app, svc)
|
||||
try:
|
||||
resp = client.post("/api/users/claim-welcome-credit", headers=auth_headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data == {"status": "granted", "credits": 1, "credits_granted": 1}
|
||||
svc.grant_welcome_credits_if_eligible.assert_called_once()
|
||||
finally:
|
||||
app.dependency_overrides.pop(get_user_service, None)
|
||||
|
||||
|
||||
def test_claim_welcome_credit_idempotent_already_granted(client, app, auth_headers):
|
||||
svc = MagicMock()
|
||||
svc.grant_welcome_credits_if_eligible.return_value = (False, "already_granted")
|
||||
svc.get_user.return_value = MagicMock(credits=1)
|
||||
svc.NEW_USER_FREE_CREDITS = 1
|
||||
_override_user_service(app, svc)
|
||||
try:
|
||||
resp = client.post("/api/users/claim-welcome-credit", headers=auth_headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "already_granted"
|
||||
assert data["credits_granted"] == 0
|
||||
finally:
|
||||
app.dependency_overrides.pop(get_user_service, None)
|
||||
@@ -512,6 +512,82 @@ class TestWorkerService:
|
||||
assert "--job-id" in str(override_args)
|
||||
assert "test123" in str(override_args)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_render_video_worker_routes_to_cloud_run_job(self):
|
||||
"""Test that render worker routes to Cloud Run Jobs when enabled.
|
||||
|
||||
When USE_CLOUD_RUN_JOBS_FOR_RENDER=true and ENABLE_CLOUD_TASKS=true,
|
||||
trigger_render_video_worker should dispatch a Cloud Run Job (reusing
|
||||
video-encoding-job with a render_video_worker args override) instead
|
||||
of posting to the internal HTTP endpoint. As a BackgroundTask on the
|
||||
service, the render poll was killed ~10s after SIGTERM whenever a
|
||||
deploy rollout landed mid-render, freezing the job at rendering_video
|
||||
(see incident 2026-09-13, job 41e06b90).
|
||||
"""
|
||||
from backend.services.worker_service import WorkerService, reset_worker_service
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_render = True
|
||||
|
||||
mock_jobs_client = MagicMock()
|
||||
mock_operation = MagicMock()
|
||||
mock_operation.metadata = "test-metadata"
|
||||
mock_jobs_client.run_job.return_value = mock_operation
|
||||
|
||||
mock_run_v2 = MagicMock()
|
||||
mock_run_v2.JobsClient.return_value = mock_jobs_client
|
||||
mock_run_v2.RunJobRequest = MagicMock()
|
||||
mock_run_v2.RunJobRequest.Overrides = MagicMock()
|
||||
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
|
||||
|
||||
import google.cloud
|
||||
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
|
||||
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
|
||||
service = WorkerService()
|
||||
result = await service.trigger_render_video_worker("test456")
|
||||
|
||||
assert result is True
|
||||
mock_jobs_client.run_job.assert_called_once()
|
||||
|
||||
# Reuses the video-encoding-job Cloud Run Job resource
|
||||
call_args = mock_run_v2.RunJobRequest.call_args
|
||||
assert call_args is not None
|
||||
assert "video-encoding-job" in str(call_args)
|
||||
|
||||
# But overrides the module to the render worker with the job id
|
||||
override_args = mock_run_v2.RunJobRequest.Overrides.ContainerOverride.call_args
|
||||
assert "backend.workers.render_video_worker" in str(override_args)
|
||||
assert "--job-id" in str(override_args)
|
||||
assert "test456" in str(override_args)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_render_video_worker_flag_off_uses_legacy_path(self):
|
||||
"""With USE_CLOUD_RUN_JOBS_FOR_RENDER off, the legacy Cloud Tasks /
|
||||
HTTP path is used and no Cloud Run Job is dispatched (rollback path)."""
|
||||
from backend.services.worker_service import WorkerService, reset_worker_service
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_render = False
|
||||
|
||||
service = WorkerService()
|
||||
with patch.object(service, '_trigger_worker_cloud_run_job', new=AsyncMock()) as mock_crj, \
|
||||
patch.object(service, 'trigger_worker', new=AsyncMock(return_value=True)) as mock_legacy:
|
||||
result = await service.trigger_render_video_worker("test789")
|
||||
|
||||
assert result is True
|
||||
mock_crj.assert_not_called()
|
||||
mock_legacy.assert_called_once_with("render-video", "test789")
|
||||
|
||||
|
||||
class TestWorkerServiceWarmup:
|
||||
"""Test encoding worker warmup in trigger methods."""
|
||||
@@ -825,12 +901,56 @@ class TestFirestoreService:
|
||||
|
||||
assert job is None
|
||||
|
||||
def test_failed_status_triggers_failure_alert(self):
|
||||
"""Incident-hardening D1: a transition to FAILED fires the failure alert."""
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_client = MagicMock()
|
||||
mock_firestore.Client.return_value = mock_client
|
||||
mock_collection = MagicMock()
|
||||
mock_client.collection.return_value = mock_collection
|
||||
mock_collection.document.return_value = MagicMock()
|
||||
|
||||
firestore_service = FirestoreService()
|
||||
with patch('backend.services.ops_alerts.notify_job_failed') as mock_notify:
|
||||
firestore_service.update_job_status("job1", JobStatus.FAILED, message="boom")
|
||||
mock_notify.assert_called_once()
|
||||
# Reuses the caller's client + collection (no second Firestore client).
|
||||
_, kwargs = mock_notify.call_args
|
||||
assert kwargs["job_id"] == "job1"
|
||||
assert kwargs["db"] is mock_client
|
||||
|
||||
def test_non_failed_status_does_not_alert(self):
|
||||
"""A normal status transition must NOT fire the failure alert."""
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_client = MagicMock()
|
||||
mock_firestore.Client.return_value = mock_client
|
||||
mock_client.collection.return_value.document.return_value = MagicMock()
|
||||
|
||||
firestore_service = FirestoreService()
|
||||
with patch('backend.services.ops_alerts.notify_job_failed') as mock_notify:
|
||||
firestore_service.update_job_status("job1", JobStatus.COMPLETE, message="done")
|
||||
mock_notify.assert_not_called()
|
||||
|
||||
def test_failure_alert_error_does_not_break_status_write(self):
|
||||
"""If the alerter raises, the status write must still succeed (best-effort)."""
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_client = MagicMock()
|
||||
mock_firestore.Client.return_value = mock_client
|
||||
mock_doc_ref = MagicMock()
|
||||
mock_client.collection.return_value.document.return_value = mock_doc_ref
|
||||
|
||||
firestore_service = FirestoreService()
|
||||
with patch('backend.services.ops_alerts.notify_job_failed', side_effect=RuntimeError("x")):
|
||||
# Should not raise.
|
||||
firestore_service.update_job_status("job1", JobStatus.FAILED, message="boom")
|
||||
mock_doc_ref.update.assert_called_once()
|
||||
|
||||
def test_update_job(self):
|
||||
"""Test updating a job in Firestore."""
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_client = MagicMock()
|
||||
mock_firestore.Client.return_value = mock_client
|
||||
|
||||
|
||||
mock_collection = MagicMock()
|
||||
mock_client.collection.return_value = mock_collection
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Pure-logic unit tests for the song-request board (no Firestore needed)."""
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from backend.api.routes.requests_board import _to_public, _was_corrected
|
||||
from backend.models.song_request import SongRequest, SubmitRequestBody
|
||||
from backend.services.song_request_service import (
|
||||
SongRequestService,
|
||||
_dedupe_key,
|
||||
_utc_today,
|
||||
)
|
||||
|
||||
|
||||
def _req(**kw) -> SongRequest:
|
||||
d = dict(
|
||||
id="r1",
|
||||
artist="The Beatles",
|
||||
title="Hey Jude",
|
||||
artist_raw="The Beatles",
|
||||
title_raw="Hey Jude",
|
||||
dedupe_key=_dedupe_key("The Beatles", "Hey Jude"),
|
||||
submitted_by="a@b.com",
|
||||
created_at=datetime(2026, 9, 2, tzinfo=timezone.utc),
|
||||
updated_at=datetime(2026, 9, 2, tzinfo=timezone.utc),
|
||||
)
|
||||
d.update(kw)
|
||||
return SongRequest(**d)
|
||||
|
||||
|
||||
def test_dedupe_key_normalizes_case_accents_and_ampersand():
|
||||
# Case/whitespace/punct fold, and '&' == 'and'
|
||||
assert _dedupe_key("The Beatles", "Hey Jude") == _dedupe_key(" the beatles ", "hey jude!")
|
||||
assert _dedupe_key("Simon & Garfunkel", "x") == _dedupe_key("Simon and Garfunkel", "x")
|
||||
assert _dedupe_key("Beyoncé", "Halo") == _dedupe_key("beyonce", "halo")
|
||||
|
||||
|
||||
def test_dedupe_key_distinguishes_different_songs():
|
||||
assert _dedupe_key("The Beatles", "Hey Jude") != _dedupe_key("The Beatles", "Let It Be")
|
||||
|
||||
|
||||
def test_utc_today_format():
|
||||
assert re.fullmatch(r"\d{4}-\d{2}-\d{2}", _utc_today())
|
||||
|
||||
|
||||
def test_vote_doc_id_encodes_one_per_day():
|
||||
assert SongRequestService._vote_doc_id("a@b.com", "2026-09-02") == "a@b.com__2026-09-02"
|
||||
|
||||
|
||||
def test_was_corrected_true_when_canonical_differs():
|
||||
assert _was_corrected(_req(artist_raw="beatles", artist="The Beatles")) is True
|
||||
|
||||
|
||||
def test_was_corrected_false_when_only_cosmetic_whitespace():
|
||||
# Same after normalization → not flagged as a correction
|
||||
assert _was_corrected(_req(artist_raw="The Beatles", artist="The Beatles", title_raw="hey jude", title="Hey Jude")) is False
|
||||
|
||||
|
||||
def test_submit_body_rejects_blank_artist_or_title():
|
||||
with pytest.raises(ValidationError):
|
||||
SubmitRequestBody(artist=" ", title="Hey Jude")
|
||||
with pytest.raises(ValidationError):
|
||||
SubmitRequestBody(artist="The Beatles", title=" ")
|
||||
|
||||
|
||||
def test_submit_body_strips_whitespace():
|
||||
body = SubmitRequestBody(artist=" The Beatles ", title=" Hey Jude ")
|
||||
assert body.artist == "The Beatles"
|
||||
assert body.title == "Hey Jude"
|
||||
|
||||
|
||||
def test_to_public_hides_email_and_serializes():
|
||||
pub = _to_public(_req(vote_count=4), your_vote=1)
|
||||
dumped = pub.model_dump()
|
||||
assert "submitted_by" not in dumped
|
||||
assert dumped["vote_count"] == 4
|
||||
assert dumped["your_vote"] == 1
|
||||
assert dumped["created_at"] == "2026-09-02T00:00:00+00:00"
|
||||
@@ -2182,3 +2182,178 @@ class TestRedistributeModeProgress:
|
||||
|
||||
jm.transition_to_state.assert_called_once()
|
||||
jm.update_job.assert_not_called()
|
||||
|
||||
|
||||
class TestEncodePublishSeam:
|
||||
"""Composed integration test of the encode→publish seam (hardening plan T1).
|
||||
|
||||
Both NOMAD-1632 bugs lived in the boundary between ``GCEEncodingBackend.encode()``
|
||||
and the orchestrator's ``_run_encoding`` / ``_download_gce_encoded_files``, yet
|
||||
NO existing test composes those two real layers — the stale-cache test mocks the
|
||||
*entire* backend, so the real classifier and completeness guard never run inside
|
||||
an orchestrator test. These tests wire the **real** backend to the **real**
|
||||
orchestrator and patch only the network boundary (the worker's ``encode_videos``
|
||||
call) and storage (GCS download), replaying the golden fixtures from
|
||||
``backend/tests/fixtures/encoding/``.
|
||||
|
||||
Asserted shapes:
|
||||
- empty → guard must NOT trip → 0 downloads → "stale" RuntimeError →
|
||||
re-encode recovers (Failure B path).
|
||||
- partial → completeness guard trips → job fails loud (Failure A defense).
|
||||
- complete → success, all result attrs populated with local paths.
|
||||
- malformed → classified out → treated as empty (no mis-slotting, no crash) →
|
||||
recovered via the same stale path.
|
||||
"""
|
||||
|
||||
FIXTURES_DIR = (
|
||||
os.path.join(os.path.dirname(__file__), "fixtures", "encoding")
|
||||
)
|
||||
|
||||
def _load_fixture(self, name):
|
||||
import json
|
||||
with open(os.path.join(self.FIXTURES_DIR, f"{name}.json")) as fh:
|
||||
return json.load(fh)
|
||||
|
||||
def _make_config(self, temp_dir):
|
||||
return OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Nat King Cole",
|
||||
title="Portrait of Jennie",
|
||||
title_video_path=os.path.join(temp_dir, "title.mov"),
|
||||
karaoke_video_path=os.path.join(temp_dir, "karaoke.mkv"),
|
||||
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
|
||||
output_dir=temp_dir,
|
||||
encoding_backend="gce", # exercise the REAL GCEEncodingBackend
|
||||
)
|
||||
|
||||
def _make_storage(self):
|
||||
"""Storage mock: no custom-instrumental staging; downloads write a file."""
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.list_files = MagicMock(return_value=[])
|
||||
|
||||
def _download(gcs_path, local_path):
|
||||
with open(local_path, "w") as f:
|
||||
f.write("fake encoded bytes")
|
||||
|
||||
mock_storage.download_file = MagicMock(side_effect=_download)
|
||||
return mock_storage
|
||||
|
||||
def _patch_worker(self, *, side_effect=None, return_value=None):
|
||||
"""Patch ONLY the network boundary: the GCE worker's encode_videos.
|
||||
|
||||
Returns (context_manager, mock_service). The real backend, real
|
||||
classifier, real completeness guard and real orchestrator all run.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(
|
||||
side_effect=side_effect, return_value=return_value
|
||||
)
|
||||
cm = patch(
|
||||
"backend.services.encoding_service.get_encoding_service",
|
||||
return_value=mock_service,
|
||||
)
|
||||
return cm, mock_service
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_output_recovers_via_reencode(self):
|
||||
"""Failure B: empty output_files is recoverable, NOT a guard failure.
|
||||
|
||||
Real encode() must return success (guard does not fire on empty) →
|
||||
orchestrator downloads 0 files → raises the 'stale' RuntimeError →
|
||||
re-encodes under a fresh job id → recovers.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
self._make_config(temp_dir), storage=self._make_storage()
|
||||
)
|
||||
cm, mock_service = self._patch_worker(
|
||||
side_effect=[self._load_fixture("empty"), self._load_fixture("success")]
|
||||
)
|
||||
with cm:
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
# encode() ran twice: empty (recoverable) then the fresh re-encode.
|
||||
assert mock_service.encode_videos.call_count == 2
|
||||
# The retry used a fresh suffixed worker job id.
|
||||
retry_job_id = mock_service.encode_videos.call_args_list[1].kwargs["job_id"]
|
||||
assert retry_job_id.startswith("test-job_retry_")
|
||||
# Recovered: results point at downloaded local files.
|
||||
assert orchestrator.result.final_video is not None
|
||||
assert orchestrator.result.final_video.startswith(temp_dir)
|
||||
assert orchestrator.result.final_video_720p is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_partial_output_fails_loud(self):
|
||||
"""Failure A defense: a partial result (720p missing) trips the guard and
|
||||
fails the job loudly rather than publishing an incomplete release."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
self._make_config(temp_dir), storage=self._make_storage()
|
||||
)
|
||||
cm, mock_service = self._patch_worker(
|
||||
return_value=self._load_fixture("partial")
|
||||
)
|
||||
with cm:
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
msg = str(exc_info.value)
|
||||
assert "incomplete" in msg.lower()
|
||||
assert "mp4_720p" in msg
|
||||
# No retry — a partial result is a defect, not a recoverable empty.
|
||||
assert mock_service.encode_videos.call_count == 1
|
||||
# Nothing was published / downloaded.
|
||||
assert orchestrator.result.final_video is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_complete_output_populates_all_results(self):
|
||||
"""Happy path: all four formats present → success, all attrs populated
|
||||
with local downloaded paths. Uses the NOMAD-1632 title to prove the
|
||||
720p whose title contains 'Portrait' maps correctly."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
storage = self._make_storage()
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
self._make_config(temp_dir), storage=storage
|
||||
)
|
||||
cm, mock_service = self._patch_worker(
|
||||
return_value=self._load_fixture("success")
|
||||
)
|
||||
with cm:
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
assert mock_service.encode_videos.call_count == 1
|
||||
for attr in (
|
||||
"final_video",
|
||||
"final_video_mkv",
|
||||
"final_video_lossy",
|
||||
"final_video_720p",
|
||||
):
|
||||
val = getattr(orchestrator.result, attr)
|
||||
assert val is not None, f"{attr} not populated"
|
||||
assert val.startswith(temp_dir), f"{attr} not a downloaded local path"
|
||||
assert storage.download_file.called
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_malformed_output_treated_as_empty(self):
|
||||
"""Malformed names (stray / wrong-extension) classify to nothing, so the
|
||||
guard must NOT mis-fire or mis-slot — the result is treated as empty.
|
||||
With persistently malformed output, that surfaces as the recoverable
|
||||
'stale' RuntimeError (handled, not a crash)."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
self._make_config(temp_dir), storage=self._make_storage()
|
||||
)
|
||||
cm, mock_service = self._patch_worker(
|
||||
side_effect=[
|
||||
self._load_fixture("malformed"),
|
||||
self._load_fixture("malformed"),
|
||||
]
|
||||
)
|
||||
with cm:
|
||||
with pytest.raises(RuntimeError, match="stale"):
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
# Classified-out → empty → recoverable path attempted (re-encode),
|
||||
# which with still-malformed output raises the stale signal again.
|
||||
assert mock_service.encode_videos.call_count == 2
|
||||
assert orchestrator.result.final_video is None
|
||||
@@ -123,7 +123,11 @@ def test_bump_worker_generation_is_best_effort():
|
||||
# render worker (GCE path) supersession behaviour
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _render_job(generation=1):
|
||||
def _render_job(generation=1, status=JobStatus.RENDERING_VIDEO):
|
||||
# Entry snapshots (job_start) must use REVIEW_COMPLETE — the real dispatch
|
||||
# state. A job already in RENDERING_VIDEO at entry is skipped by the
|
||||
# worker-side idempotency gate (duplicate trigger / CRJ retry protection).
|
||||
# Mid-render re-read snapshots (job_after) stay RENDERING_VIDEO.
|
||||
job = MagicMock()
|
||||
job.artist = "John Maus"
|
||||
job.title = "The Fear"
|
||||
@@ -134,7 +138,7 @@ def _render_job(generation=1):
|
||||
job.prep_only = False
|
||||
job.state_data = {"worker_generation": generation, "is_duet": False}
|
||||
job.file_urls = {}
|
||||
job.status = JobStatus.RENDERING_VIDEO
|
||||
job.status = status
|
||||
return job
|
||||
|
||||
|
||||
@@ -187,7 +191,7 @@ async def _run_gce_render(job_start, job_after, transition_side_effect=None):
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_superseded_by_status_reset_does_not_fail_job():
|
||||
"""Admin reset moved the job to awaiting_review mid-render → discard, don't fail."""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=1)
|
||||
job_after.status = "awaiting_review" # reset out from under the render
|
||||
|
||||
@@ -207,7 +211,7 @@ async def test_render_superseded_by_status_reset_does_not_fail_job():
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_superseded_by_generation_bump_does_not_fail_job():
|
||||
"""A newer render was triggered (generation bumped) → discard the stale run."""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=2) # newer run took over
|
||||
|
||||
result, jm = await _run_gce_render(job_start, job_after)
|
||||
@@ -225,7 +229,7 @@ async def test_invalid_terminal_transition_is_graceful_when_superseded():
|
||||
reset moved the job to awaiting_review). The worker must bail gracefully,
|
||||
exactly reproducing and fixing the 7f457087 incident.
|
||||
"""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=1)
|
||||
job_after.status = "awaiting_review" # reset confirmed on re-read in the handler
|
||||
|
||||
@@ -252,7 +256,7 @@ async def test_invalid_transition_when_not_superseded_still_fails():
|
||||
workflow defect — it must still fail the job (loudly) rather than be silently
|
||||
swallowed and leave the job stuck. Guards against over-broad error suppression.
|
||||
"""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=1) # same gen + still rendering_video => NOT superseded
|
||||
|
||||
invalid = InvalidStateTransitionError(
|
||||
@@ -272,7 +276,7 @@ async def test_progress_callback_skips_update_when_superseded():
|
||||
"""A stale render's progress ticks must not drag a reset job's progress bar."""
|
||||
from backend.workers import render_video_worker as rvw
|
||||
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
superseded = _render_job(generation=2) # reset bumped the fence mid-render
|
||||
|
||||
jm = MagicMock()
|
||||
@@ -318,7 +322,7 @@ async def test_progress_callback_skips_update_when_superseded():
|
||||
@pytest.mark.asyncio
|
||||
async def test_normal_render_still_completes():
|
||||
"""Un-superseded render must still write outputs and transition to INSTRUMENTAL_SELECTED."""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=1) # same gen, still rendering_video
|
||||
|
||||
result, jm = await _run_gce_render(job_start, job_after)
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Tests for the shared YouTube back-catalogue rewrite logic."""
|
||||
import pytest
|
||||
|
||||
from backend.services import youtube_backfill as bf
|
||||
|
||||
|
||||
def _video(title, description="", category_id="10", vid="vid123"):
|
||||
return {"id": vid, "snippet": {"title": title, "description": description, "categoryId": category_id}}
|
||||
|
||||
|
||||
class TestClassify:
|
||||
def test_standard_karaoke_title_with_brand_code(self):
|
||||
c = bf.classify(_video(
|
||||
"Coldplay - Yellow (Karaoke)",
|
||||
"Karaoke video created with Nomad Karaoke\n\nBrand Code: NOMAD-1603",
|
||||
))
|
||||
assert c["is_karaoke"] and c["eligible"]
|
||||
assert c["artist"] == "Coldplay" and c["song_title"] == "Yellow"
|
||||
assert c["brand_code"] == "NOMAD-1603"
|
||||
assert c["parse_confidence"] == "high"
|
||||
|
||||
def test_official_karaoke_version_suffix(self):
|
||||
c = bf.classify(_video("Adele - Hello (Official Karaoke Version)"))
|
||||
assert c["eligible"] and c["artist"] == "Adele" and c["song_title"] == "Hello"
|
||||
|
||||
def test_fiverr_era_video_is_eligible(self):
|
||||
c = bf.classify(_video(
|
||||
"Queen - Bohemian Rhapsody (Karaoke)",
|
||||
"This is a karaoke (instrumental) version...\nhttps://www.fiverr.com/share/j2aLvm",
|
||||
))
|
||||
assert c["kind"] == "fiverr" and c["eligible"]
|
||||
|
||||
def test_terse_new_template_detected(self):
|
||||
c = bf.classify(_video(
|
||||
"Taylor Swift - Cruel Summer (Karaoke)",
|
||||
"AI-powered vocal separation and synchronized lyrics.\n\nBrand Code: NOMAD-0009",
|
||||
))
|
||||
assert c["kind"] == "terse_new" and c["eligible"]
|
||||
assert c["brand_code"] == "NOMAD-0009"
|
||||
|
||||
def test_npbrand_code_parsed(self):
|
||||
c = bf.classify(_video("Artist - Song (Karaoke)", "Brand Code: NOMADNP-0042"))
|
||||
assert c["brand_code"] == "NOMADNP-0042"
|
||||
|
||||
def test_no_brand_code_still_eligible(self):
|
||||
c = bf.classify(_video("Oasis - Wonderwall (Karaoke)", "some description"))
|
||||
assert c["eligible"] and c["brand_code"] is None
|
||||
|
||||
def test_non_karaoke_tutorial_is_skipped(self):
|
||||
c = bf.classify(_video("Channel Trailer", "Welcome to my channel"))
|
||||
assert not c["is_karaoke"] and not c["eligible"] and c["kind"] == "non_karaoke"
|
||||
|
||||
def test_karaoke_word_but_unparseable_title_not_eligible(self):
|
||||
c = bf.classify(_video("How I Make Karaoke Videos With AI"))
|
||||
assert c["is_karaoke"] and not c["eligible"] and c["parse_confidence"] == "none"
|
||||
|
||||
def test_medium_confidence_hyphenated_not_auto_eligible(self):
|
||||
c = bf.classify(_video('YouTube "Reused content" appeal - Nomad Karaoke Explanation'))
|
||||
assert c["is_karaoke"] and c["parse_confidence"] == "medium" and not c["eligible"]
|
||||
|
||||
def test_endash_separator_supported(self):
|
||||
c = bf.classify(_video("Beyoncé – Halo (Karaoke)"))
|
||||
assert c["eligible"] and c["artist"] == "Beyoncé" and c["song_title"] == "Halo"
|
||||
|
||||
|
||||
class TestBuildEntries:
|
||||
def test_targets_and_skip_and_override(self):
|
||||
videos = {
|
||||
"a": _video("Coldplay - Yellow (Karaoke)", "Brand Code: NOMAD-1603", vid="a"),
|
||||
"b": _video("How I Make Karaoke Videos", vid="b"), # medium, not eligible
|
||||
"c": _video("Some Artist - Some Song (Karaoke)", "old desc", vid="c"),
|
||||
}
|
||||
order = ["a", "b", "c"]
|
||||
entries = bf.build_entries(
|
||||
videos, order,
|
||||
skip_ids={"c"}, # skip the otherwise-eligible one
|
||||
include_overrides={"b": {"artist": "The Band", "song_title": "The Tune"}},
|
||||
)
|
||||
by = {e["video_id"]: e for e in entries}
|
||||
assert by["a"]["target"] and by["a"]["will_change"]
|
||||
# 'b' force-included with overridden artist/title
|
||||
assert by["b"]["forced_include"] and by["b"]["target"]
|
||||
assert by["b"]["artist"] == "The Band" and by["b"]["song_title"] == "The Tune"
|
||||
assert by["b"]["parse_confidence"] == "override"
|
||||
# 'c' skipped -> not a target
|
||||
assert by["c"]["in_skip_list"] and not by["c"]["target"]
|
||||
|
||||
def test_will_change_false_when_already_current(self):
|
||||
from backend.services.youtube_description import render_youtube_description
|
||||
# Brand code must be the real 4-digit form so classify re-extracts it and
|
||||
# render_for reproduces the identical description.
|
||||
current = render_youtube_description(artist="Coldplay", title="Yellow", brand_code="NOMAD-1603")
|
||||
v = _video("Coldplay - Yellow (Karaoke)", current, vid="x")
|
||||
entries = bf.build_entries({"x": v}, ["x"], skip_ids=set(), include_overrides={})
|
||||
assert entries[0]["target"]
|
||||
assert entries[0]["brand_code"] == "NOMAD-1603"
|
||||
assert entries[0]["will_change"] is False
|
||||
|
||||
|
||||
class TestBuildUpdateSnippet:
|
||||
def test_preserves_title_category_and_swaps_description(self):
|
||||
entry = bf.classify(_video("Coldplay - Yellow (Karaoke)", "Brand Code: NOMAD-1603"))
|
||||
current = {"title": "Coldplay - Yellow (Karaoke)", "categoryId": "10",
|
||||
"tags": ["old", "tags"], "description": "old"}
|
||||
body = bf.build_update_snippet(current, entry, enrich_tags=False)
|
||||
assert body["title"] == "Coldplay - Yellow (Karaoke)"
|
||||
assert body["categoryId"] == "10"
|
||||
assert body["tags"] == ["old", "tags"] # preserved
|
||||
assert "nomadkaraoke.com/r/youtube" in body["description"]
|
||||
assert "AI" not in body["description"]
|
||||
|
||||
def test_enrich_tags_replaces_tags(self):
|
||||
entry = bf.classify(_video("Coldplay - Yellow (Karaoke)"))
|
||||
current = {"title": "Coldplay - Yellow (Karaoke)", "categoryId": "10", "tags": ["old"]}
|
||||
body = bf.build_update_snippet(current, entry, enrich_tags=True)
|
||||
assert "karaoke" in body["tags"]
|
||||
assert "Coldplay" in body["tags"]
|
||||
assert body["tags"] != ["old"]
|
||||
|
||||
def test_missing_category_defaults_to_music(self):
|
||||
entry = bf.classify(_video("Coldplay - Yellow (Karaoke)"))
|
||||
body = bf.build_update_snippet({"title": "x"}, entry, enrich_tags=False)
|
||||
assert body["categoryId"] == bf.DEFAULT_MUSIC_CATEGORY
|
||||
|
||||
def test_readonly_fields_dropped(self):
|
||||
entry = bf.classify(_video("Coldplay - Yellow (Karaoke)"))
|
||||
current = {"title": "t", "categoryId": "10", "channelId": "UC...", "publishedAt": "2020"}
|
||||
body = bf.build_update_snippet(current, entry, enrich_tags=False)
|
||||
assert "channelId" not in body and "publishedAt" not in body
|
||||
|
||||
|
||||
class TestListLoaders:
|
||||
def test_skip_ids_parses_comments_and_pipe(self, tmp_path, monkeypatch):
|
||||
f = tmp_path / "skip_ids.txt"
|
||||
f.write_text("# c\nabc123 # note\nDEF456 | Artist | Title\n\n", encoding="utf-8")
|
||||
monkeypatch.setattr(bf, "SKIP_IDS_PATH", f)
|
||||
assert bf.load_skip_ids() == {"abc123", "DEF456"}
|
||||
|
||||
def test_include_overrides_bare_and_override(self, tmp_path, monkeypatch):
|
||||
f = tmp_path / "include_ids.txt"
|
||||
f.write_text("bare1 # x\nov1 | The Band | The Song\n", encoding="utf-8")
|
||||
monkeypatch.setattr(bf, "INCLUDE_IDS_PATH", f)
|
||||
out = bf.load_include_overrides()
|
||||
assert out["bare1"] is None
|
||||
assert out["ov1"] == {"artist": "The Band", "song_title": "The Song"}
|
||||
|
||||
def test_real_data_files_load(self):
|
||||
# The committed lists should parse and contain the curated decisions.
|
||||
skip = bf.load_skip_ids()
|
||||
inc = bf.load_include_overrides()
|
||||
assert "jAAhbfmh8Bc" in skip # a lyrics-with-vocals video
|
||||
assert "5zSFKuCEIhs" in inc # Los Campesinos! force-include
|
||||
assert inc["5zSFKuCEIhs"]["artist"] == "Los Campesinos!"
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Tests for the shared YouTube description/tags renderer."""
|
||||
import pytest
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.youtube_description import (
|
||||
build_youtube_tags,
|
||||
hashtagify,
|
||||
render_youtube_description,
|
||||
)
|
||||
|
||||
|
||||
class TestHashtagify:
|
||||
def test_strips_punctuation_and_spaces(self):
|
||||
assert hashtagify("Twenty One Pilots") == "TwentyOnePilots"
|
||||
assert hashtagify("P!nk") == "Pnk"
|
||||
assert hashtagify("AC/DC") == "ACDC"
|
||||
|
||||
def test_empty_or_symbol_only_returns_empty(self):
|
||||
assert hashtagify("") == ""
|
||||
assert hashtagify(None) == ""
|
||||
assert hashtagify("!!!") == ""
|
||||
|
||||
def test_keeps_unicode_letters(self):
|
||||
assert hashtagify("Beyoncé") == "Beyoncé"
|
||||
|
||||
|
||||
class TestRenderDefaultTemplate:
|
||||
"""Renders against the real canonical template from config."""
|
||||
|
||||
def _render(self, **kwargs):
|
||||
return render_youtube_description(**kwargs)
|
||||
|
||||
def test_fills_all_placeholders(self):
|
||||
out = self._render(artist="Coldplay", title="Yellow", brand_code="NOMAD-1603")
|
||||
assert "Yellow" in out
|
||||
assert "Coldplay" in out
|
||||
assert "#Coldplay" in out
|
||||
assert "Brand Code: NOMAD-1603" in out
|
||||
assert "https://nomadkaraoke.com/r/youtube" in out
|
||||
|
||||
def test_no_leftover_placeholders(self):
|
||||
out = self._render(artist="Coldplay", title="Yellow", brand_code="NOMAD-1603")
|
||||
for token in ("{artist}", "{title}", "{artist_hashtag}", "{brand_code}"):
|
||||
assert token not in out
|
||||
|
||||
def test_removes_ai_framing(self):
|
||||
out = self._render(artist="Coldplay", title="Yellow", brand_code="NOMAD-1")
|
||||
assert "AI" not in out
|
||||
assert "AI-powered" not in out
|
||||
|
||||
def test_omits_brand_code_line_when_absent(self):
|
||||
out = self._render(artist="Coldplay", title="Yellow", brand_code=None)
|
||||
assert "Brand Code" not in out
|
||||
assert "{brand_code}" not in out
|
||||
# No dangling blank block at the end.
|
||||
assert not out.endswith("\n")
|
||||
|
||||
def test_drops_artist_hashtag_when_unrenderable(self):
|
||||
out = self._render(artist="!!!", title="Song", brand_code="NOMAD-2")
|
||||
# No stray empty hashtag left behind.
|
||||
assert "# " not in out
|
||||
assert "#{artist_hashtag}" not in out
|
||||
assert "#karaoke #instrumental" in out
|
||||
|
||||
def test_config_default_is_the_canonical_template(self):
|
||||
# Guard: the config default must carry the placeholders the renderer expects.
|
||||
tpl = get_settings().default_youtube_description
|
||||
assert "{title}" in tpl and "{artist}" in tpl
|
||||
assert "{brand_code}" in tpl
|
||||
assert "nomadkaraoke.com/r/youtube" in tpl
|
||||
|
||||
|
||||
class TestRenderLegacyTemplate:
|
||||
def test_template_without_placeholders_appends_brand_code(self):
|
||||
legacy = "Karaoke video created with Nomad Karaoke.\n\n#karaoke"
|
||||
out = render_youtube_description(
|
||||
artist="Coldplay", title="Yellow", brand_code="NOMAD-1603", template=legacy
|
||||
)
|
||||
assert out.endswith("Brand Code: NOMAD-1603")
|
||||
assert out.startswith("Karaoke video created with Nomad Karaoke.")
|
||||
|
||||
def test_template_without_placeholders_no_brand_code(self):
|
||||
legacy = "Karaoke video created with Nomad Karaoke.\n\n#karaoke"
|
||||
out = render_youtube_description(
|
||||
artist="Coldplay", title="Yellow", brand_code=None, template=legacy
|
||||
)
|
||||
assert "Brand Code" not in out
|
||||
|
||||
|
||||
class TestBuildTags:
|
||||
def test_includes_core_and_song_specific_tags(self):
|
||||
tags = build_youtube_tags("Coldplay", "Yellow")
|
||||
assert "karaoke" in tags
|
||||
assert "Coldplay" in tags
|
||||
assert "Yellow" in tags
|
||||
assert "Coldplay karaoke" in tags
|
||||
|
||||
def test_deduplicates_case_insensitively(self):
|
||||
# An artist literally named "Karaoke" must not duplicate the core tag.
|
||||
tags = build_youtube_tags("karaoke", "Test")
|
||||
assert sum(1 for t in tags if t.lower() == "karaoke") == 1
|
||||
|
||||
def test_skips_empty_artist_title(self):
|
||||
tags = build_youtube_tags("", "")
|
||||
assert "" not in tags
|
||||
assert "karaoke" in tags
|
||||
|
||||
def test_respects_total_length_budget(self):
|
||||
tags = build_youtube_tags("A" * 300, "B" * 300)
|
||||
total = sum(len(t) + 1 for t in tags)
|
||||
assert total <= 460
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Tests for the scheduled YouTube description backfill worker."""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.youtube_description import render_youtube_description
|
||||
from backend.workers import youtube_description_backfill_worker as worker
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Fakes
|
||||
# ----------------------------------------------------------------------------
|
||||
class FakeDocRef:
|
||||
def __init__(self, data=None):
|
||||
self.data = data
|
||||
self.set_calls = []
|
||||
|
||||
def get(self):
|
||||
m = MagicMock()
|
||||
m.exists = self.data is not None
|
||||
m.to_dict.return_value = dict(self.data) if self.data else {}
|
||||
return m
|
||||
|
||||
def set(self, d):
|
||||
self.data = dict(d)
|
||||
self.set_calls.append(dict(d))
|
||||
|
||||
|
||||
def _fake_db(ref):
|
||||
db = MagicMock()
|
||||
db.collection.return_value.document.return_value = ref
|
||||
return db
|
||||
|
||||
|
||||
def _fake_settings(**overrides):
|
||||
base = dict(
|
||||
youtube_backfill_enabled=True,
|
||||
default_youtube_description="TEMPLATE-V1 {title} {artist} {brand_code}",
|
||||
youtube_backfill_quota_reserve=3000,
|
||||
youtube_backfill_daily_max_updates=150,
|
||||
youtube_backfill_enrich_tags=True,
|
||||
youtube_backfill_report_email="andrew@nomadkaraoke.com",
|
||||
)
|
||||
base.update(overrides)
|
||||
return SimpleNamespace(**base)
|
||||
|
||||
|
||||
def _entry(vid, will_change=True, target=True):
|
||||
return {
|
||||
"video_id": vid,
|
||||
"yt_title": f"Artist - {vid} (Karaoke)",
|
||||
"artist": "Artist",
|
||||
"song_title": vid,
|
||||
"brand_code": "NOMAD-1603",
|
||||
"parse_confidence": "high",
|
||||
"kind": "terse_new",
|
||||
"is_karaoke": True,
|
||||
"eligible": True,
|
||||
"category_id": "10",
|
||||
"current_description": "old description",
|
||||
"target": target,
|
||||
"will_change": will_change,
|
||||
"in_skip_list": False,
|
||||
"forced_include": False,
|
||||
}
|
||||
|
||||
|
||||
def _videos(vids):
|
||||
return {v: {"id": v, "snippet": {"title": f"Artist - {v} (Karaoke)", "categoryId": "10",
|
||||
"description": "old description", "tags": ["old"]}} for v in vids}
|
||||
|
||||
|
||||
class _Ctx:
|
||||
"""Bundle of patches; returns handles for assertions."""
|
||||
|
||||
def __init__(self, entries, videos, settings=None, quota_remaining=100000):
|
||||
self.entries = entries
|
||||
self.videos = videos
|
||||
self.settings = settings or _fake_settings()
|
||||
self.ref = FakeDocRef()
|
||||
self.youtube = MagicMock()
|
||||
self.youtube.videos.return_value.update.return_value.execute.return_value = {}
|
||||
self.quota = MagicMock()
|
||||
self.quota.get_quota_stats.return_value = {"units_remaining": quota_remaining}
|
||||
self.email = MagicMock()
|
||||
|
||||
def __enter__(self):
|
||||
self._patches = [
|
||||
patch.object(worker, "get_settings", return_value=self.settings),
|
||||
patch.object(worker.bf, "load_credentials_from_secret", return_value={"refresh_token": "x"}),
|
||||
patch.object(worker.bf, "build_youtube", return_value=self.youtube),
|
||||
patch.object(worker.bf, "fetch_all_channel_entries", return_value=(self.entries, self.videos)),
|
||||
patch.object(worker, "get_firestore_client", return_value=_fake_db(self.ref)),
|
||||
patch.object(worker, "get_youtube_quota_service", return_value=self.quota),
|
||||
patch.object(worker, "_email_service", return_value=self.email),
|
||||
]
|
||||
for p in self._patches:
|
||||
p.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
for p in self._patches:
|
||||
p.stop()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ----------------------------------------------------------------------------
|
||||
def test_disabled_short_circuits():
|
||||
with _Ctx([], {}, settings=_fake_settings(youtube_backfill_enabled=False)) as ctx:
|
||||
result = worker.run_backfill_sync()
|
||||
assert result["status"] == "disabled"
|
||||
ctx.youtube.videos.assert_not_called()
|
||||
|
||||
|
||||
def test_full_drain_updates_all_and_sends_completion():
|
||||
vids = ["a", "b", "c"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
with _Ctx(entries, _videos(vids)) as ctx:
|
||||
result = worker.run_backfill_sync()
|
||||
assert result["updated"] == 3
|
||||
assert result["pending_after"] == 0
|
||||
assert result["completed"] is True
|
||||
# 3 videos.update calls
|
||||
assert ctx.youtube.videos.return_value.update.call_count == 3
|
||||
# completion email sent, subject mentions complete
|
||||
subj = ctx.email.send_email.call_args.kwargs["subject"]
|
||||
assert "complete" in subj.lower()
|
||||
# state persisted with completed_notified
|
||||
assert ctx.ref.data["completed_notified"] is True
|
||||
assert ctx.ref.data["completed"] is True
|
||||
|
||||
|
||||
def test_budget_cap_partial_and_progress_email():
|
||||
vids = ["a", "b", "c"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
with _Ctx(entries, _videos(vids)) as ctx:
|
||||
result = worker.run_backfill_sync(max_updates=2)
|
||||
assert result["updated"] == 2
|
||||
assert result["pending_after"] == 1
|
||||
assert result["completed"] is False
|
||||
subj = ctx.email.send_email.call_args.kwargs["subject"]
|
||||
assert "remaining" in subj.lower()
|
||||
assert ctx.ref.data.get("completed_notified") in (None, False)
|
||||
|
||||
|
||||
def test_quota_reserve_blocks_updates():
|
||||
vids = ["a", "b"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
# remaining barely above reserve -> budget 0
|
||||
with _Ctx(entries, _videos(vids), quota_remaining=3010) as ctx:
|
||||
result = worker.run_backfill_sync()
|
||||
assert result["budget"] == 0
|
||||
assert result["updated"] == 0
|
||||
ctx.youtube.videos.return_value.update.assert_not_called()
|
||||
|
||||
|
||||
def test_dry_run_makes_no_changes():
|
||||
vids = ["a", "b"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
with _Ctx(entries, _videos(vids)) as ctx:
|
||||
result = worker.run_backfill_sync(dry_run=True)
|
||||
assert result["dry_run"] is True
|
||||
ctx.youtube.videos.return_value.update.assert_not_called()
|
||||
ctx.email.send_email.assert_not_called()
|
||||
assert ctx.ref.set_calls == [] # no state persisted on dry run
|
||||
|
||||
|
||||
def test_nothing_pending_already_notified_no_email():
|
||||
# Channel already fully drained and previously notified.
|
||||
entries = [_entry("a", will_change=False)]
|
||||
ctx = _Ctx(entries, _videos(["a"]))
|
||||
ctx.ref = FakeDocRef({
|
||||
"template_fingerprint": worker._template_fingerprint(ctx.settings),
|
||||
"completed": True,
|
||||
"completed_notified": True,
|
||||
"cycle_index": 1,
|
||||
})
|
||||
with ctx:
|
||||
result = worker.run_backfill_sync()
|
||||
assert result["updated"] == 0
|
||||
assert result["completed"] is True
|
||||
ctx.email.send_email.assert_not_called()
|
||||
|
||||
|
||||
def test_template_change_starts_new_cycle():
|
||||
entries = [_entry("a", will_change=False)]
|
||||
ctx = _Ctx(entries, _videos(["a"]))
|
||||
# Prior state has a DIFFERENT fingerprint -> new cycle should bump cycle_index.
|
||||
ctx.ref = FakeDocRef({
|
||||
"template_fingerprint": "STALEFINGERPRINT",
|
||||
"completed": True,
|
||||
"completed_notified": True,
|
||||
"cycle_index": 2,
|
||||
})
|
||||
with ctx:
|
||||
worker.run_backfill_sync()
|
||||
assert ctx.ref.data["cycle_index"] == 3
|
||||
assert ctx.ref.data["template_fingerprint"] == worker._template_fingerprint(ctx.settings)
|
||||
|
||||
|
||||
def test_quota_exceeded_stops_run():
|
||||
vids = ["a", "b", "c"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
ctx = _Ctx(entries, _videos(vids))
|
||||
# First update ok, second raises quotaExceeded.
|
||||
calls = {"n": 0}
|
||||
|
||||
def _exec():
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 2:
|
||||
raise RuntimeError("quotaExceeded: The request cannot be completed")
|
||||
return {}
|
||||
|
||||
with ctx:
|
||||
ctx.youtube.videos.return_value.update.return_value.execute.side_effect = _exec
|
||||
result = worker.run_backfill_sync()
|
||||
# 1 success, stopped on the 2nd (quota) before doing the 3rd
|
||||
assert result["updated"] == 1
|
||||
assert result["completed"] is False
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Great news! Your karaoke video for \"{artist} - {title}\" has been uploaded to YouTube:",
|
||||
"delayNote": "This upload was briefly delayed while our systems processed other uploads, but everything is all set now.",
|
||||
"signOff": "Thanks!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"greeting": "Hi {name},",
|
||||
"body": "Great news — \"{artist} - {title}\", a karaoke track you voted for on the Nomad Karaoke requests board, is now live on YouTube:",
|
||||
"callToAction": "Want to pick the next free track? Vote at https://requests.nomadkaraoke.com",
|
||||
"signOff": "Thanks for voting!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"greeting": "Hi {name},",
|
||||
"body": "Good news — a karaoke version of \"{artist} - {title}\" (which you voted for on the Nomad Karaoke requests board) already exists online, so we won't be re-making it. Here's a version you can use right now:",
|
||||
"callToAction": "Want to help pick the next FREE track we make? Vote at https://requests.nomadkaraoke.com",
|
||||
"signOff": "Happy singing!\n-Andrew"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} is live on YouTube! 🎉",
|
||||
"subjectFallback": "A track you voted for is now live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "A karaoke version of {artist} - {title} already exists",
|
||||
"subjectFallback": "A karaoke version of the song you requested already exists"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "أخبار رائعة! تم رفع فيديو الكاريوكي الخاص بك لأغنية \"{artist} - {title}\" على YouTube:",
|
||||
"delayNote": "تأخر هذا الرفع لفترة وجيزة بينما قامت أنظمتنا بمعالجة عمليات الرفع الأخرى، ولكن كل شيء جاهز الآن.",
|
||||
"signOff": "شكراً!\n- أندرو"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "أخبار رائعة — \"{artist} - {title}\"، مقطع الكاريوكي الذي صوّت له في لوحة طلبات Nomad Karaoke، متاح الآن على YouTube:",
|
||||
"callToAction": "هل ترغب في اختيار المقطع المجاني التالي؟ صوّت عبر https://requests.nomadkaraoke.com",
|
||||
"greeting": "مرحباً {name}،",
|
||||
"signOff": "شكراً لتصويتك!\n- أندرو"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "أخبار سارة — توجد بالفعل نسخة كاريوكي لأغنية \"{artist} - {title}\" (التي قمت بالتصويت لها في لوحة طلبات Nomad Karaoke) متاحة على الإنترنت، لذا لن نقوم بإعادة إنتاجها. إليك نسخة يمكنك استخدامها الآن:",
|
||||
"callToAction": "هل ترغب في المساعدة في اختيار الأغنية المجانية التالية التي سنقوم بإنتاجها؟ صوّت عبر https://requests.nomadkaraoke.com",
|
||||
"signOff": "غناء ممتع!\n-أندرو",
|
||||
"greeting": "مرحباً {name}،"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} متاح الآن على YouTube! 🎉",
|
||||
"subjectFallback": "المقطع الذي صوّت له متاح الآن!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "توجد بالفعل نسخة كاريوكي لأغنية {artist} - {title}",
|
||||
"subjectFallback": "توجد بالفعل نسخة كاريوكي للأغنية التي طلبتها"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Bones notícies! El teu vídeo de karaoke per a \"{artist} - {title}\" s'ha pujat a YouTube:",
|
||||
"delayNote": "Aquesta pujada s'ha endarrerit breument mentre els nostres sistemes processaven altres pujades, però ara ja està tot llest.",
|
||||
"signOff": "Gràcies!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Bones notícies — \"{artist} - {title}\", una pista de karaoke que vas votar al tauler de peticions de Nomad Karaoke, ja està disponible a YouTube:",
|
||||
"callToAction": "Vols triar la propera pista gratuïta? Vota a https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hola {name},",
|
||||
"signOff": "Gràcies per votar!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Bones notícies — ja existeix a internet una versió de karaoke de \"{artist} - {title}\" (que vas votar al tauler de peticions de Nomad Karaoke), així que no la tornarem a fer. Aquí tens una versió que pots utilitzar ara mateix:",
|
||||
"callToAction": "Vols ajudar a triar la següent pista GRATUÏTA que farem? Vota a https://requests.nomadkaraoke.com",
|
||||
"signOff": "Que gaudeixis cantant!\n-Andrew",
|
||||
"greeting": "Hola {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} ja està disponible a YouTube! 🎉",
|
||||
"subjectFallback": "Una pista que vas votar ja està disponible!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Ja existeix una versió de karaoke de {artist} - {title}",
|
||||
"subjectFallback": "Ja existeix una versió de karaoke de la cançó que has demanat"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Skvělé zprávy! Tvoje karaoke video pro \"{artist} - {title}\" bylo nahráno na YouTube:",
|
||||
"delayNote": "Toto nahrání bylo krátce zpožděno, zatímco naše systémy zpracovávaly jiná nahrání, ale teď už je vše připraveno.",
|
||||
"signOff": "Díky!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Skvělá zpráva — karaoke skladba „{artist} - {title}“, pro kterou jsi hlasoval/a na nástěnce přání Nomad Karaoke, je nyní na YouTube:",
|
||||
"callToAction": "Chceš vybrat další skladbu zdarma? Hlasuj na https://requests.nomadkaraoke.com",
|
||||
"greeting": "Ahoj {name},",
|
||||
"signOff": "Díky za hlasování!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Máme dobrou zprávu — karaoke verze \"{artist} - {title}\" (která dostala tvůj hlas na nástěnce přání Nomad Karaoke) už na internetu existuje, takže ji nebudeme vytvářet znovu. Tady je verze, kterou můžeš rovnou použít:",
|
||||
"callToAction": "Chceš pomoct vybrat další písničku, kterou vytvoříme ZDARMA? Hlasuj na https://requests.nomadkaraoke.com",
|
||||
"signOff": "Příjemné zpívání!\n-Andrew",
|
||||
"greeting": "Ahoj {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} je nyní na YouTube! 🎉",
|
||||
"subjectFallback": "Skladba, pro kterou jsi hlasoval/a, je nyní online!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Karaoke verze {artist} - {title} už existuje",
|
||||
"subjectFallback": "Karaoke verze požadované písničky už existuje"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Gode nyheder! Din karaokevideo til \"{artist} - {title}\" er blevet uploadet til YouTube:",
|
||||
"delayNote": "Denne upload blev kortvarigt forsinket, mens vores systemer behandlede andre uploads, men alt er klar nu.",
|
||||
"signOff": "Tak!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Gode nyheder — \"{artist} - {title}\", et karaoke-nummer, du stemte på via Nomad Karaokes ønskeside, er nu live på YouTube:",
|
||||
"callToAction": "Vil du være med til at vælge det næste gratis nummer? Stem på https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hej {name},",
|
||||
"signOff": "Tak for din stemme!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Gode nyheder — en karaoke-version af \"{artist} - {title}\" (som du stemte på på Nomad Karaokes ønsketavle) findes allerede online, så vi kommer ikke til at lave en ny version. Her er en version, du kan bruge med det samme:",
|
||||
"callToAction": "Vil du hjælpe med at vælge det næste GRATIS nummer, vi laver? Stem på https://requests.nomadkaraoke.com",
|
||||
"signOff": "God sanglyst!\n-Andrew",
|
||||
"greeting": "Hej {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} er live på YouTube! 🎉",
|
||||
"subjectFallback": "Et nummer, du har stemt på, er nu live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "En karaoke-version af {artist} - {title} findes allerede",
|
||||
"subjectFallback": "En karaoke-version af den sang, du efterspurgte, findes allerede"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Gute Neuigkeiten! Dein Karaoke-Video für \"{artist} - {title}\" wurde auf YouTube hochgeladen:",
|
||||
"delayNote": "Dieser Upload wurde kurzzeitig verzögert, während unsere Systeme andere Uploads verarbeitet haben, aber jetzt ist alles bereit.",
|
||||
"signOff": "Danke!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Gute Neuigkeiten — \"{artist} - {title}\", ein Karaoke-Track, für den du auf dem Nomad Karaoke Wunsch-Board abgestimmt hast, ist jetzt live auf YouTube:",
|
||||
"callToAction": "Möchtest du den nächsten kostenlosen Track auswählen? Stimme ab unter https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hallo {name},",
|
||||
"signOff": "Danke fürs Abstimmen!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Gute Nachrichten — eine Karaoke-Version von \"{artist} - {title}\" (für die du auf dem Nomad Karaoke Wunsch-Board abgestimmt hast) existiert bereits online, daher werden wir sie nicht neu erstellen. Hier ist eine Version, die du sofort nutzen kannst:",
|
||||
"callToAction": "Möchtest du mitentscheiden, welchen KOSTENLOSEN Track wir als Nächstes erstellen? Stimme ab unter https://requests.nomadkaraoke.com",
|
||||
"signOff": "Viel Spaß beim Singen!\n-Andrew",
|
||||
"greeting": "Hallo {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} ist live auf YouTube! 🎉",
|
||||
"subjectFallback": "Ein Track, für den du abgestimmt hast, ist jetzt live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Eine Karaoke-Version von {artist} - {title} existiert bereits",
|
||||
"subjectFallback": "Eine Karaoke-Version deines gewünschten Songs existiert bereits"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Υπέροχα νέα! Το καραόκε βίντεό σου για το \"{artist} - {title}\" ανέβηκε στο YouTube:",
|
||||
"delayNote": "Αυτό το ανέβασμα καθυστέρησε για λίγο ενώ τα συστήματά μας επεξεργάζονταν άλλα ανεβάσματα, αλλά τώρα όλα είναι έτοιμα.",
|
||||
"signOff": "Ευχαριστώ!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Υπέροχα νέα — το \"{artist} - {title}\", ένα κομμάτι καραόκε που ψήφισες στον πίνακα αιτημάτων του Nomad Karaoke, είναι πλέον διαθέσιμο στο YouTube:",
|
||||
"callToAction": "Θέλεις να επιλέξεις το επόμενο δωρεάν κομμάτι; Ψήφισε στο https://requests.nomadkaraoke.com",
|
||||
"greeting": "Γεια σου {name},",
|
||||
"signOff": "Ευχαριστώ που ψήφισες!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Καλά νέα — μια έκδοση καραόκε του \"{artist} - {title}\" (για το οποίο ψήφισες στον πίνακα αιτημάτων του Nomad Karaoke) υπάρχει ήδη στο διαδίκτυο, οπότε δεν θα τη φτιάξουμε από την αρχή. Ορίστε μια έκδοση που μπορείς να χρησιμοποιήσεις αμέσως:",
|
||||
"callToAction": "Θέλεις να βοηθήσεις στην επιλογή του επόμενου ΔΩΡΕΑΝ κομματιού που θα φτιάξουμε; Ψήφισε στο https://requests.nomadkaraoke.com",
|
||||
"signOff": "Καλό τραγούδι!\n-Andrew",
|
||||
"greeting": "Γεια σου {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} είναι διαθέσιμο στο YouTube! 🎉",
|
||||
"subjectFallback": "Ένα κομμάτι που ψήφισες είναι πλέον διαθέσιμο!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Μια έκδοση καραόκε του {artist} - {title} υπάρχει ήδη",
|
||||
"subjectFallback": "Μια έκδοση καραόκε του τραγουδιού που ζήτησες υπάρχει ήδη"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Great news! Your karaoke video for \"{artist} - {title}\" has been uploaded to YouTube:",
|
||||
"delayNote": "This upload was briefly delayed while our systems processed other uploads, but everything is all set now.",
|
||||
"signOff": "Thanks!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"greeting": "Hi {name},",
|
||||
"body": "Great news — \"{artist} - {title}\", a karaoke track you voted for on the Nomad Karaoke requests board, is now live on YouTube:",
|
||||
"callToAction": "Want to pick the next free track? Vote at https://requests.nomadkaraoke.com",
|
||||
"signOff": "Thanks for voting!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"greeting": "Hi {name},",
|
||||
"body": "Good news — a karaoke version of \"{artist} - {title}\" (which you voted for on the Nomad Karaoke requests board) already exists online, so we won't be re-making it. Here's a version you can use right now:",
|
||||
"callToAction": "Want to help pick the next FREE track we make? Vote at https://requests.nomadkaraoke.com",
|
||||
"signOff": "Happy singing!\n-Andrew"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} is live on YouTube! 🎉",
|
||||
"subjectFallback": "A track you voted for is now live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "A karaoke version of {artist} - {title} already exists",
|
||||
"subjectFallback": "A karaoke version of the song you requested already exists"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "¡Excelentes noticias! Tu video de karaoke para \"{artist} - {title}\" ha sido subido a YouTube:",
|
||||
"delayNote": "Esta subida se retrasó brevemente mientras nuestros sistemas procesaban otras subidas, pero ya está todo listo.",
|
||||
"signOff": "¡Gracias!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Excelentes noticias: \"{artist} - {title}\", una pista de karaoke por la que votaste en el tablero de solicitudes de Nomad Karaoke, ya está disponible en YouTube:",
|
||||
"callToAction": "¿Quieres elegir la próxima pista gratuita? Vota en https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hola {name},",
|
||||
"signOff": "¡Gracias por votar!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Buenas noticias: ya existe en línea una versión de karaoke de \"{artist} - {title}\" (por la que votaste en el tablero de solicitudes de Nomad Karaoke), así que no haremos una nueva versión. Aquí tienes una versión que puedes usar ahora mismo:",
|
||||
"callToAction": "¿Quieres ayudar a elegir la próxima pista GRATUITA que hagamos? Vota en https://requests.nomadkaraoke.com",
|
||||
"signOff": "¡Que disfrutes cantando!\n-Andrew",
|
||||
"greeting": "Hola {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "¡{artist} - {title} ya está disponible en YouTube! 🎉",
|
||||
"subjectFallback": "¡Una pista por la que votaste ya está disponible!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Ya existe una versión de karaoke de {artist} - {title}",
|
||||
"subjectFallback": "Ya existe una versión de karaoke de la canción que solicitaste"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Loistavia uutisia! Karaokevideosi kappaleelle \"{artist} - {title}\" on ladattu YouTube-palveluun:",
|
||||
"delayNote": "Tämä lataus viivästyi hetkellisesti, kun järjestelmämme käsittelivät muita latauksia, mutta nyt kaikki on valmista.",
|
||||
"signOff": "Kiitos!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Mahtavia uutisia — karaokekappale \"{artist} - {title}\", jota äänestit Nomad Karaoke -toivelistalla, on nyt YouTubessa:",
|
||||
"callToAction": "Haluatko valita seuraavan ilmaisen kappaleen? Äänestä osoitteessa https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hei {name},",
|
||||
"signOff": "Kiitos äänestämisestä!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Hyviä uutisia — karaokeversio kappaleesta \"{artist} - {title}\" (jota äänestit Nomad Karaoke -toivetaululla) löytyy jo verkosta, joten emme tee siitä uutta versiota. Tässä on versio, jota voit käyttää heti:",
|
||||
"callToAction": "Haluatko auttaa valitsemaan seuraavan ILMAISEN kappaleen, jonka teemme? Äänestä osoitteessa https://requests.nomadkaraoke.com",
|
||||
"signOff": "Mukavia lauluhetkiä!\n-Andrew",
|
||||
"greeting": "Hei {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} on nyt YouTubessa! 🎉",
|
||||
"subjectFallback": "Äänestämäsi kappale on nyt julkaistu!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Karaokeversio kappaleesta {artist} - {title} on jo olemassa",
|
||||
"subjectFallback": "Karaokeversio pyytämästäsi kappaleesta on jo olemassa"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Bonne nouvelle ! Ta vidéo karaoké pour \"{artist} - {title}\" a été mise en ligne sur YouTube :",
|
||||
"delayNote": "Cette mise en ligne a été brièvement retardée pendant que nos systèmes traitaient d'autres mises en ligne, mais tout est prêt maintenant.",
|
||||
"signOff": "Merci !\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Excellente nouvelle — \"{artist} - {title}\", un titre de karaoké pour lequel tu as voté sur le tableau des requêtes de Nomad Karaoke, est maintenant en ligne sur YouTube :",
|
||||
"callToAction": "Tu veux choisir le prochain titre gratuit ? Vote sur https://requests.nomadkaraoke.com",
|
||||
"greeting": "Salut {name},",
|
||||
"signOff": "Merci d'avoir voté !\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Bonne nouvelle ! Une version karaoké de \"{artist} - {title}\" (pour laquelle tu as voté sur la liste des demandes de Nomad Karaoke) existe déjà en ligne, nous n'allons donc pas la recréer. Voici une version que tu peux utiliser dès maintenant :",
|
||||
"callToAction": "Tu veux aider à choisir le prochain titre GRATUIT que nous créerons ? Vote sur https://requests.nomadkaraoke.com",
|
||||
"signOff": "Bon karaoké !\n-Andrew",
|
||||
"greeting": "Salut {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} est en ligne sur YouTube ! 🎉",
|
||||
"subjectFallback": "Un titre pour lequel tu as voté est maintenant en ligne !"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Une version karaoké de {artist} - {title} existe déjà",
|
||||
"subjectFallback": "Une version karaoké de la chanson que tu as demandée existe déjà"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "חדשות מעולות! סרטון הקריוקי שלכם עבור \"{artist} - {title}\" הועלה ל-YouTube:",
|
||||
"delayNote": "העלאה זו עוכבה לזמן קצר בזמן שהמערכות שלנו עיבדו העלאות אחרות, אבל עכשיו הכל מוכן.",
|
||||
"signOff": "תודה!\n-אנדרו"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "חדשות מעולות — \"{artist} - {title}\", שיר קריוקי שהצבעת עבורו בלוח הבקשות של Nomad Karaoke, עלה עכשיו ל-YouTube:",
|
||||
"callToAction": "רוצה לבחור את השיר החינמי הבא? אפשר להצביע בכתובת https://requests.nomadkaraoke.com",
|
||||
"greeting": "היי {name},",
|
||||
"signOff": "תודה על ההצבעה!\n- אנדרו"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "חדשות טובות — גרסת קריוקי של \"{artist} - {title}\" (שהצבעתם עבורה בלוח הבקשות של Nomad Karaoke) כבר קיימת ברשת, אז לא ניצור אותה מחדש. הנה גרסה שתוכלו להשתמש בה כבר עכשיו:",
|
||||
"callToAction": "רוצים לעזור לבחור את הרצועה החינמית הבאה שניצור? הצביעו ב-https://requests.nomadkaraoke.com",
|
||||
"signOff": "שירה מהנה!\n-Andrew",
|
||||
"greeting": "היי {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} עלה ל-YouTube! 🎉",
|
||||
"subjectFallback": "שיר שהצבעת עבורו עלה לאוויר!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "גרסת קריוקי של {artist} - {title} כבר קיימת",
|
||||
"subjectFallback": "גרסת קריוקי של השיר שביקשתם כבר קיימת"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "बढ़िया खबर! \"{artist} - {title}\" के लिए तुम्हारा कराओके वीडियो YouTube पर अपलोड कर दिया गया है:",
|
||||
"delayNote": "इस अपलोड में थोड़ी देरी हुई क्योंकि हमारे सिस्टम अन्य अपलोड प्रोसेस कर रहे थे, लेकिन अब सब कुछ सेट है।",
|
||||
"signOff": "धन्यवाद!\n-एंड्रयू"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "खुशखबरी — \"{artist} - {title}\", वह कराओके ट्रैक जिसके लिए तुमने Nomad Karaoke रिक्वेस्ट बोर्ड पर वोट किया था, अब YouTube पर लाइव है:",
|
||||
"callToAction": "क्या तुम अगला फ्री ट्रैक चुनना चाहते हो? https://requests.nomadkaraoke.com पर वोट करो",
|
||||
"greeting": "हाय {name},",
|
||||
"signOff": "वोट करने के लिए धन्यवाद!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "अच्छी ख़बर — \"{artist} - {title}\" का कराओके वर्ज़न (जिसके लिए तुमने Nomad Karaoke रिक्वेस्ट बोर्ड पर वोट किया था) ऑनलाइन पहले से ही मौजूद है, इसलिए हम इसे दोबारा नहीं बनाएंगे। यहाँ एक वर्ज़न है जिसका तुम अभी इस्तेमाल कर सकते हो:",
|
||||
"callToAction": "क्या तुम हमारा अगला मुफ़्त (FREE) ट्रैक चुनने में मदद करना चाहते हो? https://requests.nomadkaraoke.com पर वोट करो",
|
||||
"signOff": "गाने का आनंद लो!\n-Andrew",
|
||||
"greeting": "हाय {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} YouTube पर लाइव है! 🎉",
|
||||
"subjectFallback": "जिस ट्रैक के लिए तुमने वोट किया था, वह अब लाइव है!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "{artist} - {title} का कराओके वर्ज़न पहले से मौजूद है",
|
||||
"subjectFallback": "तुमने जिस गाने की रिक्वेस्ट की थी, उसका कराओके वर्ज़न पहले से मौजूद है"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Sjajne vijesti! Tvoj karaoke video za \"{artist} - {title}\" je prenesen na YouTube:",
|
||||
"delayNote": "Ovaj prijenos je bio nakratko odgođen dok su naši sustavi obrađivali druge prijenose, ali sada je sve spremno.",
|
||||
"signOff": "Hvala!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Odlične vijesti — \"{artist} - {title}\", karaoke pjesma za koju si glasao/la na Nomad Karaoke stranici za prijedloge, sada je objavljena na YouTubeu:",
|
||||
"callToAction": "Želiš li odabrati sljedeću besplatnu pjesmu? Glasaj na https://requests.nomadkaraoke.com",
|
||||
"greeting": "Bok, {name},",
|
||||
"signOff": "Hvala na glasanju!\n- Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Dobre vijesti — karaoke verzija pjesme \"{artist} - {title}\" (za koju si glasao na Nomad Karaoke listi zahtjeva) već postoji na internetu, pa je nećemo ponovno raditi. Evo verzije koju možeš odmah koristiti:",
|
||||
"callToAction": "Želiš li pomoći u odabiru sljedeće BESPLATNE pjesme koju ćemo napraviti? Glasaj na https://requests.nomadkaraoke.com",
|
||||
"signOff": "Uživaj u pjevanju!\n-Andrew",
|
||||
"greeting": "Bok, {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} je objavljena na YouTubeu! 🎉",
|
||||
"subjectFallback": "Pjesma za koju si glasao/la sada je objavljena!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Karaoke verzija pjesme {artist} - {title} već postoji",
|
||||
"subjectFallback": "Karaoke verzija pjesme koju si zatražio već postoji"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Nagyszerű hír! A karaoke videód a(z) \"{artist} - {title}\" dalhoz fel lett töltve a YouTube-ra:",
|
||||
"delayNote": "Ez a feltöltés rövid ideig késett, amíg a rendszereink más feltöltéseket dolgoztak fel, de most már minden rendben van.",
|
||||
"signOff": "Köszönöm!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Nagyszerű hír — a(z) \"{artist} - {title}\", egy karaoke dal, amire a Nomad Karaoke kérések oldalán szavaztál, már elérhető a YouTube-on:",
|
||||
"callToAction": "Szeretnéd te kiválasztani a következő ingyenes dalt? Szavazz itt: https://requests.nomadkaraoke.com",
|
||||
"greeting": "Szia {name},",
|
||||
"signOff": "Köszönöm, hogy szavaztál!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Jó hír — a(z) \"{artist} - {title}\" (amelyre a Nomad Karaoke kérésfalán szavaztál) karaoke verziója már elérhető az interneten, így mi nem készítjük el újra. Íme egy verzió, amit azonnal használhatsz:",
|
||||
"callToAction": "Szívesen segítenél kiválasztani a következő INGYENES dalt, amit elkészítünk? Szavazz itt: https://requests.nomadkaraoke.com",
|
||||
"signOff": "Jó éneklést!\n-Andrew",
|
||||
"greeting": "Szia {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} már elérhető a YouTube-on! 🎉",
|
||||
"subjectFallback": "Egy dal, amire szavaztál, már elérhető!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Már létezik a(z) {artist} - {title} karaoke verziója",
|
||||
"subjectFallback": "Az általad kért dalból már létezik karaoke verzió"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Kabar baik! Video karaoke Anda untuk \"{artist} - {title}\" telah diunggah ke YouTube:",
|
||||
"delayNote": "Unggahan ini sempat tertunda sebentar saat sistem kami memproses unggahan lain, tetapi sekarang semuanya sudah siap.",
|
||||
"signOff": "Terima kasih!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Kabar gembira — \"{artist} - {title}\", lagu karaoke yang Anda pilih di halaman request Nomad Karaoke, kini sudah tayang di YouTube:",
|
||||
"callToAction": "Ingin memilih lagu gratis berikutnya? Vote di https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hai {name},",
|
||||
"signOff": "Terima kasih telah memilih!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Kabar baik — versi karaoke dari \"{artist} - {title}\" (yang Anda pilih di papan permintaan Nomad Karaoke) sudah tersedia online, jadi kami tidak akan membuatnya ulang. Berikut versi yang bisa Anda gunakan sekarang juga:",
|
||||
"callToAction": "Ingin membantu memilih lagu GRATIS berikutnya yang akan kami buat? Berikan suara Anda di https://requests.nomadkaraoke.com",
|
||||
"signOff": "Selamat bernyanyi!\n-Andrew",
|
||||
"greeting": "Hai {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} sudah tayang di YouTube! 🎉",
|
||||
"subjectFallback": "Lagu yang Anda pilih kini sudah tayang!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Versi karaoke dari {artist} - {title} sudah ada",
|
||||
"subjectFallback": "Versi karaoke dari lagu yang Anda minta sudah ada"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Ottime notizie! Il tuo video karaoke per \"{artist} - {title}\" è stato caricato su YouTube:",
|
||||
"delayNote": "Questo caricamento è stato brevemente ritardato mentre i nostri sistemi elaboravano altri caricamenti, ma ora è tutto a posto.",
|
||||
"signOff": "Grazie!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Ottime notizie — \"{artist} - {title}\", un brano karaoke che hai votato nella bacheca delle richieste di Nomad Karaoke, è ora online su YouTube:",
|
||||
"callToAction": "Vuoi scegliere il prossimo brano gratuito? Vota su https://requests.nomadkaraoke.com",
|
||||
"greeting": "Ciao {name},",
|
||||
"signOff": "Grazie per aver votato!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Buone notizie — esiste già online una versione karaoke di \"{artist} - {title}\" (per cui hai votato nella bacheca delle richieste di Nomad Karaoke), quindi non la rifaremo. Ecco una versione che puoi usare subito:",
|
||||
"callToAction": "Vuoi aiutarci a scegliere il prossimo brano GRATUITO che realizzeremo? Vota su https://requests.nomadkaraoke.com",
|
||||
"signOff": "Buon divertimento!\n-Andrew",
|
||||
"greeting": "Ciao {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} è online su YouTube! 🎉",
|
||||
"subjectFallback": "Un brano che hai votato è ora online!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Esiste già una versione karaoke di {artist} - {title}",
|
||||
"subjectFallback": "Esiste già una versione karaoke della canzone che hai richiesto"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "お知らせです!「{artist} - {title}」のカラオケ動画がYouTubeにアップロードされました:",
|
||||
"delayNote": "システムが他のアップロードを処理していたため一時的に遅延していましたが、現在はすべて完了しています。",
|
||||
"signOff": "よろしくお願いします!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "嬉しいお知らせです!Nomad Karaokeのリクエストボードで投票していただいたカラオケトラック「{artist} - {title}」が、YouTubeで公開されました:",
|
||||
"callToAction": "次の無料トラックも選んでみませんか?投票はこちらから: https://requests.nomadkaraoke.com",
|
||||
"greeting": "{name}さん、",
|
||||
"signOff": "ご投票ありがとうございました!\n- Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "嬉しいお知らせです!Nomad Karaokeのリクエストボードで投票していただいた「{artist} - {title}」ですが、すでにオンライン上にカラオケバージョンが存在していることがわかりました。そのため、こちらでの新規作成は見送らせていただきます。今すぐご利用いただけるバージョンはこちらです:",
|
||||
"callToAction": "次に無料で作成する曲を一緒に選びませんか?ぜひ https://requests.nomadkaraoke.com から投票してください。",
|
||||
"signOff": "カラオケをお楽しみください!\n-Andrew",
|
||||
"greeting": "{name}さん、"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} がYouTubeで公開されました! 🎉",
|
||||
"subjectFallback": "投票していただいた曲が公開されました!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "{artist} - {title} のカラオケバージョンはすでに存在しています",
|
||||
"subjectFallback": "リクエストいただいた曲のカラオケバージョンはすでに存在しています"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "좋은 소식입니다! \"{artist} - {title}\" 노래방 비디오가 YouTube에 업로드되었습니다:",
|
||||
"delayNote": "시스템에서 다른 업로드를 처리하는 동안 이 업로드가 잠시 지연되었으나, 이제 모두 완료되었습니다.",
|
||||
"signOff": "감사합니다!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "기쁜 소식입니다! Nomad Karaoke 요청 게시판에서 투표하신 노래방 트랙 \"{artist} - {title}\"이(가) YouTube에 공개되었습니다:",
|
||||
"callToAction": "다음 무료 트랙을 직접 선택하고 싶으신가요? https://requests.nomadkaraoke.com 에서 투표해 주세요.",
|
||||
"greeting": "안녕하세요 {name}님,",
|
||||
"signOff": "투표해 주셔서 감사합니다!\n- Andrew 드림"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "기쁜 소식을 전해드립니다! Nomad Karaoke 요청 게시판에서 투표해 주신 \"{artist} - {title}\" 가라오케 버전이 이미 온라인에 있어, 저희가 새로 제작하지 않기로 했습니다. 지금 바로 이용하실 수 있는 버전은 다음과 같습니다:",
|
||||
"callToAction": "저희가 제작할 다음 무료 트랙을 직접 골라보시겠어요? https://requests.nomadkaraoke.com 에서 투표해 주세요.",
|
||||
"signOff": "즐거운 시간 되세요!\n- Andrew 드림",
|
||||
"greeting": "안녕하세요 {name}님,"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} 트랙이 YouTube에 공개되었습니다! 🎉",
|
||||
"subjectFallback": "투표하신 트랙이 공개되었습니다!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "{artist} - {title} 가라오케 버전이 이미 있습니다",
|
||||
"subjectFallback": "요청하신 노래의 가라오케 버전이 이미 있습니다"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Berita baik! Video karaoke anda untuk \"{artist} - {title}\" telah dimuat naik ke YouTube:",
|
||||
"delayNote": "Muat naik ini tertangguh seketika semasa sistem kami memproses muat naik lain, tetapi semuanya sudah sedia sekarang.",
|
||||
"signOff": "Terima kasih!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Berita baik — \"{artist} - {title}\", lagu karaoke yang anda undi di papan permintaan Nomad Karaoke, kini tersedia di YouTube:",
|
||||
"callToAction": "Ingin memilih lagu percuma yang seterusnya? Undi di https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hai {name},",
|
||||
"signOff": "Terima kasih kerana mengundi!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Berita baik — versi karaoke untuk \"{artist} - {title}\" (yang anda undi di papan permintaan Nomad Karaoke) sudah ada dalam talian, jadi kami tidak akan membuatnya semula. Berikut ialah versi yang boleh anda gunakan sekarang:",
|
||||
"callToAction": "Ingin membantu memilih trek PERCUMA seterusnya yang akan kami buat? Undi di https://requests.nomadkaraoke.com",
|
||||
"signOff": "Selamat menyanyi!\n-Andrew",
|
||||
"greeting": "Hai {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} kini tersedia di YouTube! 🎉",
|
||||
"subjectFallback": "Lagu yang anda undi kini tersedia!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Versi karaoke untuk {artist} - {title} sudah ada",
|
||||
"subjectFallback": "Versi karaoke untuk lagu yang anda minta sudah ada"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Gode nyheter! Karaokevideoen din for \"{artist} - {title}\" har blitt lastet opp til YouTube:",
|
||||
"delayNote": "Denne opplastingen ble kort forsinket mens systemene våre behandlet andre opplastinger, men alt er klart nå.",
|
||||
"signOff": "Takk!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Gode nyheter — \"{artist} - {title}\", en karaokesang du stemte på via Nomad Karaokes ønskeside, er nå ute på YouTube:",
|
||||
"callToAction": "Vil du velge neste gratis sang? Stem på https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hei {name},",
|
||||
"signOff": "Takk for at du stemte!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Gode nyheter — en karaokeversjon av \"{artist} - {title}\" (som du stemte på på ønsketavlen til Nomad Karaoke) finnes allerede på nettet, så vi kommer ikke til å lage den på nytt. Her er en versjon du kan bruke med en gang:",
|
||||
"callToAction": "Vil du være med på å velge den neste GRATIS låten vi lager? Stem på https://requests.nomadkaraoke.com",
|
||||
"signOff": "Kos deg med syngingen!\n-Andrew",
|
||||
"greeting": "Hei {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} er ute på YouTube! 🎉",
|
||||
"subjectFallback": "En sang du stemte på er nå ute!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "En karaokeversjon av {artist} - {title} finnes allerede",
|
||||
"subjectFallback": "En karaokeversjon av sangen du etterspurte, finnes allerede"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Goed nieuws! Je karaokevideo voor \"{artist} - {title}\" is geüpload naar YouTube:",
|
||||
"delayNote": "Deze upload was even vertraagd terwijl onze systemen andere uploads verwerkten, maar alles is nu in orde.",
|
||||
"signOff": "Bedankt!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Goed nieuws — \"{artist} - {title}\", een karaokenummer waar je op hebt gestemd op het Nomad Karaoke-verzoekenbord, is nu live op YouTube:",
|
||||
"callToAction": "Wil je het volgende gratis nummer kiezen? Stem op https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hoi {name},",
|
||||
"signOff": "Bedankt voor het stemmen!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Goed nieuws — er bestaat online al een karaokeversie van \"{artist} - {title}\" (waar je op hebt gestemd op het verzoekenbord van Nomad Karaoke), dus we gaan deze niet opnieuw maken. Hier is een versie die je direct kunt gebruiken:",
|
||||
"callToAction": "Wil je helpen het volgende GRATIS nummer te kiezen dat we gaan maken? Stem op https://requests.nomadkaraoke.com",
|
||||
"signOff": "Veel zingplezier!\n-Andrew",
|
||||
"greeting": "Hoi {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} is live op YouTube! 🎉",
|
||||
"subjectFallback": "Een nummer waar je op hebt gestemd is nu live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Er bestaat al een karaokeversie van {artist} - {title}",
|
||||
"subjectFallback": "Er bestaat al een karaokeversie van het nummer dat je hebt aangevraagd"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Świetne wieści! Twoje wideo karaoke dla \"{artist} - {title}\" zostało przesłane na YouTube:",
|
||||
"delayNote": "Przesyłanie było przez chwilę opóźnione, ponieważ nasze systemy przetwarzały inne pliki, ale teraz wszystko jest już gotowe.",
|
||||
"signOff": "Dzięki!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Świetne wieści — \"{artist} - {title}\", utwór karaoke, na który zagłosowałeś/aś na tablicy życzeń Nomad Karaoke, jest już dostępny na YouTube:",
|
||||
"callToAction": "Chcesz wybrać kolejny darmowy utwór? Zagłosuj na https://requests.nomadkaraoke.com",
|
||||
"greeting": "Cześć {name},",
|
||||
"signOff": "Dzięki za głos!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Dobre wieści — wersja karaoke \"{artist} - {title}\" (która otrzymała Twój głos na tablicy życzeń Nomad Karaoke) już istnieje w sieci, więc nie będziemy tworzyć jej od nowa. Oto wersja, z której możesz skorzystać już teraz:",
|
||||
"callToAction": "Chcesz pomóc w wyborze kolejnego DARMOWEGO utworu, który stworzymy? Zagłosuj na https://requests.nomadkaraoke.com",
|
||||
"signOff": "Miłego śpiewania!\n-Andrew",
|
||||
"greeting": "Cześć {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} jest już na YouTube! 🎉",
|
||||
"subjectFallback": "Utwór, na który zagłosowałeś/aś, jest już dostępny!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Wersja karaoke {artist} - {title} już istnieje",
|
||||
"subjectFallback": "Wersja karaoke wybranej przez Ciebie piosenki już istnieje"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Ótimas notícias! Seu vídeo de karaokê para \"{artist} - {title}\" foi enviado para o YouTube:",
|
||||
"delayNote": "Este upload foi brevemente atrasado enquanto nossos sistemas processavam outros uploads, mas está tudo pronto agora.",
|
||||
"signOff": "Obrigado!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Ótimas notícias — \"{artist} - {title}\", uma faixa de karaokê em que você votou no painel de pedidos do Nomad Karaoke, já está disponível no YouTube:",
|
||||
"callToAction": "Quer escolher a próxima faixa gratuita? Vote em https://requests.nomadkaraoke.com",
|
||||
"greeting": "Olá, {name},",
|
||||
"signOff": "Obrigado por votar!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Boas notícias — uma versão de karaokê de \"{artist} - {title}\" (na qual você votou no quadro de pedidos do Nomad Karaoke) já existe online, então não vamos refazê-la. Aqui está uma versão que você pode usar agora mesmo:",
|
||||
"callToAction": "Quer ajudar a escolher a próxima faixa GRATUITA que vamos criar? Vote em https://requests.nomadkaraoke.com",
|
||||
"signOff": "Divirta-se cantando!\n-Andrew",
|
||||
"greeting": "Olá, {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} já está no ar no YouTube! 🎉",
|
||||
"subjectFallback": "Uma faixa em que você votou já está no ar!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Já existe uma versão de karaokê de {artist} - {title}",
|
||||
"subjectFallback": "Já existe uma versão de karaokê da música que você pediu"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Vești bune! Videoclipul tău de karaoke pentru \"{artist} - {title}\" a fost încărcat pe YouTube:",
|
||||
"delayNote": "Această încărcare a fost întârziată scurt timp în timp ce sistemele noastre au procesat alte încărcări, dar acum totul este gata.",
|
||||
"signOff": "Mulțumesc!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Vești bune — \"{artist} - {title}\", o piesă de karaoke pentru care ai votat în lista de cereri Nomad Karaoke, este acum live pe YouTube:",
|
||||
"callToAction": "Vrei să alegi următoarea piesă gratuită? Votează la https://requests.nomadkaraoke.com",
|
||||
"greeting": "Salut, {name},",
|
||||
"signOff": "Îți mulțumesc pentru vot!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Vești bune — o versiune de karaoke pentru \"{artist} - {title}\" (pentru care ai votat pe pagina de cereri Nomad Karaoke) există deja online, așa că nu o vom reface. Iată o versiune pe care o poți folosi chiar acum:",
|
||||
"callToAction": "Vrei să ne ajuți să alegem următoarea piesă GRATUITĂ pe care o vom crea? Votează pe https://requests.nomadkaraoke.com",
|
||||
"signOff": "Spor la cântat!\n-Andrew",
|
||||
"greeting": "Salut, {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} este live pe YouTube! 🎉",
|
||||
"subjectFallback": "O piesă pentru care ai votat este acum live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "O versiune de karaoke pentru {artist} - {title} există deja",
|
||||
"subjectFallback": "O versiune de karaoke a melodiei pe care ai cerut-o există deja"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Отличные новости! Твое караоке-видео для \"{artist} - {title}\" было загружено на YouTube:",
|
||||
"delayNote": "Эта загрузка была ненадолго отложена, пока наши системы обрабатывали другие загрузки, но теперь все готово.",
|
||||
"signOff": "Спасибо!\n-Эндрю"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Отличные новости — караоке-трек \"{artist} - {title}\", получивший твой голос на доске заявок Nomad Karaoke, теперь доступен на YouTube:",
|
||||
"callToAction": "Хочешь выбрать следующий бесплатный трек? Голосуй на https://requests.nomadkaraoke.com",
|
||||
"greeting": "Привет, {name},",
|
||||
"signOff": "Спасибо за твой голос!\n-Эндрю"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Хорошие новости — караоке-версия \"{artist} - {title}\" (за которую ты голосовал(а) на доске заявок Nomad Karaoke) уже есть в сети, поэтому мы не будем делать её заново. Вот версия, которую можно использовать прямо сейчас:",
|
||||
"callToAction": "Хочешь помочь выбрать следующий БЕСПЛАТНЫЙ трек, который мы сделаем? Голосуй на https://requests.nomadkaraoke.com",
|
||||
"signOff": "Приятного пения!\n-Эндрю",
|
||||
"greeting": "Привет, {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} теперь на YouTube! 🎉",
|
||||
"subjectFallback": "Трек, получивший твой голос, теперь доступен!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Караоке-версия {artist} - {title} уже существует",
|
||||
"subjectFallback": "Караоке-версия запрошенной тобой песни уже существует"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Skvelé správy! Tvoje karaoke video pre \"{artist} - {title}\" bolo nahrané na YouTube:",
|
||||
"delayNote": "Toto nahrávanie bolo na chvíľu zdržané, kým naše systémy spracovávali iné nahrávania, ale teraz je už všetko pripravené.",
|
||||
"signOff": "Vďaka!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Skvelá správa — karaoke skladba \"{artist} - {title}\", za ktorú si hlasoval(a) na nástenke žiadostí Nomad Karaoke, je teraz online na YouTube:",
|
||||
"callToAction": "Chceš vybrať ďalšiu bezplatnú skladbu? Hlasuj na https://requests.nomadkaraoke.com",
|
||||
"greeting": "Ahoj {name},",
|
||||
"signOff": "Vďaka za hlasovanie!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Máme dobré správy — karaoke verzia \"{artist} - {title}\" (za ktorú si hlasoval na nástenke žiadostí Nomad Karaoke) už existuje online, takže ju nebudeme robiť nanovo. Tu je verzia, ktorú môžeš hneď použiť:",
|
||||
"callToAction": "Chceš pomôcť vybrať ďalšiu BEZPLATNÚ skladbu, ktorú vytvoríme? Hlasuj na https://requests.nomadkaraoke.com",
|
||||
"signOff": "Príjemné spievanie!\n-Andrew",
|
||||
"greeting": "Ahoj {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} je online na YouTube! 🎉",
|
||||
"subjectFallback": "Skladba, za ktorú si hlasoval(a), je teraz online!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Karaoke verzia {artist} - {title} už existuje",
|
||||
"subjectFallback": "Karaoke verzia piesne, ktorú si si vyžiadal, už existuje"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Goda nyheter! Din karaokevideo för \"{artist} - {title}\" har laddats upp på YouTube:",
|
||||
"delayNote": "Denna uppladdning fördröjdes kort medan våra system bearbetade andra uppladdningar, men allt är klart nu.",
|
||||
"signOff": "Tack!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Goda nyheter — \"{artist} - {title}\", en karaokelåt du röstade på via Nomad Karaokes önskelista, är nu live på YouTube:",
|
||||
"callToAction": "Vill du välja nästa gratislåt? Rösta på https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hej {name},",
|
||||
"signOff": "Tack för att du röstade!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Goda nyheter — en karaokeversion av \"{artist} - {title}\" (som du röstade på i Nomad Karaokes önskelista) finns redan online, så vi kommer inte att skapa den på nytt. Här är en version du kan använda direkt:",
|
||||
"callToAction": "Vill du hjälpa till att välja nästa GRATIS låt vi skapar? Rösta på https://requests.nomadkaraoke.com",
|
||||
"signOff": "Trevlig sångstund!\n-Andrew",
|
||||
"greeting": "Hej {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} är live på YouTube! 🎉",
|
||||
"subjectFallback": "En låt du röstade på är nu live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "En karaokeversion av {artist} - {title} finns redan",
|
||||
"subjectFallback": "En karaokeversion av låten du önskade finns redan"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "ข่าวดี! วิดีโอคาราโอเกะของคุณสำหรับ \"{artist} - {title}\" ถูกอัปโหลดไปยัง YouTube แล้ว:",
|
||||
"delayNote": "การอัปโหลดนี้ล่าช้าไปเล็กน้อยในขณะที่ระบบของเราประมวลผลการอัปโหลดอื่นๆ แต่ตอนนี้ทุกอย่างเรียบร้อยแล้ว",
|
||||
"signOff": "ขอบคุณ!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "ข่าวดี — เพลงคาราโอเกะ \"{artist} - {title}\" ที่คุณโหวตไว้บนบอร์ดขอเพลงของ Nomad Karaoke พร้อมให้ร้องแล้วบน YouTube:",
|
||||
"callToAction": "อยากเป็นคนเลือกเพลงฟรีเพลงต่อไปไหม? ร่วมโหวตได้ที่ https://requests.nomadkaraoke.com",
|
||||
"greeting": "สวัสดี {name},",
|
||||
"signOff": "ขอบคุณที่ร่วมโหวต!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "ข่าวดี — มีเวอร์ชันคาราโอเกะของเพลง \"{artist} - {title}\" (ที่คุณโหวตไว้บนกระดานขอเพลงของ Nomad Karaoke) ออนไลน์อยู่แล้ว เราจึงไม่ได้ทำขึ้นมาใหม่ นี่คือเวอร์ชันที่คุณสามารถนำไปใช้ได้เลย:",
|
||||
"callToAction": "อยากช่วยเราเลือกเพลงฟรีเพลงต่อไปไหม? โหวตได้ที่ https://requests.nomadkaraoke.com",
|
||||
"signOff": "ขอให้สนุกกับการร้องเพลงนะ!\n-Andrew",
|
||||
"greeting": "สวัสดี {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} พร้อมให้ร้องแล้วบน YouTube! 🎉",
|
||||
"subjectFallback": "เพลงที่คุณโหวตพร้อมให้ร้องแล้ว!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "มีเวอร์ชันคาราโอเกะของเพลง {artist} - {title} อยู่แล้ว",
|
||||
"subjectFallback": "มีเวอร์ชันคาราโอเกะของเพลงที่คุณขออยู่แล้ว"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Magandang balita! Na-upload na sa YouTube ang iyong karaoke video para sa \"{artist} - {title}\":",
|
||||
"delayNote": "Saglit na naantala ang upload na ito habang pinoproseso ng aming mga system ang iba pang mga upload, pero ayos na ang lahat ngayon.",
|
||||
"signOff": "Salamat!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Magandang balita — live na sa YouTube ang \"{artist} - {title}\", ang karaoke track na binoto mo sa requests board ng Nomad Karaoke:",
|
||||
"callToAction": "Gusto mong pumili ng susunod na libreng track? Bumoto sa https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hi {name},",
|
||||
"signOff": "Salamat sa pagboto!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Magandang balita — mayroon nang karaoke version online ng \"{artist} - {title}\" (na binoto mo sa Nomad Karaoke requests board), kaya hindi na namin ito gagawin ulit. Heto ang version na magagamit mo ngayon:",
|
||||
"callToAction": "Gusto mo bang tumulong sa pagpili ng susunod na LIBRENG track na gagawin namin? Bumoto sa https://requests.nomadkaraoke.com",
|
||||
"signOff": "Happy singing!\n-Andrew",
|
||||
"greeting": "Hi {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} ay live na sa YouTube! 🎉",
|
||||
"subjectFallback": "Live na ang track na binoto mo!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Mayroon nang karaoke version ng {artist} - {title}",
|
||||
"subjectFallback": "Mayroon nang karaoke version ang kantang ni-request mo"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Harika haber! \"{artist} - {title}\" için karaoke videon YouTube'a yüklendi:",
|
||||
"delayNote": "Sistemlerimiz diğer yüklemeleri işlerken bu yükleme kısa bir süreliğine gecikti, ancak şimdi her şey hazır.",
|
||||
"signOff": "Teşekkürler!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Harika haber — Nomad Karaoke istek panosunda oy verdiğin karaoke parçası \"{artist} - {title}\" artık YouTube'da yayında:",
|
||||
"callToAction": "Bir sonraki ücretsiz parçayı seçmek ister misin? https://requests.nomadkaraoke.com adresinden oy ver",
|
||||
"greeting": "Merhaba {name},",
|
||||
"signOff": "Oy verdiğin için teşekkürler!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "İyi haber! Nomad Karaoke istek panosunda oy verdiğin \"{artist} - {title}\" şarkısının bir karaoke versiyonu internette zaten mevcut, bu yüzden bu şarkıyı yeniden yapmayacağız. İşte hemen şimdi kullanabileceğin bir versiyon:",
|
||||
"callToAction": "Yapacağımız bir sonraki ÜCRETSİZ parçayı seçmemize yardım etmek ister misin? https://requests.nomadkaraoke.com adresinden oy ver",
|
||||
"signOff": "Keyifli şarkılar!\n-Andrew",
|
||||
"greeting": "Merhaba {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} YouTube'da yayında! 🎉",
|
||||
"subjectFallback": "Oy verdiğin bir parça artık yayında!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "{artist} - {title} şarkısının bir karaoke versiyonu zaten mevcut",
|
||||
"subjectFallback": "İstediğin şarkının bir karaoke versiyonu zaten mevcut"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Чудові новини! Твоє караоке-відео для \"{artist} - {title}\" було завантажено на YouTube:",
|
||||
"delayNote": "Це завантаження було ненадовго відкладено, поки наші системи обробляли інші завантаження, але тепер усе готово.",
|
||||
"signOff": "Дякую!\n-Ендрю"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Чудові новини — караоке-трек \"{artist} - {title}\", за який ти голосував(-ла) на дошці запитів Nomad Karaoke, вже доступний на YouTube:",
|
||||
"callToAction": "Хочеш обрати наступний безкоштовний трек? Голосуй за посиланням: https://requests.nomadkaraoke.com",
|
||||
"greeting": "Привіт, {name},",
|
||||
"signOff": "Дякую за твій голос!\n-Ендрю"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Гарні новини — караоке-версія \"{artist} - {title}\" (яка отримала твій голос на дошці запитів Nomad Karaoke) вже є в інтернеті, тому ми не будемо створювати її наново. Ось версія, якою можна скористатися прямо зараз:",
|
||||
"callToAction": "Хочеш допомогти обрати наступний БЕЗКОШТОВНИЙ трек, який ми створимо? Голосуй на https://requests.nomadkaraoke.com",
|
||||
"signOff": "Приємного співу!\n-Ендрю",
|
||||
"greeting": "Привіт, {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} вже на YouTube! 🎉",
|
||||
"subjectFallback": "Трек, за який ти голосував(-ла), вже доступний!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Караоке-версія {artist} - {title} вже існує",
|
||||
"subjectFallback": "Караоке-версія замовленої тобою пісні вже існує"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "Tin tuyệt vời! Video karaoke của bạn cho bài hát \"{artist} - {title}\" đã được tải lên YouTube:",
|
||||
"delayNote": "Bản tải lên này đã bị trì hoãn một thời gian ngắn trong khi hệ thống của chúng tôi xử lý các bản tải lên khác, nhưng mọi thứ hiện đã sẵn sàng.",
|
||||
"signOff": "Cảm ơn bạn!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "Tin vui đây — \"{artist} - {title}\", bài hát karaoke mà bạn đã bình chọn trên bảng yêu cầu của Nomad Karaoke, hiện đã có trên YouTube:",
|
||||
"callToAction": "Bạn muốn chọn bài hát miễn phí tiếp theo? Hãy bình chọn tại https://requests.nomadkaraoke.com",
|
||||
"greeting": "Chào {name},",
|
||||
"signOff": "Cảm ơn bạn đã bình chọn!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Tin vui đây — phiên bản karaoke của \"{artist} - {title}\" (mà bạn đã bình chọn trên bảng yêu cầu của Nomad Karaoke) đã có sẵn trên mạng, nên chúng tôi sẽ không làm lại bài này nữa. Dưới đây là phiên bản bạn có thể sử dụng ngay:",
|
||||
"callToAction": "Bạn muốn giúp chọn bài hát MIỄN PHÍ tiếp theo mà chúng tôi sẽ làm? Hãy bình chọn tại https://requests.nomadkaraoke.com",
|
||||
"signOff": "Chúc bạn hát vui vẻ!\n-Andrew",
|
||||
"greeting": "Chào {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} đã có trên YouTube! 🎉",
|
||||
"subjectFallback": "Bài hát bạn bình chọn đã lên sóng!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Đã có sẵn phiên bản karaoke của {artist} - {title}",
|
||||
"subjectFallback": "Đã có sẵn phiên bản karaoke của bài hát bạn yêu cầu"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,7 +341,27 @@
|
||||
"greatNews": "好消息!您制作的卡拉OK视频({artist} - {title})已上传至 YouTube:",
|
||||
"delayNote": "由于系统正在处理其他任务,此上传稍有延迟,但现在一切都已就绪。",
|
||||
"signOff": "谢谢!\n-Andrew"
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"body": "好消息——您在 Nomad Karaoke 点歌板上投票的卡拉OK曲目“{artist} - {title}”现已在 YouTube 上线:",
|
||||
"callToAction": "想挑选下一首免费曲目吗?请访问 https://requests.nomadkaraoke.com 投票",
|
||||
"greeting": "嗨,{name},",
|
||||
"signOff": "感谢您的投票!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "好消息 —— 您在 Nomad Karaoke 点歌板上投票的 \"{artist} - {title}\" 的卡拉OK版本网上已经有了,所以我们就不重复制作了。您可以直接使用以下版本:",
|
||||
"callToAction": "想帮忙挑选我们制作的下一首免费伴奏吗?请前往 https://requests.nomadkaraoke.com 投票",
|
||||
"signOff": "祝您欢唱愉快!\n-Andrew",
|
||||
"greeting": "嗨,{name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} 已在 YouTube 上线!🎉",
|
||||
"subjectFallback": "您投票的曲目现已上线!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "{artist} - {title} 的卡拉OK版本已存在",
|
||||
"subjectFallback": "您请求的歌曲的卡拉OK版本已存在"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
"""Daily free-community-track picker (requests voting board — Phase 2).
|
||||
|
||||
Once per UTC day this:
|
||||
1. Claims the day atomically (a create-only lock doc) so only one run can ever
|
||||
make a track that day — "one free track per day, total".
|
||||
2. Picks the highest-priority eligible open request (top net votes, oldest-first,
|
||||
skipping community-rejected net<0). Human votes and (future) trending-agent
|
||||
submissions feed the same queue — the picker is source-agnostic.
|
||||
3. Grants the requester one free credit and submits the job **as that user**
|
||||
(non-admin, so the credit is consumed and the job is owned by them), reusing
|
||||
the same search → auto-select → download primitives the web flow uses.
|
||||
4. Advances the request open → queued → in_progress and records job_id/owner.
|
||||
|
||||
Every side effect is idempotent and gated by durable markers on the request +
|
||||
the per-day lock's ``phase`` so a retried Scheduler delivery or a crash mid-run
|
||||
can resume the same day without double-granting credits or making two tracks.
|
||||
|
||||
Triggered by Cloud Scheduler (noon US Eastern) via POST /api/internal/community-daily-pick.
|
||||
Master kill-switch: settings.community_daily_pick_enabled (default off — deploys dark).
|
||||
"""
|
||||
import html
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.models.job import JobCreate, JobStatus
|
||||
from backend.models.song_request import SongRequest
|
||||
from backend.services.audio_search_service import (
|
||||
AudioSearchError,
|
||||
AudioSearchService,
|
||||
NoResultsError,
|
||||
)
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
COMMUNITY_CREDIT_REASON = "community_daily_pick"
|
||||
COMMUNITY_REVIEW_ADMIN_EMAIL = "andrew@nomadkaraoke.com"
|
||||
|
||||
|
||||
def _utc_today() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
async def run_daily_pick(dry_run: bool = False) -> Dict[str, Any]:
|
||||
"""Claim today, walk the ranked requests, and make the first one that has no
|
||||
existing community karaoke version (idempotently).
|
||||
|
||||
For each candidate in rank order we run the same KaraokeNerds check the job
|
||||
flow uses. A candidate that already has a community version is flagged for
|
||||
Andrew's review (kept off auto-make, emailed to him) and we move on to the
|
||||
next — so a fresh, non-duplicate free track still ships that day.
|
||||
|
||||
Args:
|
||||
dry_run: shadow mode — logs what it would make/flag but persists nothing.
|
||||
Also used implicitly when the master kill-switch is off.
|
||||
"""
|
||||
service = get_song_request_service()
|
||||
settings = get_settings()
|
||||
date = _utc_today()
|
||||
|
||||
# Shadow mode (explicit dry-run OR the master kill-switch is off) must NOT
|
||||
# claim the day or persist flags — otherwise a manual dry-run would burn the
|
||||
# per-day lock and block the real scheduler run. It only peeks.
|
||||
shadow = dry_run or not settings.community_daily_pick_enabled
|
||||
if shadow:
|
||||
reason = "dry_run" if dry_run else "kill_switch_off"
|
||||
chosen, flagged = await _select_candidate(service, shadow=True)
|
||||
logger.info(
|
||||
"daily-pick[SHADOW:%s]: would make %s; would flag %d existing-version dup(s)",
|
||||
reason, f"{chosen.artist} - {chosen.title}" if chosen else "nothing", len(flagged),
|
||||
)
|
||||
return {"status": "shadow", "reason": reason, "date": date,
|
||||
"request_id": chosen.id if chosen else None,
|
||||
"artist": chosen.artist if chosen else None,
|
||||
"title": chosen.title if chosen else None,
|
||||
"would_flag": [f["request"].id for f in flagged]}
|
||||
|
||||
# Real path — claim the day atomically so at most one run proceeds.
|
||||
lock, claimed_new = service.claim_day(date)
|
||||
if not claimed_new:
|
||||
if lock.phase in ("done", "empty"):
|
||||
logger.info("daily-pick: day %s already resolved (phase=%s)", date, lock.phase)
|
||||
return {"status": "already_done", "date": date, "phase": lock.phase,
|
||||
"request_id": lock.request_id, "job_id": lock.job_id}
|
||||
logger.info("daily-pick: resuming incomplete day %s (phase=%s)", date, lock.phase)
|
||||
|
||||
# Resume: a prior run already chose a request — finish making it.
|
||||
if lock.request_id:
|
||||
request = service.get_request(lock.request_id)
|
||||
if request is None:
|
||||
service.update_lock(date, phase="empty", note="chosen request vanished")
|
||||
return {"status": "empty", "date": date}
|
||||
return await _make_request(service, settings, date, request)
|
||||
|
||||
# Fresh: walk candidates, flag existing-version dups, pick the first clean one.
|
||||
chosen, flagged = await _select_candidate(service, shadow=False)
|
||||
newly_flagged = [f for f in flagged if f["newly"]]
|
||||
if newly_flagged:
|
||||
_email_admin_flagged(newly_flagged)
|
||||
|
||||
if chosen is None:
|
||||
service.update_lock(
|
||||
date, phase="empty", note=f"no clean candidate ({len(flagged)} flagged)"
|
||||
)
|
||||
logger.info(
|
||||
"daily-pick: nothing makeable for %s (%d flagged for review)", date, len(flagged)
|
||||
)
|
||||
return {"status": "empty", "date": date,
|
||||
"flagged": [f["request"].id for f in flagged]}
|
||||
|
||||
result = await _make_request(service, settings, date, chosen)
|
||||
result["flagged"] = [f["request"].id for f in flagged]
|
||||
return result
|
||||
|
||||
|
||||
async def _select_candidate(service, shadow: bool):
|
||||
"""Walk ranked pick-candidates, KaraokeNerds-checking each. Returns
|
||||
(chosen_request | None, flagged) where flagged is a list of
|
||||
{request, versions, newly} for candidates that already have a community
|
||||
version. In real mode dups are persisted as review_state=pending (idempotent;
|
||||
``newly`` is True only the first time). Shadow mode persists nothing."""
|
||||
from backend.services.karaokenerds_service import check_community_versions
|
||||
|
||||
chosen = None
|
||||
flagged = []
|
||||
for req in service.list_pick_candidates():
|
||||
try:
|
||||
result = await check_community_versions(req.artist, req.title)
|
||||
except Exception: # noqa: BLE001 (defensive — the service already swallows)
|
||||
logger.warning(
|
||||
"daily-pick: community check errored for %s - %s; treating as clean",
|
||||
req.artist, req.title, exc_info=True,
|
||||
)
|
||||
result = {"has_community": False}
|
||||
|
||||
if result.get("has_community"):
|
||||
versions = _versions_payload(result)
|
||||
newly = True if shadow else service.set_review_pending(req.id, versions)
|
||||
logger.info(
|
||||
"daily-pick: %s existing community version for %s — %s - %s",
|
||||
"would flag" if shadow else "flagged", req.id, req.artist, req.title,
|
||||
)
|
||||
flagged.append({"request": req, "versions": versions, "newly": newly})
|
||||
continue
|
||||
|
||||
chosen = req
|
||||
break
|
||||
return chosen, flagged
|
||||
|
||||
|
||||
def _versions_payload(result: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Flatten a KaraokeNerds check result into the subset we store on the request
|
||||
(for the admin queue + the reject-to-voters email)."""
|
||||
tracks = []
|
||||
for song in result.get("songs", []) or []:
|
||||
for tr in song.get("community_tracks", []) or []:
|
||||
if tr.get("youtube_url"):
|
||||
tracks.append({
|
||||
"brand_name": tr.get("brand_name") or "Unknown",
|
||||
"youtube_url": tr.get("youtube_url"),
|
||||
})
|
||||
return {"best_youtube_url": result.get("best_youtube_url"), "tracks": tracks[:10]}
|
||||
|
||||
|
||||
def _email_admin_flagged(flagged) -> None:
|
||||
"""Email Andrew a summary of newly-flagged picks (referrals.py pattern)."""
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
rows = []
|
||||
for f in flagged:
|
||||
r = f["request"]
|
||||
v = f["versions"] or {}
|
||||
links = ", ".join(
|
||||
f'<a href="{html.escape(t["youtube_url"])}">{html.escape(t["brand_name"])}</a>'
|
||||
for t in (v.get("tracks") or [])[:3] if t.get("youtube_url")
|
||||
)
|
||||
rows.append(
|
||||
f"<li><strong>{html.escape(r.artist)} - {html.escape(r.title)}</strong> "
|
||||
f"({r.vote_count} votes) — existing: {links or html.escape(v.get('best_youtube_url') or '?')}</li>"
|
||||
)
|
||||
html_content = (
|
||||
f"<p>The daily community picker flagged {len(flagged)} top request(s) that already "
|
||||
f"have community karaoke versions online:</p><ul>{''.join(rows)}</ul>"
|
||||
f"<p>Keep / make ours / reject at "
|
||||
f'<a href="https://gen.nomadkaraoke.com/admin/community-reviews">/admin/community-reviews</a>.</p>'
|
||||
)
|
||||
get_email_service().provider.send_email(
|
||||
to_email=COMMUNITY_REVIEW_ADMIN_EMAIL,
|
||||
subject=f"[Requests board] {len(flagged)} pick(s) need review — existing karaoke versions",
|
||||
html_content=html_content,
|
||||
text_content=(
|
||||
f"{len(flagged)} flagged requests-board picks already have community versions. "
|
||||
f"Review at https://gen.nomadkaraoke.com/admin/community-reviews"
|
||||
),
|
||||
)
|
||||
logger.info("daily-pick: emailed admin about %d flagged pick(s)", len(flagged))
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("daily-pick: failed to email admin about flagged picks")
|
||||
|
||||
|
||||
async def _make_request(service, settings, date: str, request: SongRequest) -> Dict[str, Any]:
|
||||
"""Drive a chosen request to in_progress idempotently, threading the per-day
|
||||
lock's phase markers. Safe to re-enter (resume)."""
|
||||
owner = (request.owner_email or request.submitted_by).lower()
|
||||
|
||||
def phase_cb(p, **kw):
|
||||
service.update_lock(date, phase=p, **kw)
|
||||
|
||||
result = await _provision_and_start(service, settings, request, owner, phase_cb)
|
||||
result["date"] = date
|
||||
return result
|
||||
|
||||
|
||||
async def _provision_and_start(service, settings, request, owner, phase_cb=None) -> Dict[str, Any]:
|
||||
"""Grant the free credit, create the job as the requester, kick off search +
|
||||
download, and advance the request to in_progress + assign the owner. Idempotent
|
||||
and re-entrant. ``phase_cb(phase, **fields)`` (optional) records progress on the
|
||||
daily lock for the picker; the admin "make ours" path passes None.
|
||||
|
||||
Returns a "made"/"error" summary (no date — callers add their own context)."""
|
||||
def phase(p, **kw):
|
||||
if phase_cb:
|
||||
phase_cb(p, **kw)
|
||||
|
||||
# 1) Claim the request: open -> queued (no-op if already advanced).
|
||||
if request.status == "open":
|
||||
service.transition_status(
|
||||
request.id, "open", "queued",
|
||||
picked_at=datetime.now(timezone.utc).isoformat(),
|
||||
)
|
||||
phase("claimed", request_id=request.id, owner_email=owner)
|
||||
|
||||
# 2) Grant the free credit (guarded so a retry can't re-grant).
|
||||
request = service.get_request(request.id) or request
|
||||
if not request.community_credit_granted:
|
||||
ok, balance, msg = get_user_service().add_credits(
|
||||
owner, amount=1, reason=COMMUNITY_CREDIT_REASON,
|
||||
)
|
||||
if not ok:
|
||||
logger.error("daily-pick: credit grant failed for %s: %s", owner, msg)
|
||||
return {"status": "error", "step": "grant_credit",
|
||||
"request_id": request.id, "message": msg}
|
||||
service.mark_credit_granted(request.id)
|
||||
logger.info("daily-pick: granted 1 credit to %s (balance=%s)", owner, balance)
|
||||
phase("credit_granted")
|
||||
|
||||
# 3) Create the job as the requester (non-admin → consumes the granted credit).
|
||||
request = service.get_request(request.id) or request
|
||||
job_id = request.job_id
|
||||
if not job_id:
|
||||
try:
|
||||
job_id = _create_community_job(request, owner, settings)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("daily-pick: job creation failed for request %s", request.id)
|
||||
return {"status": "error", "step": "create_job",
|
||||
"request_id": request.id, "message": str(e)}
|
||||
service.set_job_id(request.id, job_id)
|
||||
phase("job_created", job_id=job_id)
|
||||
|
||||
# 4) Kick off search + auto-download for the job (idempotent trigger).
|
||||
search_ok = await _search_and_download(job_id, request)
|
||||
|
||||
# 5) Advance to in_progress and assign the owner (starts the 24h handoff clock).
|
||||
if request.status in ("open", "queued"):
|
||||
service.transition_status(request.id, request.status, "in_progress")
|
||||
service.assign_owner(request.id, owner)
|
||||
phase("done")
|
||||
|
||||
logger.info(
|
||||
"daily-pick: made request %s (job %s, owner %s, search_ok=%s)",
|
||||
request.id, job_id, owner, search_ok,
|
||||
)
|
||||
return {"status": "made", "request_id": request.id,
|
||||
"job_id": job_id, "owner": owner, "search_ok": search_ok,
|
||||
"artist": request.artist, "title": request.title}
|
||||
|
||||
|
||||
def _create_community_job(request: SongRequest, owner: str, settings) -> str:
|
||||
"""Create a PENDING job owned by the requester, mirroring search_audio."""
|
||||
theme_id = get_theme_service().get_default_theme_id()
|
||||
job_create = JobCreate(
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
theme_id=theme_id,
|
||||
enable_cdg=settings.default_enable_cdg,
|
||||
enable_txt=settings.default_enable_txt,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
youtube_description_template=settings.default_youtube_description,
|
||||
discord_webhook_url=settings.default_discord_webhook_url,
|
||||
dropbox_path=settings.default_dropbox_path,
|
||||
gdrive_folder_id=settings.default_gdrive_folder_id,
|
||||
user_email=owner,
|
||||
audio_search_artist=request.artist,
|
||||
audio_search_title=request.title,
|
||||
auto_download=True,
|
||||
review_mode="auto",
|
||||
backing_preference="auto",
|
||||
)
|
||||
job_manager = JobManager()
|
||||
job = job_manager.create_job(job_create, is_admin=False)
|
||||
job_manager.update_job(job.job_id, {
|
||||
"audio_search_artist": request.artist,
|
||||
"audio_search_title": request.title,
|
||||
"auto_download": True,
|
||||
# Tag the job so the publish hook + stale-review exclusion can find it.
|
||||
"state_data.community_request_id": request.id,
|
||||
})
|
||||
return job.job_id
|
||||
|
||||
|
||||
async def _search_and_download(job_id: str, request: SongRequest) -> bool:
|
||||
"""Run audio search, auto-select the best source, and trigger the download.
|
||||
|
||||
Returns True if the download was triggered. On no-results/search failure the
|
||||
job is parked in AWAITING_AUDIO_SELECTION so the owner can pick a source
|
||||
manually during their review — the handoff clock still runs.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
|
||||
# Skip if the job already progressed past search (idempotent re-entry).
|
||||
job = job_manager.get_job(job_id)
|
||||
if job and job.status not in (
|
||||
JobStatus.PENDING, JobStatus.SEARCHING_AUDIO, JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
):
|
||||
return True
|
||||
|
||||
# Prepare the theme style (best-effort), then search.
|
||||
from backend.workers.bulk_search_worker import _prepare_theme
|
||||
if job:
|
||||
_prepare_theme(job, job_manager)
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id, new_status=JobStatus.SEARCHING_AUDIO, progress=5,
|
||||
message=f"Searching for: {request.artist} - {request.title}",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
|
||||
audio_search_service = AudioSearchService()
|
||||
try:
|
||||
results = await audio_search_service.search_async(request.artist, request.title)
|
||||
except (NoResultsError, AudioSearchError) as e:
|
||||
logger.warning("daily-pick: 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,
|
||||
)
|
||||
return False
|
||||
|
||||
results_dicts = [r.to_dict() for r in results]
|
||||
store = {"state_data.audio_search_results": results_dicts,
|
||||
"state_data.audio_search_count": len(results_dicts)}
|
||||
remote_id = getattr(audio_search_service, "last_remote_search_id", None)
|
||||
if remote_id:
|
||||
store["state_data.remote_search_id"] = remote_id
|
||||
job_manager.update_job(job_id, store)
|
||||
|
||||
best_index = audio_search_service.select_best(results)
|
||||
from backend.api.routes.audio_search import _validate_and_prepare_selection
|
||||
try:
|
||||
_validate_and_prepare_selection(job_id=job_id, selection_index=best_index)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("daily-pick: validate/prepare failed for job %s: %s", job_id, e)
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id, new_status=JobStatus.AWAITING_AUDIO_SELECTION, progress=10,
|
||||
message="Please choose an audio source.", raise_on_invalid=False,
|
||||
)
|
||||
return False
|
||||
|
||||
return await get_worker_service().trigger_audio_download_worker(job_id)
|
||||
@@ -0,0 +1,143 @@
|
||||
"""24-hour ownership handoff for community picks (requests board — Phase 2).
|
||||
|
||||
The daily picker makes a requests-board track owned by the requester and starts a
|
||||
24h clock. If the owner doesn't complete the (lyrics) review within 24h, the job
|
||||
is handed to the next up-voter — repeatedly, oldest-first — until someone finishes
|
||||
or the voter cap is reached, at which point the track is parked ("stalled").
|
||||
|
||||
Runs hourly via Cloud Scheduler → POST /api/internal/community-handoffs. Only acts
|
||||
on a track when its job is actually blocked waiting for the owner (needs a human);
|
||||
tracks that auto-approved and are still rendering/publishing are left alone.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Job states in which the track is blocked waiting for the OWNER to act. Only in
|
||||
# these states does a stale owner warrant a handoff (a job still separating/
|
||||
# transcribing, or already rendering after an auto-approval, is not the owner's
|
||||
# fault and must not be reassigned).
|
||||
OWNER_BLOCKING_STATUSES = {
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
JobStatus.IN_REVIEW,
|
||||
JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
JobStatus.AWAITING_DURATION_CONFIRM,
|
||||
JobStatus.AWAITING_AUDIO_EDIT,
|
||||
JobStatus.IN_AUDIO_EDIT,
|
||||
}
|
||||
|
||||
|
||||
def _parse_dt(value: Any) -> Optional[datetime]:
|
||||
if not value:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(value))
|
||||
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def _owner_locale(email: str) -> str:
|
||||
try:
|
||||
user = get_user_service().get_user(email)
|
||||
if user and user.locale:
|
||||
return user.locale
|
||||
except Exception:
|
||||
pass
|
||||
return "en"
|
||||
|
||||
|
||||
async def process_community_handoffs() -> Dict[str, Any]:
|
||||
"""Reassign or park community picks whose owner has gone quiet for >24h."""
|
||||
service = get_song_request_service()
|
||||
settings = get_settings()
|
||||
job_manager = JobManager()
|
||||
email_service = get_email_service()
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
handed_off = 0
|
||||
parked = 0
|
||||
checked = 0
|
||||
errors = []
|
||||
|
||||
for req in service.list_in_progress():
|
||||
try:
|
||||
assigned = _parse_dt(req.owner_assigned_at)
|
||||
if assigned is None:
|
||||
continue
|
||||
hours = (now - assigned).total_seconds() / 3600
|
||||
if hours < settings.community_handoff_hours:
|
||||
continue
|
||||
|
||||
job = job_manager.get_job(req.job_id) if req.job_id else None
|
||||
if job is None or job.status not in OWNER_BLOCKING_STATUSES:
|
||||
# Owner isn't the blocker (still processing / auto-approved / done).
|
||||
continue
|
||||
|
||||
checked += 1
|
||||
|
||||
# Cap reached, or no untried up-voters left → park the track.
|
||||
tried = {e.lower() for e in (req.attempted_owners or [])}
|
||||
candidates = [v for v in service.list_upvoters(req.id) if v not in tried]
|
||||
if req.handoff_attempts >= settings.community_handoff_max_attempts or not candidates:
|
||||
service.mark_stalled(req.id)
|
||||
parked += 1
|
||||
logger.info(
|
||||
"handoff: parking request %s (attempts=%d, remaining_voters=%d)",
|
||||
req.id, req.handoff_attempts, len(candidates),
|
||||
)
|
||||
continue
|
||||
|
||||
new_owner = candidates[0]
|
||||
# Compare-and-set the owner FIRST (guards against a stale/overlapping
|
||||
# run clobbering a fresher assignment); only then move the job. Skip if
|
||||
# another run already advanced this request past the owner we observed.
|
||||
if not service.assign_owner(req.id, new_owner, expected_owner=req.owner_email):
|
||||
logger.info("handoff: request %s changed owner mid-run; skipping", req.id)
|
||||
continue
|
||||
# Reassign the job to the next voter (does not move credits — the job
|
||||
# was already paid for at creation; review completion needs no credit).
|
||||
job_manager.update_job(req.job_id, {"user_email": new_owner})
|
||||
|
||||
try:
|
||||
email_service.send_review_reminder(
|
||||
to_email=new_owner,
|
||||
artist=req.artist,
|
||||
title=req.title,
|
||||
job_id=req.job_id,
|
||||
locale=_owner_locale(new_owner),
|
||||
)
|
||||
except Exception as email_err:
|
||||
logger.error("handoff: failed to email new owner for %s: %s", req.id, email_err)
|
||||
|
||||
handed_off += 1
|
||||
logger.info(
|
||||
"handoff: request %s reassigned to %s (attempt %d)",
|
||||
req.id, new_owner, req.handoff_attempts + 1,
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("handoff: error processing request %s", getattr(req, "id", "?"))
|
||||
errors.append(str(e))
|
||||
|
||||
logger.info(
|
||||
"community handoff complete: checked=%d handed_off=%d parked=%d errors=%d",
|
||||
checked, handed_off, parked, len(errors),
|
||||
)
|
||||
return {
|
||||
"status": "completed",
|
||||
"checked": checked,
|
||||
"handed_off": handed_off,
|
||||
"parked": parked,
|
||||
"errors": errors,
|
||||
}
|
||||
@@ -123,6 +123,47 @@ async def process_render_video(job_id: str) -> bool:
|
||||
if not job:
|
||||
logger.error(f"[job:{job_id}] Job not found in Firestore")
|
||||
job_log.error(f"Job {job_id} not found in Firestore!")
|
||||
await worker_registry.unregister(job_id, "render-video")
|
||||
return False
|
||||
|
||||
# Hard idempotency gate (worker-side). The legacy HTTP endpoint enforces
|
||||
# this via _check_worker_idempotency at dispatch time, but the Cloud Run
|
||||
# Job path invokes this worker directly — and Cloud Run may re-run the
|
||||
# execution (max_retries=2) after an OOM/timeout/hard kill. The worker
|
||||
# must therefore protect itself regardless of dispatch path:
|
||||
# - terminal job: never resurrect. A stale or duplicate trigger racing
|
||||
# a job that just finished would otherwise re-render and drag a
|
||||
# complete job back to instrumental_selected.
|
||||
# - already RENDERING_VIDEO: either another execution owns the render
|
||||
# (duplicate trigger) or a previous execution died mid-render (Cloud
|
||||
# Run Job retry). Never re-enter: a live render must not be disrupted,
|
||||
# and a dead one is recovered by the rendering_video_stuck sweep →
|
||||
# re-park → auto-retry. Re-entering would hit the same-state
|
||||
# transition guard and hard-fail the job with a spurious
|
||||
# "Invalid state transition" error.
|
||||
# (Legacy path unaffected: the worker enters with status
|
||||
# REVIEW_COMPLETE — RENDERING_VIDEO is only set below, by this worker.)
|
||||
terminal_statuses = {"failed", "cancelled", "complete", "prep_complete", "error"}
|
||||
status_value = job.status.value if hasattr(job.status, "value") else str(job.status)
|
||||
if status_value in terminal_statuses:
|
||||
logger.info(
|
||||
f"[job:{job_id}] WORKER_END worker=render-video status=skipped "
|
||||
f"reason=terminal_state:{status_value}"
|
||||
)
|
||||
job_log.info(f"Job in terminal state '{status_value}' — skipping render")
|
||||
await worker_registry.unregister(job_id, "render-video")
|
||||
return False
|
||||
if job.status == JobStatus.RENDERING_VIDEO:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] WORKER_END worker=render-video status=skipped "
|
||||
f"reason=already_rendering"
|
||||
)
|
||||
job_log.warning(
|
||||
"Job already in rendering_video — another execution owns this render "
|
||||
"(or a previous one died and the rendering_video_stuck sweep will "
|
||||
"recover it); not re-entering"
|
||||
)
|
||||
await worker_registry.unregister(job_id, "render-video")
|
||||
return False
|
||||
|
||||
# Capture the supersession fence at start. If an admin reset (or a newer
|
||||
@@ -334,7 +375,20 @@ async def process_render_video(job_id: str) -> bool:
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
job_log.info("Triggering video worker for final encoding...")
|
||||
await worker_service.trigger_video_worker(job_id)
|
||||
video_triggered = await worker_service.trigger_video_worker(job_id)
|
||||
if not video_triggered:
|
||||
# No exception path reaches here (trigger returns False
|
||||
# instead of raising) — surface it loudly, or the job
|
||||
# sits at instrumental_selected with no error and no
|
||||
# sweep watching that state.
|
||||
job_log.error(
|
||||
"Video worker dispatch FAILED after render complete — "
|
||||
"job stalls at instrumental_selected until manually retried"
|
||||
)
|
||||
logger.error(
|
||||
f"[job:{job_id}] Video worker dispatch failed after GCE "
|
||||
f"render complete (job stalled at instrumental_selected)"
|
||||
)
|
||||
|
||||
job_manager.update_state_data(job_id, 'render_progress', {'stage': 'complete'})
|
||||
return True
|
||||
@@ -637,7 +691,16 @@ async def process_render_video(job_id: str) -> bool:
|
||||
|
||||
worker_service = get_worker_service()
|
||||
job_log.info("Triggering video worker for final encoding...")
|
||||
await worker_service.trigger_video_worker(job_id)
|
||||
video_triggered = await worker_service.trigger_video_worker(job_id)
|
||||
if not video_triggered:
|
||||
job_log.error(
|
||||
"Video worker dispatch FAILED after render complete — "
|
||||
"job stalls at instrumental_selected until manually retried"
|
||||
)
|
||||
logger.error(
|
||||
f"[job:{job_id}] Video worker dispatch failed after local "
|
||||
f"render complete (job stalled at instrumental_selected)"
|
||||
)
|
||||
|
||||
# Mark render progress as complete for idempotency
|
||||
# This allows the worker to be re-triggered after admin reset
|
||||
@@ -843,3 +906,59 @@ def park_active_render_jobs_for_shutdown() -> int:
|
||||
|
||||
# For compatibility with worker service
|
||||
render_video_worker = process_render_video
|
||||
|
||||
|
||||
# ==================== CLI Entry Point for Cloud Run Jobs ====================
|
||||
# Allows the render worker to run as a standalone Cloud Run Job execution
|
||||
# (video-encoding-job with an args override), immune to Cloud Run Service
|
||||
# deployment rollouts. As a BackgroundTask on the service it was killed ~10s
|
||||
# after SIGTERM whenever a deploy landed mid-render (incident 2026-09-13).
|
||||
# Usage: python -m backend.workers.render_video_worker --job-id <job_id>
|
||||
|
||||
def main():
|
||||
"""CLI entry point for running the render worker as a Cloud Run Job.
|
||||
|
||||
Exit-code contract (differs from video_worker deliberately): the Cloud Run
|
||||
Job template has max_retries=2, and ``process_render_video`` handles every
|
||||
expected failure internally — it parks the job (capacity/shutdown), fails
|
||||
it with a user-facing message, or discards a superseded result. Re-running
|
||||
the worker after any of those would re-enter a job that has already moved
|
||||
to a non-render state. So a clean return (True OR False) exits 0, and only
|
||||
an escaped exception (crash before state was handled) exits 1 to request a
|
||||
Cloud Run retry.
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Post-review render video worker for karaoke generation"
|
||||
)
|
||||
parser.add_argument("--job-id", required=True, help="Job ID to process")
|
||||
args = parser.parse_args()
|
||||
job_id = args.job_id
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
|
||||
logger.info(f"Starting render video worker CLI for job {job_id}")
|
||||
|
||||
try:
|
||||
success = asyncio.run(process_render_video(job_id))
|
||||
if success:
|
||||
logger.info(f"Render video completed successfully for job {job_id}")
|
||||
else:
|
||||
logger.error(
|
||||
f"Render video did not complete for job {job_id} "
|
||||
"(job state already handled by the worker — parked, failed, or superseded)"
|
||||
)
|
||||
sys.exit(0)
|
||||
except Exception as e:
|
||||
logger.error(f"Render video worker crashed: {e}", exc_info=True)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -96,6 +96,12 @@ async def process_stale_reviews() -> Dict[str, Any]:
|
||||
|
||||
# Get blocking state entry time from state_data
|
||||
state_data = job.state_data or {}
|
||||
|
||||
# Skip requests-board community picks — their ownership handoff worker
|
||||
# (community_handoff) owns their review lifecycle; auto-cancel+refund
|
||||
# here would kill a track voters are still waiting on.
|
||||
if state_data.get('community_request_id'):
|
||||
continue
|
||||
blocking_entered_at_str = state_data.get('blocking_state_entered_at')
|
||||
if not blocking_entered_at_str:
|
||||
continue
|
||||
|
||||
@@ -594,21 +594,24 @@ async def redistribute_video(job_id: str) -> bool:
|
||||
job_logger=job_log,
|
||||
)
|
||||
|
||||
# Map downloaded files to orchestrator result attributes by filename patterns
|
||||
# Map downloaded files to orchestrator result attributes by their format tag.
|
||||
# Classify on the trailing parenthetical (not the whole filename) so a track
|
||||
# whose artist/title contains a format word — e.g. "Portrait of Jennie", whose
|
||||
# 720p was misfiled as the portrait video in the encode path (NOMAD-1632) —
|
||||
# redistributes correctly here too.
|
||||
from backend.services.encoding_interface import classify_encoded_output
|
||||
_RESULT_ATTR_BY_FORMAT = {
|
||||
'mp4_4k_lossless': 'final_video',
|
||||
'mkv_4k': 'final_video_mkv',
|
||||
'mp4_4k_lossy': 'final_video_lossy',
|
||||
'mp4_720p': 'final_video_720p',
|
||||
'cdg_zip': 'final_karaoke_cdg_zip',
|
||||
'txt_zip': 'final_karaoke_txt_zip',
|
||||
}
|
||||
for filename, path in downloaded_files.items():
|
||||
lower = filename.lower()
|
||||
if 'lossless' in lower and '4k' in lower and lower.endswith('.mp4'):
|
||||
orchestrator.result.final_video = path
|
||||
elif 'lossless' in lower and lower.endswith('.mkv'):
|
||||
orchestrator.result.final_video_mkv = path
|
||||
elif 'lossy' in lower and '4k' in lower:
|
||||
orchestrator.result.final_video_lossy = path
|
||||
elif '720p' in lower:
|
||||
orchestrator.result.final_video_720p = path
|
||||
elif 'cdg' in lower and lower.endswith('.zip'):
|
||||
orchestrator.result.final_karaoke_cdg_zip = path
|
||||
elif 'txt' in lower and lower.endswith('.zip'):
|
||||
orchestrator.result.final_karaoke_txt_zip = path
|
||||
attr = _RESULT_ATTR_BY_FORMAT.get(classify_encoded_output(filename))
|
||||
if attr:
|
||||
setattr(orchestrator.result, attr, path)
|
||||
|
||||
# Run only organization + distribution + notifications
|
||||
await orchestrator._run_organization()
|
||||
|
||||
@@ -720,6 +720,49 @@ class VideoWorkerOrchestrator:
|
||||
})
|
||||
self.job_log.info("Cleared outputs_deleted_at flag (job was re-processed)")
|
||||
|
||||
# Incident-hardening G1 (SHADOW): before a public release is considered
|
||||
# done, assert the outputs it *should* have shipped (lossy 4K + 720p, plus
|
||||
# CDG when enabled) actually landed on the public GDrive share. This closes
|
||||
# the residual silent-partial hole — e.g. a per-file download failure in
|
||||
# _download_gce_encoded_files clears one result attr, so the upload skips a
|
||||
# None path and publishes a partial release without the encode() guard ever
|
||||
# tripping (exactly the NOMAD-1632 class). Shadow-first: log + alert only,
|
||||
# never fail the job, until a clean shadow window justifies enforcing.
|
||||
self._check_publish_completeness()
|
||||
|
||||
def _check_publish_completeness(self):
|
||||
"""SHADOW check that a public-share release shipped all expected outputs."""
|
||||
try:
|
||||
from backend.services.publish_completeness import compute_publish_shortfall
|
||||
|
||||
missing = compute_publish_shortfall(self.config, self.result)
|
||||
if not missing:
|
||||
return
|
||||
|
||||
missing_str = ", ".join(missing)
|
||||
self.job_log.error(
|
||||
f"PUBLISH_COMPLETENESS shortfall (SHADOW) for job {self.config.job_id}: "
|
||||
f"public release is missing {missing_str}. gdrive_files="
|
||||
f"{self.result.gdrive_files}"
|
||||
)
|
||||
try:
|
||||
from backend.services.ops_alerts import send_ops_alert
|
||||
|
||||
brand = self.result.brand_code or "(no brand)"
|
||||
track = f"{self.config.artist} - {self.config.title}"
|
||||
send_ops_alert(
|
||||
"🟠 **Publish completeness SHADOW** — partial public release detected\n"
|
||||
f"**Job:** `{self.config.job_id}` ({brand})\n"
|
||||
f"**Track:** {track}\n"
|
||||
f"**Missing:** {missing_str}\n"
|
||||
"_Shadow mode: the job was NOT failed. Investigate the "
|
||||
"encode→publish path (silent-partial class, NOMAD-1632)._"
|
||||
)
|
||||
except Exception as alert_exc: # noqa: BLE001
|
||||
self.job_log.warning(f"Publish-completeness alert did not send: {alert_exc}")
|
||||
except Exception as e: # noqa: BLE001 - shadow check must never break distribution
|
||||
self.job_log.warning(f"Publish-completeness check skipped (non-fatal): {e}")
|
||||
|
||||
async def _upload_to_youtube(self):
|
||||
"""Upload video to YouTube."""
|
||||
self.job_log.info("Uploading to YouTube")
|
||||
@@ -764,10 +807,19 @@ class VideoWorkerOrchestrator:
|
||||
# Build video title
|
||||
title = f"{self.config.artist} - {self.config.title} (Karaoke)"
|
||||
|
||||
# Build description
|
||||
description = self.config.youtube_description_template or ""
|
||||
if self.result.brand_code:
|
||||
description = f"{description}\n\nBrand Code: {self.result.brand_code}".strip()
|
||||
# Build description + tags via the shared renderer (single source of
|
||||
# truth, also used by the bulk-rewrite tool).
|
||||
from backend.services.youtube_description import (
|
||||
build_youtube_tags,
|
||||
render_youtube_description,
|
||||
)
|
||||
|
||||
description = render_youtube_description(
|
||||
artist=self.config.artist,
|
||||
title=self.config.title,
|
||||
brand_code=self.result.brand_code,
|
||||
template=self.config.youtube_description_template or None,
|
||||
)
|
||||
|
||||
# Upload
|
||||
video_id, video_url = youtube_service.upload_video(
|
||||
@@ -775,7 +827,7 @@ class VideoWorkerOrchestrator:
|
||||
title=title,
|
||||
description=description,
|
||||
thumbnail_path=self.config.title_jpg_path,
|
||||
tags=["karaoke", self.config.artist, self.config.title],
|
||||
tags=build_youtube_tags(self.config.artist, self.config.title),
|
||||
replace_existing=True, # Server-side always replaces
|
||||
)
|
||||
|
||||
@@ -1038,14 +1090,22 @@ class VideoWorkerOrchestrator:
|
||||
try:
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
success = await worker_service.schedule_gdrive_validation()
|
||||
# Name the just-published track so the validator can check *its own*
|
||||
# completeness same-run (incident-hardening D2), not just global gaps.
|
||||
# Only require CDG when this job actually produced one (video-only /
|
||||
# lyric-less releases legitimately ship no CDG).
|
||||
brand_code = self.result.brand_code
|
||||
expect_cdg = bool(self.result.final_karaoke_cdg_zip)
|
||||
success = await worker_service.schedule_gdrive_validation(
|
||||
brand_code=brand_code, expect_cdg=expect_cdg
|
||||
)
|
||||
if success:
|
||||
self.job_log.info("Scheduled delayed GDrive validation (5 min)")
|
||||
else:
|
||||
# Fallback: trigger immediately if scheduling failed
|
||||
self.job_log.warning("Cloud Tasks scheduling failed, triggering validation immediately")
|
||||
from backend.services.gdrive_validator_client import trigger_gdrive_validation
|
||||
trigger_gdrive_validation()
|
||||
trigger_gdrive_validation(brand_code=brand_code, expect_cdg=expect_cdg)
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"GDrive validation trigger failed (non-fatal): {e}")
|
||||
# Never fail the pipeline for validation
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
"""
|
||||
Scheduled daily worker that rewrites existing YouTube video descriptions on the
|
||||
Nomad Karaoke channel to match the current template
|
||||
(`Settings.default_youtube_description`, rendered via
|
||||
`backend.services.youtube_description`).
|
||||
|
||||
Design (built to be re-usable, not a one-shot):
|
||||
- Each run enumerates the whole channel (cheap, read-only) and computes which
|
||||
videos are "pending" by comparing each video's LIVE description to the freshly
|
||||
rendered template. A video stops being pending once its description matches.
|
||||
- A template fingerprint is stored in Firestore. Whenever the template changes,
|
||||
the fingerprint changes, a fresh "cycle" starts, and every video becomes
|
||||
pending again — so re-running this same worker re-drains the whole channel with
|
||||
zero manual reset. That's the reuse path for any future template change.
|
||||
- Work is capped per run by (a) a hard `youtube_backfill_daily_max_updates` and
|
||||
(b) whatever daily quota is left after reserving `youtube_backfill_quota_reserve`
|
||||
units for the live upload pipeline (via YouTubeQuotaService).
|
||||
- A Postmark email is sent after each run (progress) and once when the channel is
|
||||
fully drained (completion).
|
||||
|
||||
Triggered by Cloud Scheduler → POST /api/internal/youtube-backfill/run.
|
||||
"""
|
||||
import hashlib
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, Optional
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services import youtube_backfill as bf
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
from backend.services.youtube_quota_service import get_youtube_quota_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STATE_COLLECTION = "youtube_backfill"
|
||||
STATE_DOC = "state"
|
||||
_MAX_STORED_ERRORS = 20
|
||||
|
||||
|
||||
def _template_fingerprint(settings) -> str:
|
||||
raw = (settings.default_youtube_description or "").encode("utf-8")
|
||||
return hashlib.sha256(raw).hexdigest()[:16]
|
||||
|
||||
|
||||
def _fresh_cycle_state(prev: Dict, fingerprint: str, now: datetime) -> Dict:
|
||||
return {
|
||||
"template_fingerprint": fingerprint,
|
||||
"cycle_index": (prev.get("cycle_index", 0) or 0) + 1,
|
||||
"cycle_started_at": now,
|
||||
"total_updated_in_cycle": 0,
|
||||
"completed": False,
|
||||
"completed_notified": False,
|
||||
"recent_errors": {},
|
||||
}
|
||||
|
||||
|
||||
def run_backfill_sync(max_updates: Optional[int] = None, dry_run: bool = False) -> Dict:
|
||||
"""Run one daily drain pass. Safe to call repeatedly (idempotent-ish).
|
||||
|
||||
Returns a summary dict (also useful for tests / manual invocation).
|
||||
"""
|
||||
settings = get_settings()
|
||||
if not settings.youtube_backfill_enabled:
|
||||
logger.info("YOUTUBE_BACKFILL disabled; skipping run.")
|
||||
return {"status": "disabled"}
|
||||
|
||||
creds = bf.load_credentials_from_secret()
|
||||
if not creds:
|
||||
logger.error("YOUTUBE_BACKFILL: no YouTube credentials available; skipping.")
|
||||
return {"status": "no_credentials"}
|
||||
|
||||
youtube = bf.build_youtube(creds)
|
||||
db = get_firestore_client()
|
||||
state_ref = db.collection(STATE_COLLECTION).document(STATE_DOC)
|
||||
snap = state_ref.get()
|
||||
state = snap.to_dict() if snap.exists else {}
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
fingerprint = _template_fingerprint(settings)
|
||||
if state.get("template_fingerprint") != fingerprint:
|
||||
logger.info("YOUTUBE_BACKFILL: template changed (or first run) — starting new cycle.")
|
||||
state = _fresh_cycle_state(state, fingerprint, now)
|
||||
|
||||
# Enumerate channel + compute pending (read-only).
|
||||
entries, videos = bf.fetch_all_channel_entries(youtube)
|
||||
total_targets = sum(1 for e in entries if e["target"])
|
||||
pending = [e for e in entries if e["will_change"]]
|
||||
pending_before = len(pending)
|
||||
logger.info(f"YOUTUBE_BACKFILL: {total_targets} targets, {pending_before} pending this run.")
|
||||
|
||||
# Compute today's budget from remaining quota, reserving headroom for uploads.
|
||||
quota = get_youtube_quota_service()
|
||||
try:
|
||||
stats = quota.get_quota_stats()
|
||||
remaining_units = int(stats.get("units_remaining", 0) or 0)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning(f"YOUTUBE_BACKFILL: could not read quota stats: {exc}")
|
||||
stats = {}
|
||||
remaining_units = 0
|
||||
allowed_units = max(0, remaining_units - settings.youtube_backfill_quota_reserve)
|
||||
budget = allowed_units // bf.UPDATE_COST
|
||||
budget = min(budget, settings.youtube_backfill_daily_max_updates)
|
||||
if max_updates is not None:
|
||||
budget = min(budget, max_updates)
|
||||
|
||||
updated = 0
|
||||
errors: Dict[str, str] = {}
|
||||
if not dry_run and pending_before > 0 and budget > 0:
|
||||
for entry in pending[:budget]:
|
||||
vid = entry["video_id"]
|
||||
current_snippet = videos.get(vid, {}).get("snippet", {})
|
||||
body = bf.build_update_snippet(
|
||||
current_snippet, entry, enrich_tags=settings.youtube_backfill_enrich_tags
|
||||
)
|
||||
try:
|
||||
youtube.videos().update(
|
||||
part="snippet", body={"id": vid, "snippet": body}
|
||||
).execute()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
msg = str(exc)
|
||||
errors[vid] = msg
|
||||
if "quotaExceeded" in msg:
|
||||
logger.warning("YOUTUBE_BACKFILL: API quota exceeded; stopping run.")
|
||||
break
|
||||
logger.error(f"YOUTUBE_BACKFILL: update failed for {vid}: {msg}")
|
||||
continue
|
||||
updated += 1
|
||||
try:
|
||||
quota.record_upload(f"desc-backfill:{vid}", units=bf.UPDATE_COST)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
pending_after = pending_before - updated
|
||||
completed = pending_after == 0
|
||||
|
||||
state["total_updated_in_cycle"] = (state.get("total_updated_in_cycle", 0) or 0) + updated
|
||||
state["total_targets"] = total_targets
|
||||
state["last_run_at"] = now
|
||||
state["last_run_updated"] = updated
|
||||
state["last_run_pending_before"] = pending_before
|
||||
state["last_run_pending_after"] = pending_after
|
||||
state["last_run_budget"] = budget
|
||||
state["completed"] = completed
|
||||
# Always refresh (clear when this run had none) so stale errors don't linger.
|
||||
state["recent_errors"] = dict(list(errors.items())[:_MAX_STORED_ERRORS])
|
||||
|
||||
summary = {
|
||||
"status": "ok",
|
||||
"dry_run": dry_run,
|
||||
"cycle_index": state.get("cycle_index"),
|
||||
"total_targets": total_targets,
|
||||
"pending_before": pending_before,
|
||||
"updated": updated,
|
||||
"pending_after": pending_after,
|
||||
"budget": budget,
|
||||
"remaining_units": remaining_units,
|
||||
"completed": completed,
|
||||
"errors": len(errors),
|
||||
}
|
||||
|
||||
if dry_run:
|
||||
logger.info(f"YOUTUBE_BACKFILL (dry-run): {summary}")
|
||||
return summary
|
||||
|
||||
just_completed = completed and not state.get("completed_notified")
|
||||
try:
|
||||
if just_completed:
|
||||
_send_completion_email(settings, state, summary)
|
||||
state["completed_notified"] = True
|
||||
elif updated > 0:
|
||||
# Only email on real progress; a quota-starved 0-update run just logs
|
||||
# (avoids a daily "0 updated" email while uploads hog the quota).
|
||||
_send_progress_email(settings, state, summary, stats, errors)
|
||||
elif pending_before > 0 and budget == 0:
|
||||
logger.info(
|
||||
"YOUTUBE_BACKFILL: no budget this run (quota reserved for uploads); "
|
||||
f"{pending_before} still pending."
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error(f"YOUTUBE_BACKFILL: failed to send report email: {exc}")
|
||||
|
||||
state_ref.set(state)
|
||||
logger.info(f"YOUTUBE_BACKFILL: run complete: {summary}")
|
||||
return summary
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Email reporting
|
||||
# ----------------------------------------------------------------------------
|
||||
def _email_service():
|
||||
from backend.services.email_service import EmailService
|
||||
|
||||
return EmailService()
|
||||
|
||||
|
||||
def _send_progress_email(settings, state, summary, stats, errors):
|
||||
done = summary["total_targets"] - summary["pending_after"]
|
||||
err_html = ""
|
||||
if errors:
|
||||
rows = "".join(f"<li><code>{vid}</code>: {msg}</li>" for vid, msg in list(errors.items())[:10])
|
||||
err_html = f"<p><b>{len(errors)} error(s) this run:</b></p><ul>{rows}</ul>"
|
||||
html = f"""
|
||||
<h2>YouTube descriptions — daily progress</h2>
|
||||
<p>Cycle #{state.get('cycle_index')} · rewriting the channel to the current template.</p>
|
||||
<ul>
|
||||
<li><b>Updated this run:</b> {summary['updated']}</li>
|
||||
<li><b>Remaining (pending):</b> {summary['pending_after']}</li>
|
||||
<li><b>Done so far:</b> {done} / {summary['total_targets']}</li>
|
||||
<li><b>Run budget:</b> {summary['budget']} updates (quota remaining ~{summary['remaining_units']} units)</li>
|
||||
<li><b>Updated in this cycle so far:</b> {state.get('total_updated_in_cycle')}</li>
|
||||
</ul>
|
||||
{err_html}
|
||||
<p>Another batch runs tomorrow until the channel is fully drained.</p>
|
||||
"""
|
||||
_email_service().send_email(
|
||||
to_email=settings.youtube_backfill_report_email,
|
||||
subject=f"[YouTube Descriptions] {summary['updated']} updated, {summary['pending_after']} remaining",
|
||||
html_content=html,
|
||||
)
|
||||
|
||||
|
||||
def _send_completion_email(settings, state, summary):
|
||||
html = f"""
|
||||
<h2>✅ YouTube description rewrite complete</h2>
|
||||
<p>Cycle #{state.get('cycle_index')} is done — every eligible video on the
|
||||
channel now matches the current template.</p>
|
||||
<ul>
|
||||
<li><b>Total targets:</b> {summary['total_targets']}</li>
|
||||
<li><b>Updated in this cycle:</b> {state.get('total_updated_in_cycle')}</li>
|
||||
<li><b>Final pending:</b> {summary['pending_after']}</li>
|
||||
</ul>
|
||||
<p>The daily job will now idle until the template changes again (which will
|
||||
automatically kick off a fresh rewrite cycle).</p>
|
||||
"""
|
||||
_email_service().send_email(
|
||||
to_email=settings.youtube_backfill_report_email,
|
||||
subject="[YouTube Descriptions] ✅ Back-catalogue rewrite complete",
|
||||
html_content=html,
|
||||
)
|
||||
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user