mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 17:47:11 +09:00
Compare commits
No files matched your search
@@ -0,0 +1,120 @@
|
||||
# Plan: Admin Lyrics Review Dashboard
|
||||
|
||||
**Created:** 2026-03-05
|
||||
**Branch:** feat/sess-20260305-0002-admin-lyrics-review
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Add an "Edit Reviews" section to the admin dashboard for reviewing completed lyrics reviews. Three goals:
|
||||
|
||||
1. **View what users saw** - Jump into a read-only lyrics review UI showing original vs corrected lyrics
|
||||
2. **Replay user edits** - Step through edit log entries to see exactly what each user changed
|
||||
3. **Review raw data** - View human edits data to evaluate quality for AudioShake data sharing
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] New admin sidebar item "Edit Reviews" linking to `/admin/edit-reviews`
|
||||
- [ ] Backend endpoint to list recent jobs that have completed lyrics review (with edit logs)
|
||||
- [ ] Backend endpoint to serve immutable correction data for a job (read-only, cannot modify job)
|
||||
- [ ] Admin page showing list of recently reviewed jobs with key metrics
|
||||
- [ ] Ability to open the existing LyricsAnalyzer in read-only mode with snapshot data
|
||||
- [ ] Edit log replay/stepper UI to walk through user changes one by one
|
||||
- [ ] Raw data viewer for edit logs, annotations, and correction diffs
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Backend: 2 new admin endpoints
|
||||
|
||||
1. **`GET /api/admin/edit-reviews`** - List jobs with completed reviews
|
||||
- Query Firestore for jobs with `state_data.last_edit_log_path` set (indicating review was performed)
|
||||
- Filter by status (completed jobs, or optionally all post-review statuses)
|
||||
- Return summary: job_id, artist, title, user_email, review_completed_at, edit_count, feedback_count
|
||||
- Support pagination, search, exclude_test filtering
|
||||
|
||||
2. **`GET /api/admin/edit-reviews/{job_id}`** - Get full review snapshot
|
||||
- Returns immutable copy of:
|
||||
- Original corrections (`corrections.json` from GCS)
|
||||
- Updated corrections (`corrections_updated.json` from GCS)
|
||||
- Edit log (`edit_log_{session_id}.json` from GCS)
|
||||
- Annotations (`annotations.json` from GCS)
|
||||
- Job metadata (artist, title, user_email, timestamps)
|
||||
- Audio URL (signed, for playback in review UI)
|
||||
- This is a **read-only** endpoint - no job state mutations
|
||||
- Uses `require_admin` dependency (not `require_review_auth`)
|
||||
- Does NOT transition job status or modify any state
|
||||
|
||||
### Frontend: New admin page + Read-only review mode
|
||||
|
||||
1. **`/admin/edit-reviews/page.tsx`** - List page
|
||||
- Table of recently reviewed jobs
|
||||
- Columns: Artist/Title, User, Review Date, Edits Made, Feedback Given, Actions
|
||||
- "View Review" button → opens read-only lyrics review
|
||||
- "View Edit Log" button → opens edit replay view
|
||||
- "View Raw Data" button → shows raw JSON
|
||||
|
||||
2. **Read-only review viewer** - Reuse LyricsAnalyzer
|
||||
- Load data from the new admin endpoint (not the regular review endpoint)
|
||||
- Pass `isReadOnly={true}` and `apiClient={null}` to LyricsAnalyzer
|
||||
- Header shows "Admin Review - Read Only" indicator
|
||||
- No submit/save buttons, no state transitions
|
||||
- Audio playback still works (via signed URL)
|
||||
|
||||
3. **Edit log replay** - New component
|
||||
- Timeline/stepper showing each edit entry
|
||||
- For each entry: operation type, text before → text after, timestamp
|
||||
- Step forward/backward through edits
|
||||
- Show feedback reason if user provided one
|
||||
- Summary stats: total edits, edits with feedback, correction types breakdown
|
||||
|
||||
4. **Raw data viewer** - JSON viewer tabs
|
||||
- Tab 1: Edit Log (formatted JSON with syntax highlighting)
|
||||
- Tab 2: Annotations
|
||||
- Tab 3: Corrections diff (original vs updated)
|
||||
|
||||
### Key safety guarantee
|
||||
|
||||
The admin review endpoint serves a **snapshot** of the data. It reads from GCS files that were already written. The LyricsAnalyzer receives `apiClient={null}` so it physically cannot call any mutation endpoints. Even if code changes in the future, the admin endpoint itself never writes to Firestore or GCS.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] **Backend: Add `GET /api/admin/edit-reviews` endpoint** - List reviewed jobs with edit log metadata
|
||||
2. [ ] **Backend: Add `GET /api/admin/edit-reviews/{job_id}` endpoint** - Serve full immutable review snapshot
|
||||
3. [ ] **Frontend: Add admin API client methods** - `adminApi.listEditReviews()`, `adminApi.getEditReview(jobId)`
|
||||
4. [ ] **Frontend: Create `/admin/edit-reviews/page.tsx`** - List page with table
|
||||
5. [ ] **Frontend: Add sidebar nav item** - "Edit Reviews" with BookOpen icon
|
||||
6. [ ] **Frontend: Create read-only review viewer** - Load snapshot data into LyricsAnalyzer with isReadOnly
|
||||
7. [ ] **Frontend: Create edit log replay component** - Step-through UI for edit entries
|
||||
8. [ ] **Frontend: Create raw data viewer** - JSON viewer with tabs
|
||||
9. [ ] **Tests: Backend unit tests** for new admin endpoints
|
||||
10. [ ] **Tests: Frontend component tests** for new page
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/admin.py` | Modify | Add edit-reviews endpoints |
|
||||
| `frontend/lib/api.ts` | Modify | Add adminApi methods for edit reviews |
|
||||
| `frontend/app/admin/edit-reviews/page.tsx` | Create | Main edit reviews list page |
|
||||
| `frontend/components/admin/edit-review-viewer.tsx` | Create | Read-only review wrapper using LyricsAnalyzer |
|
||||
| `frontend/components/admin/edit-log-replay.tsx` | Create | Edit log stepper/replay component |
|
||||
| `frontend/components/admin/raw-data-viewer.tsx` | Create | JSON viewer with tabs |
|
||||
| `frontend/components/admin/admin-sidebar.tsx` | Modify | Add Edit Reviews nav item |
|
||||
| `backend/tests/test_admin_edit_reviews.py` | Create | Backend tests |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- Unit tests for backend endpoints (mock Firestore + GCS)
|
||||
- Verify admin auth is required on all new endpoints
|
||||
- Verify no write operations occur on read-only endpoints
|
||||
- Frontend component tests for key interactions
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should we show ALL jobs that went through review, or only ones with edit logs? (Recommendation: only those with edit logs, since those are the interesting ones)
|
||||
- [ ] Do we need audio playback in the admin review viewer? (Recommendation: yes, it helps understand what the user heard)
|
||||
- [ ] Should the raw data be downloadable? (Nice-to-have, can add later)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
All changes are additive (new endpoints, new pages). Removing the sidebar link effectively hides the feature. No existing behavior is modified.
|
||||
@@ -0,0 +1,149 @@
|
||||
# Plan: Improve Job Observability
|
||||
|
||||
**Created:** 2026-03-07
|
||||
**Branch:** feat/sess-20260307-2216-improve-job-observability
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
After shipping the "edit completed tracks" feature, we found it very difficult to trace what actually happened to edited jobs. Timeline events are too sparse (no output details), cleanup operations aren't logged to Cloud Logging or Firestore, state_data gets fully overwritten during re-processing (losing history of previous outputs), and API endpoints don't write to the job's Firestore log subcollection.
|
||||
|
||||
The goal is to make it trivially easy for future agents and humans to reconstruct the complete lifecycle of any job by reading its timeline and Firestore logs.
|
||||
|
||||
## Problem Analysis
|
||||
|
||||
### What we found investigating two edited jobs:
|
||||
|
||||
1. **Timeline events only have `status`, `timestamp`, `progress`, `message`** — no output details like YouTube video IDs, brand codes, Dropbox links, or GDrive file IDs
|
||||
2. **Edit endpoint cleanup results never logged** — the `cleanup_results` dict is built and returned in the HTTP response but never logged to Cloud Logging or the job's Firestore log subcollection
|
||||
3. **Distribution details incomplete in logs** — YouTube logs the URL but not video_id separately; Dropbox doesn't log folder path; GDrive doesn't log file IDs
|
||||
4. **`state_data` fully overwritten on re-processing** — `video_worker.py:342-354` does `{**job.state_data, ...}`, so any `DELETE_FIELD` operations from the edit endpoint get lost when old keys are re-merged from the in-memory copy
|
||||
5. **`outputs_deleted_at` cleared by video worker** — intentionally, but loses audit trail
|
||||
6. **No Firestore job logs from API endpoints** — edit/admin endpoints only log to Cloud Run stdout, not to `jobs/{job_id}/logs/`
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Add `metadata` dict to `TimelineEvent` for structured output details
|
||||
- [ ] Log all cleanup operations (success AND failure) to both Cloud Logging and Firestore job logs
|
||||
- [ ] Log distribution output details (YouTube video ID, Dropbox path, brand code, GDrive file IDs) in timeline events and Firestore logs
|
||||
- [ ] Preserve previous output details in timeline when a job is edited (snapshot before cleanup)
|
||||
- [ ] Add helper to write Firestore job logs from API endpoints (not just workers)
|
||||
- [ ] Ensure edit/admin delete endpoints write to Firestore job logs
|
||||
- [ ] No breaking changes to existing timeline format (additive only)
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### 1. Add `metadata` field to `TimelineEvent`
|
||||
|
||||
The `TimelineEvent` model gains an optional `metadata: Optional[Dict[str, Any]]` field. This allows any timeline event to carry structured data without changing the schema. The field is additive — existing events without metadata continue to work.
|
||||
|
||||
Key events that gain metadata:
|
||||
- **`complete`**: `{youtube_url, youtube_video_id, dropbox_link, brand_code, gdrive_file_ids}`
|
||||
- **Edit initiated**: `{previous_outputs: {youtube_url, dropbox_link, brand_code, gdrive_files}, cleanup_results: {...}}`
|
||||
- **Outputs deleted**: `{deleted_outputs: {...}, cleanup_results: {...}}`
|
||||
|
||||
### 2. Write Firestore job logs from API endpoints
|
||||
|
||||
Create a simple helper function that API route handlers can call to append logs to the job's Firestore subcollection. Workers already have `JobLogAdapter` — we just need a lightweight equivalent for API routes:
|
||||
|
||||
```python
|
||||
def log_to_job(job_id: str, worker: str, level: str, message: str, metadata: dict = None):
|
||||
"""Write a log entry to the job's Firestore log subcollection."""
|
||||
entry = WorkerLogEntry.create(job_id, worker, level, message, metadata)
|
||||
FirestoreService().append_log_to_subcollection(job_id, entry)
|
||||
```
|
||||
|
||||
### 3. Enhance distribution logging in video_worker_orchestrator
|
||||
|
||||
After each distribution upload succeeds, log the details with structured metadata:
|
||||
- YouTube: video_id, video_url, channel
|
||||
- Dropbox: folder_path, sharing_link
|
||||
- GDrive: file_ids dict
|
||||
- Brand code: code, prefix, allocated vs recycled
|
||||
|
||||
### 4. Snapshot previous outputs on edit
|
||||
|
||||
Before the edit endpoint clears state_data distribution keys, capture the current values in the timeline event's metadata. This preserves the history permanently in the timeline array (which is append-only via `ArrayUnion`).
|
||||
|
||||
### 5. Log cleanup results from edit/admin endpoints
|
||||
|
||||
After cleanup runs, log each step's result to both Cloud Logging and the Firestore job log subcollection with structured metadata.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Add `metadata` to `TimelineEvent` model
|
||||
- [ ] Add `metadata: Optional[Dict[str, Any]] = None` to `TimelineEvent` in `backend/models/job.py`
|
||||
- [ ] No migration needed — Firestore is schemaless, existing events just won't have the field
|
||||
|
||||
### Step 2: Create `log_to_job` helper
|
||||
- [ ] Add `log_to_job()` function in `backend/services/firestore_service.py` (or a small utility module)
|
||||
- [ ] Takes `job_id`, `worker`, `level`, `message`, optional `metadata`
|
||||
- [ ] Wraps `WorkerLogEntry.create()` + `append_log_to_subcollection()`
|
||||
- [ ] Catches and suppresses errors (logging should never break the caller)
|
||||
|
||||
### Step 3: Update `transition_to_state` to accept metadata
|
||||
- [ ] Add optional `timeline_metadata: Optional[Dict[str, Any]] = None` parameter to `job_manager.transition_to_state()`
|
||||
- [ ] Pass through to `update_job_status()` → `TimelineEvent` construction
|
||||
- [ ] Update `firestore_service.update_job_status()` to accept and pass `timeline_metadata`
|
||||
|
||||
### Step 4: Enhance edit endpoint logging
|
||||
- [ ] Before cleanup: snapshot current distribution outputs (`youtube_url`, `dropbox_link`, `brand_code`, `gdrive_files`) into `previous_outputs` dict
|
||||
- [ ] After each cleanup step: log result to Cloud Logging AND call `log_to_job()`
|
||||
- [ ] After all cleanup: include `previous_outputs` and `cleanup_results` in the timeline event metadata
|
||||
- [ ] The "Track edit initiated" timeline event gains metadata: `{initiated_by, previous_outputs, cleanup_results}`
|
||||
|
||||
### Step 5: Enhance admin delete-outputs endpoint logging
|
||||
- [ ] Same pattern as edit endpoint: snapshot outputs, log each cleanup step, include in timeline metadata
|
||||
- [ ] The "Outputs deleted by admin" timeline event gains metadata: `{deleted_by, deleted_outputs, cleanup_results}`
|
||||
|
||||
### Step 6: Enhance distribution logging in video_worker_orchestrator
|
||||
- [ ] YouTube upload success: log video_id and video_url with metadata `{video_id, video_url}`
|
||||
- [ ] Dropbox upload success: log folder_path and sharing_link with metadata `{folder_path, sharing_link}`
|
||||
- [ ] GDrive upload success: log file_ids with metadata `{file_ids: {...}}`
|
||||
- [ ] Brand code allocation: log with metadata `{brand_code, source: "allocated"|"recycled"}`
|
||||
|
||||
### Step 7: Add output details to `complete` timeline event
|
||||
- [ ] When `video_worker.py` calls `transition_to_state(COMPLETE)`, pass `timeline_metadata` with distribution output details
|
||||
- [ ] Include: `youtube_url`, `youtube_video_id`, `dropbox_link`, `brand_code`, `gdrive_file_ids`, `edit_count`
|
||||
|
||||
### Step 8: Tests
|
||||
- [ ] Unit test: `TimelineEvent` with metadata serializes correctly
|
||||
- [ ] Unit test: `log_to_job` writes to subcollection
|
||||
- [ ] Unit test: edit endpoint includes `previous_outputs` and `cleanup_results` in timeline event
|
||||
- [ ] Unit test: `complete` transition includes output metadata
|
||||
- [ ] Verify existing tests still pass
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/models/job.py` | Modify | Add `metadata` field to `TimelineEvent` |
|
||||
| `backend/services/firestore_service.py` | Modify | Add `log_to_job()` helper, update `update_job_status()` to accept timeline metadata |
|
||||
| `backend/services/job_manager.py` | Modify | Add `timeline_metadata` param to `transition_to_state()` |
|
||||
| `backend/api/routes/jobs.py` | Modify | Enhance edit endpoint with cleanup logging, output snapshots, timeline metadata |
|
||||
| `backend/api/routes/admin.py` | Modify | Enhance delete-outputs endpoint similarly |
|
||||
| `backend/workers/video_worker_orchestrator.py` | Modify | Add structured metadata to distribution log messages |
|
||||
| `backend/workers/video_worker.py` | Modify | Pass output metadata in `complete` transition (both orchestrator and legacy paths) |
|
||||
| `backend/tests/test_edit_completed_track.py` | Modify | Verify timeline metadata in edit tests |
|
||||
| `backend/tests/test_observability.py` | Create | Tests for TimelineEvent metadata and log_to_job |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: TimelineEvent metadata serialization, log_to_job helper, edit endpoint timeline metadata assertions
|
||||
- **Existing test verification**: `make test` must pass — changes are additive so existing tests should be unaffected
|
||||
- **No E2E tests needed**: This is purely backend logging/observability — no UI changes
|
||||
|
||||
## What This Does NOT Include
|
||||
|
||||
- **Dedicated admin UI for viewing job logs** — existing admin page already shows timeline
|
||||
- **Log aggregation/search UI** — Cloud Logging and Firestore viewer already serve this purpose
|
||||
- **Changing state_data overwrite behavior** — the `{**job.state_data, ...}` pattern in video_worker.py is intentional; instead we preserve history in timeline events
|
||||
- **Changing outputs_deleted_at clearing** — video worker clearing it after re-processing is correct behavior; the edit history lives in timeline metadata instead
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
All changes are additive (new optional field on TimelineEvent, additional log writes). Rolling back just means deploying the previous version — no data migration needed.
|
||||
|
||||
## Open Questions
|
||||
|
||||
None — the approach is straightforward and low-risk.
|
||||
@@ -20,6 +20,7 @@
|
||||
| API reference | `docs/API.md` |
|
||||
| Past learnings | `docs/LESSONS-LEARNED.md` |
|
||||
| **Operational runbooks** | `docs/TROUBLESHOOTING.md` |
|
||||
| GDrive validator & gaps | `docs/GDRIVE-VALIDATOR.md` |
|
||||
| **Product communication** | `docs/PRODUCT-COMMUNICATION-GUIDE.md` |
|
||||
| Brand style guide | `docs/BRAND-STYLE-GUIDE.md` |
|
||||
|
||||
|
||||
@@ -115,8 +115,16 @@ async def require_auth(
|
||||
|
||||
# If token has a tenant_id, override the hostname-based tenant detection.
|
||||
# This allows tenant-scoped tokens to enforce tenant context regardless of domain.
|
||||
# We must also load tenant_config so downstream handlers (e.g. job creation)
|
||||
# that rely on tenant_config for setting tenant_id on jobs work correctly.
|
||||
if auth_result.tenant_id:
|
||||
request.state.tenant_id = auth_result.tenant_id
|
||||
if not getattr(request.state, "tenant_config", None):
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
tenant_service = get_tenant_service()
|
||||
tenant_config = tenant_service.get_tenant_config(auth_result.tenant_id)
|
||||
if tenant_config and tenant_config.is_active:
|
||||
request.state.tenant_config = tenant_config
|
||||
|
||||
# Log successful auth with request_id for correlation with request audit
|
||||
logger.info(
|
||||
|
||||
+239
-4
@@ -22,6 +22,7 @@ from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchSer
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.audio_search_service import get_audio_search_service, NoResultsError, AudioSearchError
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.firestore_service import log_to_job
|
||||
from backend.utils.test_data import is_test_email
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
@@ -1591,6 +1592,19 @@ async def delete_job_outputs(
|
||||
"gdrive": {"status": "skipped", "reason": "no gdrive_files in state_data"},
|
||||
}
|
||||
|
||||
# Snapshot current outputs before cleanup (preserved in timeline metadata)
|
||||
deleted_outputs = {}
|
||||
if state_data.get('youtube_url'):
|
||||
deleted_outputs['youtube_url'] = state_data['youtube_url']
|
||||
if state_data.get('dropbox_link'):
|
||||
deleted_outputs['dropbox_link'] = state_data['dropbox_link']
|
||||
if state_data.get('brand_code'):
|
||||
deleted_outputs['brand_code'] = state_data['brand_code']
|
||||
if state_data.get('gdrive_files'):
|
||||
deleted_outputs['gdrive_files'] = state_data['gdrive_files']
|
||||
|
||||
log_to_job(job_id, "admin", "INFO", f"Output deletion initiated by {admin_email}", {"deleted_outputs": deleted_outputs})
|
||||
|
||||
# Clean up YouTube
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
@@ -1717,11 +1731,17 @@ async def delete_job_outputs(
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
cleared_keys.append(key)
|
||||
|
||||
# Add timeline event
|
||||
# Add timeline event with structured metadata
|
||||
timeline_event = {
|
||||
"status": job.status, # Keep current status
|
||||
"timestamp": deletion_timestamp.isoformat(),
|
||||
"message": f"Outputs deleted by admin ({admin_email})",
|
||||
"metadata": {
|
||||
"action": "outputs_deleted",
|
||||
"deleted_by": admin_email,
|
||||
"deleted_outputs": deleted_outputs,
|
||||
"cleanup_results": results,
|
||||
},
|
||||
}
|
||||
update_payload["timeline"] = ArrayUnion([timeline_event])
|
||||
|
||||
@@ -1755,6 +1775,10 @@ async def delete_job_outputs(
|
||||
f"Brand Code: {brand_code_status}. "
|
||||
f"Cleared state_data keys: {cleared_keys}"
|
||||
)
|
||||
log_to_job(job_id, "admin", "INFO", f"Outputs deleted by {admin_email}: {overall_status}", {
|
||||
"cleanup_results": results,
|
||||
"cleared_keys": cleared_keys,
|
||||
})
|
||||
|
||||
return DeleteOutputsResponse(
|
||||
status=overall_status,
|
||||
@@ -2089,15 +2113,19 @@ async def regenerate_screens(
|
||||
db = job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
|
||||
# Update state to allow screens worker to run
|
||||
# Set status to lyrics_complete so screens worker can transition to generating_screens.
|
||||
# Store original status so the worker can restore it after regen instead of going to awaiting_review.
|
||||
original_status = job.status
|
||||
job_ref.update({
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.regen_restore_status": original_status,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": job.status,
|
||||
"status": original_status,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Admin {admin_email} triggered screen regeneration"
|
||||
"message": f"Admin {admin_email} triggered screen regeneration (will restore to {original_status})"
|
||||
}])
|
||||
})
|
||||
|
||||
@@ -3039,3 +3067,210 @@ async def backfill_user_stats(
|
||||
updated += 1
|
||||
|
||||
return {"status": "success", "users_checked": len(users_docs), "users_updated": updated}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Edit Review Endpoints
|
||||
# =============================================================================
|
||||
|
||||
class EditReviewSummary(BaseModel):
|
||||
job_id: str
|
||||
artist: str
|
||||
title: str
|
||||
user_email: str
|
||||
status: str
|
||||
created_at: Optional[str] = None
|
||||
updated_at: Optional[str] = None
|
||||
edit_log_session: Optional[str] = None
|
||||
edit_log_path: Optional[str] = None
|
||||
has_corrections_updated: bool = False
|
||||
|
||||
|
||||
class EditReviewListResponse(BaseModel):
|
||||
reviews: List[EditReviewSummary]
|
||||
total: int
|
||||
has_more: bool
|
||||
|
||||
|
||||
@router.get("/edit-reviews", response_model=EditReviewListResponse)
|
||||
def list_edit_reviews(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
exclude_test: bool = False,
|
||||
search: Optional[str] = None,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""List jobs that have completed lyrics review with edit log data."""
|
||||
user_service = get_user_service()
|
||||
db = user_service.db
|
||||
|
||||
STREAM_LIMIT = 10000
|
||||
reviews = []
|
||||
streamed = 0
|
||||
|
||||
for doc in db.collection("jobs").limit(STREAM_LIMIT).stream():
|
||||
streamed += 1
|
||||
data = doc.to_dict()
|
||||
|
||||
# Must have an edit log path
|
||||
state_data = data.get("state_data") or {}
|
||||
edit_log_path = state_data.get("last_edit_log_path")
|
||||
if not edit_log_path:
|
||||
continue
|
||||
|
||||
email = data.get("user_email", "")
|
||||
|
||||
# Filter test emails
|
||||
if exclude_test and is_test_email(email):
|
||||
continue
|
||||
|
||||
artist = data.get("artist", "")
|
||||
title = data.get("title", "")
|
||||
|
||||
# Search filter
|
||||
if search:
|
||||
search_lower = search.lower()
|
||||
if (
|
||||
search_lower not in (artist or "").lower()
|
||||
and search_lower not in (title or "").lower()
|
||||
and search_lower not in (email or "").lower()
|
||||
):
|
||||
continue
|
||||
|
||||
file_urls = data.get("file_urls") or {}
|
||||
has_corrections_updated = bool(
|
||||
file_urls.get("lyrics", {}).get("corrections_updated")
|
||||
)
|
||||
|
||||
created_at = data.get("created_at")
|
||||
updated_at = data.get("updated_at")
|
||||
|
||||
def _to_iso(val) -> Optional[str]:
|
||||
if val is None:
|
||||
return None
|
||||
if hasattr(val, 'isoformat'):
|
||||
return val.isoformat()
|
||||
return str(val)
|
||||
|
||||
try:
|
||||
reviews.append(EditReviewSummary(
|
||||
job_id=doc.id,
|
||||
artist=artist or "",
|
||||
title=title or "",
|
||||
user_email=email or "",
|
||||
status=data.get("status", ""),
|
||||
created_at=_to_iso(created_at),
|
||||
updated_at=_to_iso(updated_at),
|
||||
edit_log_session=state_data.get("last_edit_log_session"),
|
||||
edit_log_path=edit_log_path,
|
||||
has_corrections_updated=has_corrections_updated,
|
||||
))
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {doc.id}: Error building edit review summary: {e}")
|
||||
continue
|
||||
|
||||
if streamed >= STREAM_LIMIT:
|
||||
logger.warning(f"Edit reviews stream hit limit ({STREAM_LIMIT}), results may be incomplete")
|
||||
|
||||
# Sort by most recently updated (or created) descending
|
||||
reviews.sort(
|
||||
key=lambda r: r.updated_at or r.created_at or "",
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
total = len(reviews)
|
||||
paginated = reviews[offset : offset + limit]
|
||||
|
||||
return EditReviewListResponse(
|
||||
reviews=paginated,
|
||||
total=total,
|
||||
has_more=(offset + limit) < total,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/edit-reviews/{job_id}")
|
||||
async def get_edit_review_detail(
|
||||
job_id: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Get full immutable review snapshot for one job. Read-only, no state mutations."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
storage = StorageService()
|
||||
|
||||
# Job metadata
|
||||
job_meta = {
|
||||
"job_id": job.job_id,
|
||||
"artist": job.artist,
|
||||
"title": job.title,
|
||||
"user_email": job.user_email,
|
||||
"status": job.status.value if hasattr(job.status, "value") else str(job.status),
|
||||
"created_at": job.created_at.isoformat() if job.created_at else None,
|
||||
"updated_at": job.updated_at.isoformat() if job.updated_at else None,
|
||||
}
|
||||
|
||||
# Load corrections.json (original)
|
||||
original_corrections = None
|
||||
corrections_path = (job.file_urls.get("lyrics") or {}).get("corrections")
|
||||
if corrections_path:
|
||||
try:
|
||||
original_corrections = storage.download_json(corrections_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not load original corrections from {corrections_path}: {e}")
|
||||
|
||||
# Load corrections_updated.json
|
||||
updated_corrections = None
|
||||
corrections_updated_path = (job.file_urls.get("lyrics") or {}).get("corrections_updated")
|
||||
if corrections_updated_path:
|
||||
try:
|
||||
updated_corrections = storage.download_json(corrections_updated_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not load updated corrections from {corrections_updated_path}: {e}")
|
||||
|
||||
# Load edit log from GCS
|
||||
edit_log = None
|
||||
edit_log_path = (job.state_data or {}).get("last_edit_log_path")
|
||||
if edit_log_path:
|
||||
try:
|
||||
edit_log = storage.download_json(edit_log_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not load edit log from {edit_log_path}: {e}")
|
||||
|
||||
# Load annotations
|
||||
annotations = None
|
||||
annotations_path = f"jobs/{job_id}/lyrics/annotations.json"
|
||||
try:
|
||||
if storage.file_exists(annotations_path):
|
||||
annotations = storage.download_json(annotations_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not load annotations from {annotations_path}: {e}")
|
||||
|
||||
# Generate signed audio URL
|
||||
audio_url = None
|
||||
audio_gcs_path = (
|
||||
(job.file_urls.get("lyrics") or {}).get("audio")
|
||||
or (job.file_urls.get("stems") or {}).get("lead_vocals")
|
||||
or job.input_media_gcs_path
|
||||
)
|
||||
if audio_gcs_path:
|
||||
try:
|
||||
transcoding = AudioTranscodingService(storage_service=storage)
|
||||
audio_url = await transcoding.get_review_audio_url_async(
|
||||
audio_gcs_path, expiration_minutes=120
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not generate audio URL for {audio_gcs_path}: {e}")
|
||||
|
||||
return {
|
||||
"job": job_meta,
|
||||
"original_corrections": original_corrections,
|
||||
"updated_corrections": updated_corrections,
|
||||
"edit_log": edit_log,
|
||||
"annotations": annotations,
|
||||
"audio_url": audio_url,
|
||||
}
|
||||
@@ -50,6 +50,7 @@ from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from pathlib import Path
|
||||
|
||||
@@ -687,11 +688,16 @@ async def search_audio(
|
||||
non_interactive=body.non_interactive,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "audio_search")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
logger.info(f"Created job {job_id} for audio search: {body.artist} - {body.title}")
|
||||
|
||||
# Update job with audio search fields
|
||||
@@ -833,13 +839,12 @@ async def search_audio(
|
||||
selection_index=best_index,
|
||||
)
|
||||
|
||||
# For auto_download, run download in background so this endpoint returns quickly
|
||||
background_tasks.add_task(
|
||||
_download_audio_and_trigger_workers,
|
||||
job_id,
|
||||
best_index,
|
||||
audio_search_service,
|
||||
)
|
||||
# Trigger audio download as a Cloud Run Job (survives instance shutdown)
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_audio_download_worker(job_id)
|
||||
if not triggered:
|
||||
job_manager.fail_job(job_id, "Failed to trigger audio download worker")
|
||||
raise HTTPException(status_code=500, detail="Failed to trigger audio download worker")
|
||||
|
||||
return AudioSearchResponse(
|
||||
status="success",
|
||||
@@ -1156,13 +1161,12 @@ async def select_audio_source(
|
||||
selection_index=body.selection_index,
|
||||
)
|
||||
|
||||
# Schedule the actual download as a background task
|
||||
background_tasks.add_task(
|
||||
_download_audio_and_trigger_workers,
|
||||
job_id,
|
||||
body.selection_index,
|
||||
audio_search_service,
|
||||
)
|
||||
# Trigger audio download as a Cloud Run Job (survives instance shutdown)
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_audio_download_worker(job_id)
|
||||
if not triggered:
|
||||
job_manager.fail_job(job_id, "Failed to trigger audio download worker")
|
||||
raise HTTPException(status_code=500, detail="Failed to trigger audio download worker")
|
||||
|
||||
return AudioSelectResponse(
|
||||
status="success",
|
||||
|
||||
@@ -40,6 +40,7 @@ from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
@@ -56,6 +57,52 @@ def _is_youtube_url(url: str) -> bool:
|
||||
router = APIRouter(tags=["jobs"])
|
||||
|
||||
|
||||
def _apply_tenant_overrides(
|
||||
dist: EffectiveDistributionSettings,
|
||||
tenant_config,
|
||||
effective_theme_id: str | None,
|
||||
is_private: bool,
|
||||
enable_youtube_upload: bool,
|
||||
) -> tuple:
|
||||
"""
|
||||
Apply tenant-specific overrides to distribution settings and job options.
|
||||
|
||||
For tenant jobs:
|
||||
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
|
||||
(only when not already set in the request body / dist)
|
||||
- Forces is_private = True
|
||||
- Applies locked_theme as effective theme
|
||||
- Disables YouTube upload
|
||||
|
||||
Returns:
|
||||
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
|
||||
"""
|
||||
if not tenant_config:
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
defaults = tenant_config.defaults
|
||||
|
||||
# Overlay tenant distribution defaults (request-level values take precedence)
|
||||
if defaults.brand_prefix and not dist.brand_prefix:
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
if defaults.dropbox_path and not dist.dropbox_path:
|
||||
dist.dropbox_path = defaults.dropbox_path
|
||||
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id
|
||||
|
||||
# Force private for all tenant jobs
|
||||
is_private = True
|
||||
|
||||
# Apply locked_theme (overrides any user selection)
|
||||
if defaults.locked_theme:
|
||||
effective_theme_id = defaults.locked_theme
|
||||
|
||||
# Disable YouTube upload for tenants
|
||||
enable_youtube_upload = False
|
||||
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Pydantic models for signed URL upload flow
|
||||
# ============================================================================
|
||||
@@ -510,7 +557,7 @@ async def upload_and_create_job(
|
||||
"auth_url": "/api/auth/status"
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# Extract request metadata for tracking and filtering
|
||||
request_metadata = extract_request_metadata(request, created_from="upload")
|
||||
|
||||
@@ -534,6 +581,14 @@ async def upload_and_create_job(
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Apply tenant-specific overrides (brand, paths, privacy, theme)
|
||||
dist, effective_theme_id, is_private, effective_enable_youtube_upload = _apply_tenant_overrides(
|
||||
dist, tenant_config, effective_theme_id, is_private, effective_enable_youtube_upload,
|
||||
)
|
||||
if tenant_config:
|
||||
logger.info(f"Applied tenant overrides for '{tenant_config.id}': "
|
||||
f"brand={dist.brand_prefix}, private={is_private}, theme={effective_theme_id}")
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(
|
||||
effective_theme_id, enable_cdg, enable_txt
|
||||
@@ -598,11 +653,16 @@ async def upload_and_create_job(
|
||||
# Private (non-published) track mode
|
||||
is_private=is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "upload")
|
||||
add_span_attribute("job.is_private", is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
@@ -1077,12 +1137,29 @@ async def create_job_with_upload_urls(
|
||||
settings = get_settings()
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
|
||||
|
||||
# Apply default theme if none specified
|
||||
effective_theme_id = body.theme_id
|
||||
if effective_theme_id is None:
|
||||
theme_service = get_theme_service()
|
||||
effective_theme_id = theme_service.get_default_theme_id()
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Apply tenant-specific overrides (brand, paths, privacy, theme)
|
||||
effective_is_private = body.is_private
|
||||
dist, effective_theme_id, effective_is_private, effective_enable_youtube_upload = _apply_tenant_overrides(
|
||||
dist, tenant_config, effective_theme_id, effective_is_private, effective_enable_youtube_upload,
|
||||
)
|
||||
if tenant_config:
|
||||
logger.info(f"Applied tenant overrides for '{tenant_config.id}': "
|
||||
f"brand={dist.brand_prefix}, private={effective_is_private}, theme={effective_theme_id}")
|
||||
|
||||
# Validate credentials for requested distribution services
|
||||
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
|
||||
invalid_services = []
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload and not body.is_private:
|
||||
if effective_enable_youtube_upload and not effective_is_private:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -1092,7 +1169,7 @@ async def create_job_with_upload_urls(
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id and not body.is_private:
|
||||
if dist.gdrive_folder_id and not effective_is_private:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -1114,15 +1191,6 @@ async def create_job_with_upload_urls(
|
||||
# Get original audio filename
|
||||
audio_file = audio_files[0]
|
||||
|
||||
# Apply default theme if none specified
|
||||
# This ensures all karaoke videos use the Nomad theme by default
|
||||
effective_theme_id = body.theme_id
|
||||
if effective_theme_id is None:
|
||||
theme_service = get_theme_service()
|
||||
effective_theme_id = theme_service.get_default_theme_id()
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(
|
||||
effective_theme_id, body.enable_cdg, body.enable_txt
|
||||
@@ -1161,13 +1229,18 @@ async def create_job_with_upload_urls(
|
||||
other_stems_models=body.other_stems_models,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
is_private=body.is_private,
|
||||
is_private=effective_is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "signed_url_upload")
|
||||
add_span_attribute("job.is_private", effective_is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
@@ -1510,6 +1583,32 @@ async def create_job_from_url(
|
||||
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL."
|
||||
)
|
||||
|
||||
# For YouTube URLs, check availability before creating the job
|
||||
# This catches geo-restricted, private, and removed videos early
|
||||
if _is_youtube_url(body.url):
|
||||
youtube_service = get_youtube_download_service()
|
||||
availability = await youtube_service.check_availability(body.url)
|
||||
|
||||
if availability and not availability.get("available"):
|
||||
error_msg = availability.get("error", "This video is not available")
|
||||
|
||||
if availability.get("is_geo_restricted"):
|
||||
detail = (
|
||||
"This YouTube video is not available in our server's region. "
|
||||
"Videos that are restricted to certain countries cannot be downloaded. "
|
||||
"Try using a different source for this song."
|
||||
)
|
||||
elif availability.get("is_private"):
|
||||
detail = "This YouTube video is private and cannot be downloaded."
|
||||
elif availability.get("is_removed"):
|
||||
detail = "This YouTube video has been removed and cannot be downloaded."
|
||||
elif availability.get("is_age_restricted"):
|
||||
detail = "This YouTube video is age-restricted and cannot be downloaded."
|
||||
else:
|
||||
detail = f"This YouTube video is unavailable: {error_msg}"
|
||||
|
||||
raise HTTPException(status_code=400, detail=detail)
|
||||
|
||||
# Apply default distribution settings from environment if not provided
|
||||
dist = get_effective_distribution_settings(
|
||||
dropbox_path=body.dropbox_path,
|
||||
@@ -1607,11 +1706,16 @@ async def create_job_from_url(
|
||||
non_interactive=body.non_interactive,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "url")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="url")
|
||||
|
||||
@@ -1909,11 +2013,16 @@ async def create_finalise_only_job(
|
||||
request_metadata=request_metadata,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "finalise")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="finalise")
|
||||
|
||||
|
||||
@@ -501,6 +501,64 @@ async def trigger_gdrive_validation_endpoint(
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
|
||||
@router.post("/recover-stuck-jobs")
|
||||
async def recover_stuck_jobs(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Detect and recover jobs stuck in downloading_audio status.
|
||||
|
||||
Called by Cloud Scheduler (every 5 minutes) or manually from admin.
|
||||
Finds jobs stuck in DOWNLOADING_AUDIO for >10 minutes and fails them
|
||||
so they can be retried.
|
||||
"""
|
||||
from backend.services.job_health_service import check_job_consistency
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
logger.info("RECOVER_STUCK_JOBS starting")
|
||||
add_span_attribute("operation", "recover_stuck_jobs")
|
||||
|
||||
job_manager = JobManager()
|
||||
|
||||
# Query jobs in downloading_audio status
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
jobs_ref = job_manager.firestore.db.collection("jobs")
|
||||
stuck_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", "downloading_audio")
|
||||
).stream()
|
||||
|
||||
recovered = []
|
||||
for doc in stuck_query:
|
||||
job_data = doc.to_dict()
|
||||
job_id = job_data.get("job_id", doc.id)
|
||||
|
||||
# Use the health service to check if actually stuck
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
|
||||
issues = check_job_consistency(job)
|
||||
stuck_issues = [i for i in issues if "downloading_audio_stuck" in i]
|
||||
|
||||
if stuck_issues:
|
||||
logger.warning(f"[job:{job_id}] Recovering stuck download: {stuck_issues[0]}")
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
"Audio download timed out (stuck >10 minutes). Use retry to re-attempt."
|
||||
)
|
||||
recovered.append(job_id)
|
||||
|
||||
logger.info(f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} jobs")
|
||||
add_span_event("recovery_complete", {"recovered_count": len(recovered)})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"recovered_jobs": recovered,
|
||||
"recovered_count": len(recovered),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def internal_health(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
|
||||
+417
-131
@@ -33,13 +33,15 @@ from backend.services.worker_service import get_worker_service
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.config import get_settings
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.api.dependencies import require_admin, require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.metrics import metrics
|
||||
from backend.middleware.tenant import get_tenant_from_request
|
||||
from backend.utils.test_data import is_test_email
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.firestore_service import FirestoreService, log_to_job
|
||||
from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityResponse
|
||||
from pydantic import BaseModel, Field, validator
|
||||
|
||||
|
||||
@@ -130,9 +132,14 @@ async def create_job(
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job.job_id)
|
||||
add_span_attribute("job.source", "url")
|
||||
add_span_attribute("job.is_private", job_create.is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job.job_id, source="url")
|
||||
|
||||
|
||||
# Trigger both workers in parallel using asyncio.gather
|
||||
# (FastAPI's BackgroundTasks runs async tasks sequentially)
|
||||
background_tasks.add_task(_trigger_workers_parallel, job.job_id)
|
||||
@@ -201,11 +208,308 @@ def _check_job_ownership(job: Job, auth_result: AuthResult) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
class EditTrackRequest(BaseModel):
|
||||
"""Request body for editing a completed track."""
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
|
||||
|
||||
class EditTrackResponse(BaseModel):
|
||||
"""Response from editing a completed track."""
|
||||
status: str
|
||||
job_id: str
|
||||
message: str
|
||||
review_url: str
|
||||
review_token: str
|
||||
metadata_updated: bool
|
||||
cleanup_results: Dict[str, Any]
|
||||
|
||||
|
||||
@router.post("/{job_id}/edit", response_model=EditTrackResponse)
|
||||
async def edit_completed_track(
|
||||
job_id: str,
|
||||
request: EditTrackRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Edit a completed track by cleaning up distributed outputs and reopening review.
|
||||
|
||||
This allows users to correct lyrics, change instrumental selection, or update
|
||||
artist/title metadata on a completed job. The existing outputs (YouTube, Dropbox,
|
||||
GDrive, GCS finals) are deleted, the brand code is recycled, and the job is
|
||||
reset to AWAITING_REVIEW so the user can make changes and re-submit.
|
||||
|
||||
No additional credits are consumed — the original credit covers re-edits.
|
||||
"""
|
||||
import re
|
||||
from datetime import timezone
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
# Check ownership
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to edit this job")
|
||||
|
||||
# Only completed jobs can be edited
|
||||
if job.status != JobStatus.COMPLETE.value and job.status != "complete":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Only completed jobs can be edited. Current status: {job.status}"
|
||||
)
|
||||
|
||||
# Prevent editing if outputs already deleted (edit already in progress)
|
||||
if job.outputs_deleted_at:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="This job is already being edited (outputs were already deleted)"
|
||||
)
|
||||
|
||||
user_email = auth_result.user_email or "unknown"
|
||||
state_data = job.state_data or {}
|
||||
cleanup_results = {}
|
||||
|
||||
# Snapshot current outputs before cleanup (preserved in timeline metadata)
|
||||
previous_outputs = {}
|
||||
if state_data.get('youtube_url'):
|
||||
previous_outputs['youtube_url'] = state_data['youtube_url']
|
||||
if state_data.get('dropbox_link'):
|
||||
previous_outputs['dropbox_link'] = state_data['dropbox_link']
|
||||
if state_data.get('brand_code'):
|
||||
previous_outputs['brand_code'] = state_data['brand_code']
|
||||
if state_data.get('gdrive_files'):
|
||||
previous_outputs['gdrive_files'] = state_data['gdrive_files']
|
||||
|
||||
log_to_job(job_id, "edit", "INFO", f"Edit initiated by {user_email}", {"previous_outputs": previous_outputs})
|
||||
|
||||
# --- Phase 1: Clean up distributed outputs ---
|
||||
|
||||
# Delete YouTube video
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
try:
|
||||
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
|
||||
if video_id_match:
|
||||
video_id = video_id_match.group(1)
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False,
|
||||
non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict()
|
||||
)
|
||||
success = finalise.delete_youtube_video(video_id)
|
||||
cleanup_results["youtube"] = {"status": "success" if success else "failed", "video_id": video_id}
|
||||
else:
|
||||
cleanup_results["youtube"] = {"status": "skipped", "reason": "YouTube not configured"}
|
||||
else:
|
||||
cleanup_results["youtube"] = {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting YouTube video for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["youtube"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
cleanup_results["youtube"] = {"status": "skipped", "reason": "no youtube_url"}
|
||||
log_to_job(job_id, "edit", "INFO", f"YouTube cleanup: {cleanup_results['youtube'].get('status')}", cleanup_results["youtube"])
|
||||
|
||||
# Delete Dropbox folder
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
base_name = f"{job.artist} - {job.title}"
|
||||
folder_name = f"{brand_code} - {base_name}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
success = dropbox.delete_folder(full_path)
|
||||
cleanup_results["dropbox"] = {"status": "success" if success else "failed", "path": full_path}
|
||||
else:
|
||||
cleanup_results["dropbox"] = {"status": "skipped", "reason": "Dropbox not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting Dropbox folder for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
cleanup_results["dropbox"] = {"status": "skipped", "reason": "no brand_code or dropbox_path"}
|
||||
log_to_job(job_id, "edit", "INFO", f"Dropbox cleanup: {cleanup_results['dropbox'].get('status')}", cleanup_results["dropbox"])
|
||||
|
||||
# Delete Google Drive files
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
cleanup_results["gdrive"] = {"status": "success" if all_success else "partial", "files": delete_results}
|
||||
else:
|
||||
cleanup_results["gdrive"] = {"status": "skipped", "reason": "Google Drive not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
cleanup_results["gdrive"] = {"status": "skipped", "reason": "no gdrive_files"}
|
||||
log_to_job(job_id, "edit", "INFO", f"GDrive cleanup: {cleanup_results['gdrive'].get('status')}", cleanup_results["gdrive"])
|
||||
|
||||
# Delete GCS finals folder
|
||||
try:
|
||||
storage = StorageService()
|
||||
finals_prefix = f"jobs/{job_id}/finals/"
|
||||
deleted_count = storage.delete_folder(finals_prefix)
|
||||
cleanup_results["gcs_finals"] = {"status": "success", "deleted_count": deleted_count}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting GCS finals for job {job_id}: {e}", exc_info=True)
|
||||
cleanup_results["gcs_finals"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Recycle brand code if Dropbox + GDrive cleanup both succeeded
|
||||
dropbox_ok = cleanup_results.get("dropbox", {}).get("status") in ("success", "skipped")
|
||||
gdrive_ok = cleanup_results.get("gdrive", {}).get("status") in ("success", "skipped")
|
||||
if brand_code and dropbox_ok and gdrive_ok:
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
cleanup_results["brand_code"] = {"status": "recycled", "code": brand_code}
|
||||
logger.info(f"Recycled brand code {brand_code} during edit for job {job_id}")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
cleanup_results["brand_code"] = {"status": "failed", "error": str(e)}
|
||||
|
||||
# Check for critical cleanup failures before proceeding
|
||||
critical_failures = [
|
||||
svc for svc in ["dropbox", "gdrive"]
|
||||
if cleanup_results.get(svc, {}).get("status") == "error"
|
||||
]
|
||||
if critical_failures:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Cleanup failed for {', '.join(critical_failures)}. "
|
||||
f"Job not modified. Please try again or contact support."
|
||||
)
|
||||
|
||||
# --- Phase 2: Update job record ---
|
||||
|
||||
db = FirestoreService().db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
update_payload: Dict[str, Any] = {
|
||||
"outputs_deleted_at": now,
|
||||
"outputs_deleted_by": user_email,
|
||||
"updated_at": now,
|
||||
"edit_count": (job.edit_count if hasattr(job, 'edit_count') else 0) + 1,
|
||||
}
|
||||
|
||||
# Clear distribution state_data keys
|
||||
output_keys = ["youtube_url", "youtube_video_id", "dropbox_link", "brand_code", "gdrive_files"]
|
||||
for key in output_keys:
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
|
||||
# Clear processing state so workers re-run from scratch
|
||||
processing_keys = ["render_progress", "video_progress", "encoding_progress", "review_complete"]
|
||||
for key in processing_keys:
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
|
||||
# --- Phase 3: Update metadata if provided ---
|
||||
|
||||
metadata_updated = False
|
||||
if request.artist and request.artist != job.artist:
|
||||
update_payload["artist"] = request.artist
|
||||
metadata_updated = True
|
||||
if request.title and request.title != job.title:
|
||||
update_payload["title"] = request.title
|
||||
metadata_updated = True
|
||||
|
||||
# If metadata changed, delete screens so they get regenerated
|
||||
if metadata_updated:
|
||||
try:
|
||||
screens_prefix = f"jobs/{job_id}/screens/"
|
||||
storage = StorageService()
|
||||
storage.delete_folder(screens_prefix)
|
||||
logger.info(f"Deleted screens for job {job_id} due to metadata change")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to delete screens for job {job_id}: {e}")
|
||||
|
||||
# Clear screens progress so screens worker re-runs
|
||||
if "screens_progress" in state_data:
|
||||
update_payload[f"state_data.screens_progress"] = DELETE_FIELD
|
||||
|
||||
# Add timeline event with structured metadata
|
||||
edit_number = (job.edit_count if hasattr(job, 'edit_count') else 0) + 1
|
||||
timeline_event = {
|
||||
"status": "complete",
|
||||
"timestamp": now.isoformat(),
|
||||
"message": f"Track edit initiated by {user_email} (edit #{edit_number})",
|
||||
"metadata": {
|
||||
"action": "edit_initiated",
|
||||
"initiated_by": user_email,
|
||||
"edit_number": edit_number,
|
||||
"previous_outputs": previous_outputs,
|
||||
"cleanup_results": cleanup_results,
|
||||
},
|
||||
}
|
||||
update_payload["timeline"] = ArrayUnion([timeline_event])
|
||||
|
||||
# Apply Firestore update
|
||||
job_ref.update(update_payload)
|
||||
|
||||
# --- Phase 4: Transition state to AWAITING_REVIEW ---
|
||||
# This auto-generates a review token via transition_to_state
|
||||
job_manager.transition_to_state(
|
||||
job_id,
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
progress=60,
|
||||
message="Track reopened for editing",
|
||||
)
|
||||
|
||||
# If metadata changed, trigger screens worker in background
|
||||
if metadata_updated:
|
||||
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
|
||||
|
||||
# Fetch updated job to get the review token
|
||||
updated_job = job_manager.get_job(job_id)
|
||||
if not updated_job:
|
||||
logger.error(f"Job {job_id} not found after state transition to AWAITING_REVIEW")
|
||||
raise HTTPException(status_code=500, detail="Job state update failed unexpectedly")
|
||||
review_token = updated_job.review_token or ""
|
||||
|
||||
logger.info(
|
||||
f"User {user_email} initiated edit #{edit_number} for job {job_id}. "
|
||||
f"Metadata updated: {metadata_updated}. "
|
||||
f"Cleanup: YouTube={cleanup_results.get('youtube', {}).get('status')}, "
|
||||
f"Dropbox={cleanup_results.get('dropbox', {}).get('status')}, "
|
||||
f"GDrive={cleanup_results.get('gdrive', {}).get('status')}"
|
||||
)
|
||||
log_to_job(job_id, "edit", "INFO", f"Edit #{edit_number} complete: reopened for review", {
|
||||
"cleanup_results": cleanup_results,
|
||||
"metadata_updated": metadata_updated,
|
||||
})
|
||||
|
||||
return EditTrackResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Track reopened for editing. Previous outputs have been removed.",
|
||||
review_url=f"/app/jobs#/{job_id}/review",
|
||||
review_token=review_token,
|
||||
metadata_updated=metadata_updated,
|
||||
cleanup_results=cleanup_results,
|
||||
)
|
||||
|
||||
|
||||
_SUMMARY_STATE_DATA_KEYS = {
|
||||
'brand_code', 'youtube_url', 'dropbox_link',
|
||||
'audio_progress', 'lyrics_progress',
|
||||
'audio_complete', 'lyrics_complete',
|
||||
'backing_vocals_analysis',
|
||||
'backing_vocals_analysis', 'visibility_change_in_progress',
|
||||
}
|
||||
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete']
|
||||
@@ -294,9 +598,12 @@ async def list_jobs(
|
||||
logger.warning("Non-admin auth without user_email, returning empty job list")
|
||||
return []
|
||||
|
||||
# Get tenant_id from request for portal scoping
|
||||
# Tenant users only see jobs from their tenant
|
||||
# Get tenant_id from request for portal scoping.
|
||||
# Tenant portal: filters to that tenant's jobs.
|
||||
# Consumer portal (no tenant): filters to tenant_id="" (consumer jobs only).
|
||||
# All jobs have tenant_id set: "" for consumer, "vocalstar"/etc for tenants.
|
||||
tenant_id = get_tenant_from_request(request)
|
||||
effective_tenant_id = tenant_id if tenant_id else ""
|
||||
|
||||
# --- Summary mode: field-projected query returning dicts ---
|
||||
if fields == "summary":
|
||||
@@ -309,7 +616,7 @@ async def list_jobs(
|
||||
created_after=created_after_dt,
|
||||
created_before=created_before_dt,
|
||||
user_email=user_email_filter,
|
||||
tenant_id=tenant_id,
|
||||
tenant_id=effective_tenant_id,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
@@ -331,7 +638,7 @@ async def list_jobs(
|
||||
created_after=created_after_dt,
|
||||
created_before=created_before_dt,
|
||||
user_email=user_email_filter,
|
||||
tenant_id=tenant_id,
|
||||
tenant_id=effective_tenant_id,
|
||||
limit=limit
|
||||
)
|
||||
|
||||
@@ -1213,9 +1520,9 @@ async def download_file(
|
||||
storage = StorageService()
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{ext}') as tmp:
|
||||
tmp_path = tmp.name
|
||||
|
||||
|
||||
storage.download_file(gcs_path, tmp_path)
|
||||
|
||||
|
||||
def file_iterator():
|
||||
try:
|
||||
with open(tmp_path, 'rb') as f:
|
||||
@@ -1224,12 +1531,23 @@ async def download_file(
|
||||
finally:
|
||||
import os
|
||||
os.unlink(tmp_path)
|
||||
|
||||
|
||||
# Build Content-Disposition header with RFC 5987 encoding for non-ASCII filenames
|
||||
# (e.g. Chinese, Japanese, Korean characters that can't be encoded in latin-1)
|
||||
from urllib.parse import quote
|
||||
try:
|
||||
filename.encode('latin-1')
|
||||
content_disposition = f'attachment; filename="{filename}"'
|
||||
except UnicodeEncodeError:
|
||||
ascii_filename = filename.encode('ascii', 'replace').decode('ascii')
|
||||
utf8_filename = quote(filename)
|
||||
content_disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{utf8_filename}"
|
||||
|
||||
return StreamingResponse(
|
||||
file_iterator(),
|
||||
media_type=content_type,
|
||||
headers={
|
||||
'Content-Disposition': f'attachment; filename="{filename}"'
|
||||
'Content-Disposition': content_disposition
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
@@ -1460,16 +1778,6 @@ async def retry_job(
|
||||
f"source_name={job.source_name}, source_id={job.source_id}"
|
||||
)
|
||||
|
||||
# Import needed services
|
||||
from backend.services.audio_search_service import get_audio_search_service
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError
|
||||
)
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
# Clear error state
|
||||
job_manager.update_job(job_id, {
|
||||
'error_message': None,
|
||||
@@ -1488,107 +1796,23 @@ async def retry_job(
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
# Retry download using saved params
|
||||
# This is similar to the logic in audio_search.py:_download_and_start_processing
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
try:
|
||||
if job.source_name == 'YouTube':
|
||||
# Use YouTubeDownloadService
|
||||
youtube_service = get_youtube_download_service()
|
||||
video_id = job.source_id
|
||||
|
||||
try:
|
||||
audio_gcs_path = await youtube_service.download_by_id(
|
||||
video_id=video_id,
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
)
|
||||
filename = os.path.basename(audio_gcs_path)
|
||||
except YouTubeDownloadError as e:
|
||||
job_manager.fail_job(job_id, f"Audio download retry failed: YouTube download failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"YouTube download failed: {e}")
|
||||
|
||||
elif job.source_name in ['RED', 'OPS', 'Spotify']:
|
||||
# Use audio search service for torrent/Spotify sources
|
||||
if not audio_search_service.is_remote_enabled():
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
f"Cannot retry: flacfetch service not configured for {job.source_name}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Cannot download from {job.source_name} without remote flacfetch service."
|
||||
)
|
||||
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
|
||||
try:
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=job.source_name,
|
||||
source_id=job.source_id,
|
||||
output_dir="",
|
||||
target_file=job.target_file,
|
||||
download_url=job.download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
audio_gcs_path = result.filepath
|
||||
if audio_gcs_path.startswith('gs://'):
|
||||
audio_gcs_path = audio_gcs_path.replace('gs://karaoke-gen-storage/', '', 1)
|
||||
filename = os.path.basename(result.filepath)
|
||||
|
||||
except DownloadError as e:
|
||||
job_manager.fail_job(job_id, f"Audio download retry failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Download failed: {e}")
|
||||
else:
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
f"Cannot retry: unknown source type {job.source_name}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unknown source type: {job.source_name}"
|
||||
)
|
||||
|
||||
# Update job with GCS path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': filename,
|
||||
})
|
||||
|
||||
# Transition to DOWNLOADING and trigger workers
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=15,
|
||||
message="Audio downloaded, starting processing"
|
||||
# Trigger audio download via Cloud Run Job (runs to completion,
|
||||
# immune to HTTP instance termination)
|
||||
triggered = await worker_service.trigger_audio_download_worker(job_id)
|
||||
if not triggered:
|
||||
job_manager.fail_job(job_id, "Failed to trigger audio download worker")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to trigger audio download worker"
|
||||
)
|
||||
|
||||
# Trigger workers in background
|
||||
async def trigger_workers():
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
background_tasks.add_task(trigger_workers)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"job_status": "downloading",
|
||||
"message": f"Job retry started: re-downloading from {job.source_name}",
|
||||
"retry_stage": "audio_download"
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error retrying audio download for job {job_id}: {e}", exc_info=True)
|
||||
job_manager.fail_job(job_id, f"Audio download retry failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Download retry failed: {e}")
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"job_status": "downloading_audio",
|
||||
"message": f"Job retry started: re-downloading from {job.source_name}",
|
||||
"retry_stage": "audio_download"
|
||||
}
|
||||
|
||||
else:
|
||||
# No input audio available - job needs to be resubmitted
|
||||
@@ -1894,10 +2118,8 @@ async def create_job_from_search(
|
||||
# Lazy imports from audio_search to avoid circular imports at module level
|
||||
from backend.api.routes.audio_search import (
|
||||
_validate_and_prepare_selection,
|
||||
_download_audio_and_trigger_workers,
|
||||
extract_request_metadata,
|
||||
)
|
||||
from backend.services.audio_search_service import get_audio_search_service
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
|
||||
try:
|
||||
@@ -1973,7 +2195,7 @@ async def create_job_from_search(
|
||||
effective_display_artist = body.display_artist or session_artist
|
||||
effective_display_title = body.display_title or session_title
|
||||
|
||||
tenant_id = session.get('tenant_id')
|
||||
tenant_id = session.get('tenant_id') or ""
|
||||
|
||||
request_metadata = extract_request_metadata(request, created_from="guided_flow")
|
||||
|
||||
@@ -2013,6 +2235,11 @@ async def create_job_from_search(
|
||||
|
||||
logger.info(f"Created job {job_id} from search session {body.search_session_id}")
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "guided_search")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
metrics.record_job_created(job_id, source="guided_search")
|
||||
|
||||
# Apply default theme style to job (copy style_params.json to job folder)
|
||||
@@ -2048,14 +2275,12 @@ async def create_job_from_search(
|
||||
selection_index=body.selection_index,
|
||||
)
|
||||
|
||||
# Trigger audio download as a background task
|
||||
audio_search_service = get_audio_search_service()
|
||||
background_tasks.add_task(
|
||||
_download_audio_and_trigger_workers,
|
||||
job_id,
|
||||
body.selection_index,
|
||||
audio_search_service,
|
||||
)
|
||||
# Trigger audio download as a Cloud Run Job (survives instance shutdown)
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_audio_download_worker(job_id)
|
||||
if not triggered:
|
||||
job_manager.fail_job(job_id, "Failed to trigger audio download worker")
|
||||
raise HTTPException(status_code=500, detail="Failed to trigger audio download worker")
|
||||
|
||||
return JobResponse(
|
||||
status="success",
|
||||
@@ -2071,3 +2296,64 @@ async def create_job_from_search(
|
||||
logger.error(f"Error creating job from search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Change Visibility Endpoint
|
||||
# =============================================================================
|
||||
|
||||
@router.post("/{job_id}/change-visibility", response_model=ChangeVisibilityResponse)
|
||||
async def change_visibility(
|
||||
job_id: str,
|
||||
request: ChangeVisibilityRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Change job visibility between public and private.
|
||||
|
||||
Public -> Private (fast, ~1-2 min):
|
||||
- Removes YouTube/GDrive/Dropbox outputs
|
||||
- Redistributes existing files to private destination
|
||||
|
||||
Private -> Public (slow, ~15-30 min):
|
||||
- Resets custom styling to default Nomad theme
|
||||
- Regenerates screens, re-renders video, publishes publicly
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
user_email = auth_result.user_email or "unknown"
|
||||
is_admin = auth_result.is_admin
|
||||
|
||||
from backend.services.visibility_change_service import VisibilityChangeService
|
||||
service = VisibilityChangeService(job_manager)
|
||||
|
||||
# Validate (skip job-exists check since we already handled it)
|
||||
error = service.validate_change(job, user_email, is_admin, request.target_visibility)
|
||||
if error:
|
||||
status_code = 403 if "your own jobs" in error else 400
|
||||
raise HTTPException(status_code=status_code, detail=error)
|
||||
|
||||
current_is_private = getattr(job, 'is_private', False)
|
||||
previous_visibility = "private" if current_is_private else "public"
|
||||
|
||||
try:
|
||||
if request.target_visibility == "private":
|
||||
result = await service.change_to_private(job_id, job, user_email)
|
||||
else:
|
||||
result = await service.change_to_public(job_id, job, user_email)
|
||||
|
||||
return ChangeVisibilityResponse(
|
||||
status=result["status"],
|
||||
job_id=job_id,
|
||||
message=result["message"],
|
||||
previous_visibility=previous_visibility,
|
||||
new_visibility=request.target_visibility,
|
||||
reprocessing_required=result["reprocessing_required"],
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error changing visibility for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Failed to change visibility: {str(e)}")
|
||||
@@ -11,7 +11,7 @@ Provides endpoints for managing Web Push notification subscriptions:
|
||||
import logging
|
||||
from typing import Optional, Dict, List
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.config import get_settings
|
||||
@@ -37,6 +37,7 @@ class SubscribeRequest(BaseModel):
|
||||
endpoint: str
|
||||
keys: Dict[str, str] # p256dh and auth
|
||||
device_name: Optional[str] = None
|
||||
tenant_id: Optional[str] = None # Tenant scope for notification isolation
|
||||
|
||||
|
||||
class SubscribeResponse(BaseModel):
|
||||
@@ -111,7 +112,8 @@ async def get_vapid_public_key():
|
||||
|
||||
@router.post("/subscribe", response_model=SubscribeResponse)
|
||||
async def subscribe_push(
|
||||
request: SubscribeRequest,
|
||||
subscribe_request: SubscribeRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
@@ -119,6 +121,11 @@ async def subscribe_push(
|
||||
|
||||
Requires authentication. Users can have up to 5 subscriptions
|
||||
(configurable via MAX_PUSH_SUBSCRIPTIONS_PER_USER).
|
||||
|
||||
Subscriptions are scoped by tenant_id to prevent cross-tenant
|
||||
notification leakage. The tenant is resolved from:
|
||||
1. Request body tenant_id field (explicit from frontend)
|
||||
2. Tenant middleware (X-Tenant-ID header or subdomain detection)
|
||||
"""
|
||||
settings = get_settings()
|
||||
if not settings.enable_push_notifications:
|
||||
@@ -130,14 +137,20 @@ async def subscribe_push(
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
# Validate keys
|
||||
if "p256dh" not in request.keys or "auth" not in request.keys:
|
||||
if "p256dh" not in subscribe_request.keys or "auth" not in subscribe_request.keys:
|
||||
raise HTTPException(status_code=400, detail="Missing required keys (p256dh, auth)")
|
||||
|
||||
# Resolve tenant_id: prefer explicit from body, fall back to middleware
|
||||
tenant_id = subscribe_request.tenant_id
|
||||
if tenant_id is None:
|
||||
tenant_id = getattr(http_request.state, "tenant_id", None)
|
||||
|
||||
success = await push_service.add_subscription(
|
||||
user_email=auth_result.user_email,
|
||||
endpoint=request.endpoint,
|
||||
keys=request.keys,
|
||||
device_name=request.device_name
|
||||
endpoint=subscribe_request.endpoint,
|
||||
keys=subscribe_request.keys,
|
||||
device_name=subscribe_request.device_name,
|
||||
tenant_id=tenant_id or None,
|
||||
)
|
||||
|
||||
if not success:
|
||||
|
||||
@@ -26,7 +26,9 @@ from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.models.review_session import ReviewSession, ReviewSessionSummary
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.job_logging import job_log_context, JobLogger
|
||||
from backend.services.tracing import create_span, add_span_attribute, add_span_event
|
||||
@@ -63,6 +65,27 @@ def _get_audio_hash(job_id: str) -> str:
|
||||
return hashlib.md5(job_id.encode()).hexdigest()
|
||||
|
||||
|
||||
# Cross-job search endpoint MUST be registered before {job_id} routes
|
||||
# to avoid FastAPI matching "sessions" as a job_id path parameter.
|
||||
@router.get("/sessions/search")
|
||||
async def search_review_sessions(
|
||||
q: str = "",
|
||||
limit: int = 20,
|
||||
auth_info: Tuple[str, str] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Search review sessions across all jobs (admin only).
|
||||
|
||||
Query params:
|
||||
- q: Search text (matches artist, title, or job_id)
|
||||
- limit: Max results (default 20)
|
||||
"""
|
||||
firestore_svc = FirestoreService()
|
||||
results = firestore_svc.search_review_sessions(query_text=q, limit=limit)
|
||||
|
||||
return {"sessions": results}
|
||||
|
||||
|
||||
@router.get("/{job_id}/ping")
|
||||
async def ping(job_id: str):
|
||||
"""Health check endpoint expected by frontend."""
|
||||
@@ -905,3 +928,188 @@ async def get_waveform_data(
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error generating waveform data: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error generating waveform: {str(e)}")
|
||||
|
||||
|
||||
# ============================================
|
||||
# Review Session Endpoints (backup/restore)
|
||||
# ============================================
|
||||
|
||||
|
||||
@router.post("/{job_id}/sessions")
|
||||
async def save_review_session(
|
||||
job_id: str,
|
||||
data: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Save a review session snapshot for backup/restore.
|
||||
|
||||
Stores correction data in GCS and metadata in Firestore subcollection.
|
||||
Skips save if the data is identical to the most recent session (deduplication).
|
||||
|
||||
Request body:
|
||||
- correction_data: Full CorrectionData object
|
||||
- edit_count: Number of edits in this session
|
||||
- trigger: "auto" | "preview" | "manual"
|
||||
- summary: { total_segments, total_words, corrections_made, changed_words[] }
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
firestore_svc = FirestoreService()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
correction_data = data.get("correction_data")
|
||||
if not correction_data:
|
||||
raise HTTPException(status_code=400, detail="correction_data is required")
|
||||
|
||||
# Compute hash for deduplication
|
||||
data_json = json.dumps(correction_data, sort_keys=True, default=str)
|
||||
data_hash = hashlib.sha256(data_json.encode()).hexdigest()
|
||||
|
||||
# Check if identical to most recent session
|
||||
latest_hash = firestore_svc.get_latest_review_session_hash(job_id)
|
||||
if latest_hash == data_hash:
|
||||
logger.info(f"Job {job_id}: Skipping duplicate review session save")
|
||||
return {"status": "skipped", "reason": "identical_data"}
|
||||
|
||||
# Get audio duration from backing_vocals_analysis if available
|
||||
audio_duration = None
|
||||
backing_analysis = job.state_data.get("backing_vocals_analysis", {})
|
||||
if backing_analysis:
|
||||
audio_duration = backing_analysis.get("total_duration_seconds")
|
||||
|
||||
# Build session
|
||||
user_email = auth_info[0] if auth_info else ""
|
||||
summary_data = data.get("summary", {})
|
||||
|
||||
session = ReviewSession(
|
||||
job_id=job_id,
|
||||
user_email=user_email,
|
||||
edit_count=data.get("edit_count", 0),
|
||||
trigger=data.get("trigger", "auto"),
|
||||
audio_duration_seconds=audio_duration,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
summary=ReviewSessionSummary.from_dict(summary_data),
|
||||
data_hash=data_hash,
|
||||
)
|
||||
|
||||
# Upload correction data to GCS
|
||||
gcs_path = f"jobs/{job_id}/review_sessions/{session.session_id}.json"
|
||||
storage.upload_json(gcs_path, correction_data)
|
||||
session.correction_data_gcs_path = gcs_path
|
||||
|
||||
# Save metadata to Firestore
|
||||
firestore_svc.save_review_session(job_id, session)
|
||||
|
||||
logger.info(f"Job {job_id}: Saved review session {session.session_id} (trigger={session.trigger}, edits={session.edit_count})")
|
||||
return {
|
||||
"status": "saved",
|
||||
"session_id": session.session_id,
|
||||
"created_at": session.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{job_id}/sessions")
|
||||
async def list_review_sessions(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
List all review sessions for a job (metadata only, no correction_data).
|
||||
Ordered by updated_at descending (most recent first).
|
||||
"""
|
||||
firestore_svc = FirestoreService()
|
||||
sessions = firestore_svc.list_review_sessions(job_id)
|
||||
|
||||
return {
|
||||
"sessions": [
|
||||
{
|
||||
"session_id": s.session_id,
|
||||
"job_id": s.job_id,
|
||||
"user_email": s.user_email,
|
||||
"created_at": s.created_at.isoformat() if s.created_at else None,
|
||||
"updated_at": s.updated_at.isoformat() if s.updated_at else None,
|
||||
"edit_count": s.edit_count,
|
||||
"trigger": s.trigger,
|
||||
"audio_duration_seconds": s.audio_duration_seconds,
|
||||
"artist": s.artist,
|
||||
"title": s.title,
|
||||
"summary": s.summary.to_dict(),
|
||||
}
|
||||
for s in sessions
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{job_id}/sessions/{session_id}")
|
||||
async def get_review_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Get a single review session with full correction_data loaded from GCS.
|
||||
"""
|
||||
firestore_svc = FirestoreService()
|
||||
storage = StorageService()
|
||||
|
||||
session = firestore_svc.get_review_session(job_id, session_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Review session not found")
|
||||
|
||||
# Load correction data from GCS
|
||||
correction_data = None
|
||||
if session.correction_data_gcs_path:
|
||||
try:
|
||||
correction_data = storage.download_json(session.correction_data_gcs_path)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error loading correction data for session {session_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Error loading session correction data")
|
||||
|
||||
return {
|
||||
"session_id": session.session_id,
|
||||
"job_id": session.job_id,
|
||||
"user_email": session.user_email,
|
||||
"created_at": session.created_at.isoformat() if session.created_at else None,
|
||||
"updated_at": session.updated_at.isoformat() if session.updated_at else None,
|
||||
"edit_count": session.edit_count,
|
||||
"trigger": session.trigger,
|
||||
"audio_duration_seconds": session.audio_duration_seconds,
|
||||
"artist": session.artist,
|
||||
"title": session.title,
|
||||
"summary": session.summary.to_dict(),
|
||||
"correction_data": correction_data,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{job_id}/sessions/{session_id}")
|
||||
async def delete_review_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Delete a review session (metadata + GCS data)."""
|
||||
firestore_svc = FirestoreService()
|
||||
storage = StorageService()
|
||||
|
||||
session = firestore_svc.get_review_session(job_id, session_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Review session not found")
|
||||
|
||||
# Delete GCS data
|
||||
if session.correction_data_gcs_path:
|
||||
try:
|
||||
storage.delete_file(session.correction_data_gcs_path)
|
||||
except Exception:
|
||||
logger.warning(f"Job {job_id}: Could not delete GCS file for session {session_id}")
|
||||
|
||||
# Delete Firestore doc
|
||||
firestore_svc.delete_review_session(job_id, session_id)
|
||||
|
||||
return {"status": "deleted", "session_id": session_id}
|
||||
|
||||
|
||||
+17
-19
@@ -57,6 +57,7 @@ from backend.services.job_defaults_service import (
|
||||
resolve_cdg_txt_defaults,
|
||||
)
|
||||
from backend.api.dependencies import require_admin
|
||||
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
|
||||
from backend.utils.test_data import is_test_email
|
||||
@@ -65,6 +66,7 @@ from backend.services.youtube_download_service import (
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
from backend.exceptions import InvalidStateTransitionError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -577,6 +579,11 @@ async def _handle_made_for_you_order(
|
||||
job = job_manager.create_job(job_create, is_admin=True)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "made_for_you")
|
||||
add_span_attribute("job.is_private", False)
|
||||
|
||||
logger.info(f"Created made-for-you job {job_id} for {_mask_email(customer_email)} (owned by {_mask_email(ADMIN_EMAIL)})")
|
||||
|
||||
# Prepare theme style assets for the job (same as audio_search endpoint)
|
||||
@@ -1370,7 +1377,7 @@ async def get_user_detail(
|
||||
@router.post("/admin/credits", response_model=AddCreditsResponse)
|
||||
async def add_credits_to_user(
|
||||
request: AddCreditsRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
email_service: EmailService = Depends(get_email_service),
|
||||
):
|
||||
@@ -1379,12 +1386,7 @@ async def add_credits_to_user(
|
||||
|
||||
Use this to grant free credits to users, e.g., for beta testers or promotions.
|
||||
"""
|
||||
admin_token, _, _ = auth_data
|
||||
|
||||
# TODO: Enhance auth system to track admin email identity for better audit trails.
|
||||
# Current token-based admin auth doesn't include email identity.
|
||||
# For now, we log the token prefix for traceability.
|
||||
admin_id = f"admin:{admin_token[:8]}..." if admin_token else "admin:unknown"
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success, new_balance, message = user_service.add_credits(
|
||||
email=request.email,
|
||||
@@ -1412,14 +1414,13 @@ async def add_credits_to_user(
|
||||
@router.post("/admin/users/{email}/disable")
|
||||
async def disable_user(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Disable a user account (admin only).
|
||||
"""
|
||||
admin_token, _, _ = auth_data
|
||||
admin_id = f"admin:{admin_token[:8]}..." if admin_token else "admin:unknown"
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success = user_service.disable_user(email, admin_email=admin_id)
|
||||
|
||||
@@ -1432,14 +1433,13 @@ async def disable_user(
|
||||
@router.post("/admin/users/{email}/enable")
|
||||
async def enable_user(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Enable a user account (admin only).
|
||||
"""
|
||||
admin_token, _, _ = auth_data
|
||||
admin_id = f"admin:{admin_token[:8]}..." if admin_token else "admin:unknown"
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success = user_service.enable_user(email, admin_email=admin_id)
|
||||
|
||||
@@ -1452,7 +1452,7 @@ async def enable_user(
|
||||
@router.delete("/admin/users/{email}")
|
||||
async def delete_user(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
@@ -1460,8 +1460,7 @@ async def delete_user(
|
||||
|
||||
Jobs are NOT deleted - they remain as historical records.
|
||||
"""
|
||||
admin_token, _, _ = auth_data
|
||||
admin_id = f"admin:{admin_token[:8]}..." if admin_token else "admin:unknown"
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
try:
|
||||
success = user_service.delete_user(email, admin_email=admin_id)
|
||||
@@ -1478,14 +1477,13 @@ async def delete_user(
|
||||
async def set_user_role(
|
||||
email: str,
|
||||
role: UserRole,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Set a user's role (admin only).
|
||||
"""
|
||||
admin_token, _, _ = auth_data
|
||||
admin_id = f"admin:{admin_token[:8]}..." if admin_token else "admin:unknown"
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success = user_service.set_user_role(email, role, admin_email=admin_id)
|
||||
|
||||
|
||||
+15
-6
@@ -142,13 +142,14 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# Terminal states - COMPLETE, PREP_COMPLETE have no transitions
|
||||
# Terminal states - COMPLETE allows edit (reopen review) and visibility change
|
||||
# FAILED and CANCELLED allow retry transitions to resume from checkpoints
|
||||
# PREP_COMPLETE allows continuation from combined review
|
||||
JobStatus.COMPLETE: [],
|
||||
JobStatus.COMPLETE: [JobStatus.AWAITING_REVIEW, JobStatus.LYRICS_COMPLETE], # Edit track or visibility change
|
||||
JobStatus.PREP_COMPLETE: [JobStatus.AWAITING_REVIEW, JobStatus.FAILED], # Continue from combined review
|
||||
JobStatus.FAILED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
JobStatus.DOWNLOADING_AUDIO, # Retry audio download (audio search flow)
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
@@ -156,6 +157,7 @@ STATE_TRANSITIONS = {
|
||||
],
|
||||
JobStatus.CANCELLED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
JobStatus.DOWNLOADING_AUDIO, # Retry audio download (audio search flow)
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
@@ -177,6 +179,7 @@ class TimelineEvent(BaseModel):
|
||||
timestamp: str
|
||||
progress: Optional[int] = None
|
||||
message: Optional[str] = None
|
||||
metadata: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class LogEntry(BaseModel):
|
||||
@@ -223,8 +226,8 @@ class Job(BaseModel):
|
||||
user_email: Optional[str] = None # Email for notifications
|
||||
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
|
||||
|
||||
# Multi-tenant support (None = default Nomad Karaoke)
|
||||
tenant_id: Optional[str] = None # Tenant ID for white-label portal scoping
|
||||
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
|
||||
tenant_id: str = "" # Tenant ID for white-label portal scoping
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
@@ -303,6 +306,9 @@ class Job(BaseModel):
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
|
||||
|
||||
# Creation-time decision params (for observability — what did the user actually choose?)
|
||||
creation_params: Dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
# Output deletion tracking (for admin cleanup without deleting job)
|
||||
outputs_deleted_at: Optional[datetime] = None # Timestamp when outputs were deleted by admin
|
||||
outputs_deleted_by: Optional[str] = None # Admin email who deleted outputs
|
||||
@@ -310,6 +316,9 @@ class Job(BaseModel):
|
||||
# Credit refund tracking (prevents double-refund on cancel→delete or fail→delete)
|
||||
credit_refunded: bool = False
|
||||
|
||||
# Edit tracking (how many times a completed track has been re-edited)
|
||||
edit_count: int = 0
|
||||
|
||||
# Processing state
|
||||
track_output_dir: Optional[str] = None # Local output directory (temp)
|
||||
audio_hash: Optional[str] = None # Hash for deduplication
|
||||
@@ -528,8 +537,8 @@ class JobCreate(BaseModel):
|
||||
- custom_headers: All X-* headers
|
||||
"""
|
||||
|
||||
# Tenant scoping for white-label portals
|
||||
tenant_id: Optional[str] = None # Tenant ID for job scoping
|
||||
# Tenant scoping for white-label portals ("" = consumer, "vocalstar"/etc = tenant)
|
||||
tenant_id: str = "" # Tenant ID for job scoping
|
||||
|
||||
@validator('url')
|
||||
def validate_url(cls, v):
|
||||
|
||||
@@ -142,3 +142,24 @@ class RetryJobRequest(BaseModel):
|
||||
"""Request to retry a failed job."""
|
||||
from_stage: Optional[str] = None # Optional: restart from specific stage
|
||||
|
||||
|
||||
class ChangeVisibilityRequest(BaseModel):
|
||||
"""Request to change job visibility (public/private)."""
|
||||
target_visibility: str # "public" or "private"
|
||||
|
||||
@validator('target_visibility')
|
||||
def validate_target(cls, v):
|
||||
if v not in ('public', 'private'):
|
||||
raise ValueError("target_visibility must be 'public' or 'private'")
|
||||
return v
|
||||
|
||||
|
||||
class ChangeVisibilityResponse(BaseModel):
|
||||
"""Response from change visibility endpoint."""
|
||||
status: str # "success", "processing", "error"
|
||||
job_id: str
|
||||
message: str
|
||||
previous_visibility: str # "public" or "private"
|
||||
new_visibility: str # "public" or "private"
|
||||
reprocessing_required: bool
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
Review session model for persisting lyrics review progress.
|
||||
|
||||
Stored as a Firestore subcollection: jobs/{job_id}/review_sessions/{session_id}
|
||||
Full correction data is stored in GCS to avoid Firestore's 1MB document limit.
|
||||
"""
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Dict, Any, List
|
||||
import uuid
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReviewSessionSummary:
|
||||
"""Compact summary of edits in a review session, for list views."""
|
||||
total_segments: int = 0
|
||||
total_words: int = 0
|
||||
corrections_made: int = 0
|
||||
changed_words: List[Dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"total_segments": self.total_segments,
|
||||
"total_words": self.total_words,
|
||||
"corrections_made": self.corrections_made,
|
||||
"changed_words": self.changed_words,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "ReviewSessionSummary":
|
||||
return cls(
|
||||
total_segments=data.get("total_segments", 0),
|
||||
total_words=data.get("total_words", 0),
|
||||
corrections_made=data.get("corrections_made", 0),
|
||||
changed_words=data.get("changed_words", []),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReviewSession:
|
||||
"""
|
||||
A saved snapshot of a lyrics review editing session.
|
||||
|
||||
Stored at: jobs/{job_id}/review_sessions/{session_id}
|
||||
Correction data stored at: jobs/{job_id}/review_sessions/{session_id}.json (GCS)
|
||||
"""
|
||||
session_id: str = field(default_factory=lambda: str(uuid.uuid4()))
|
||||
job_id: str = ""
|
||||
user_email: str = ""
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
edit_count: int = 0
|
||||
trigger: str = "auto" # "auto" | "preview" | "manual"
|
||||
audio_duration_seconds: Optional[float] = None
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
summary: ReviewSessionSummary = field(default_factory=ReviewSessionSummary)
|
||||
correction_data_gcs_path: str = ""
|
||||
|
||||
# Hash of the correction data JSON, used to skip duplicate saves
|
||||
data_hash: str = ""
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"session_id": self.session_id,
|
||||
"job_id": self.job_id,
|
||||
"user_email": self.user_email,
|
||||
"created_at": self.created_at,
|
||||
"updated_at": self.updated_at,
|
||||
"edit_count": self.edit_count,
|
||||
"trigger": self.trigger,
|
||||
"audio_duration_seconds": self.audio_duration_seconds,
|
||||
"artist": self.artist,
|
||||
"title": self.title,
|
||||
"summary": self.summary.to_dict(),
|
||||
"correction_data_gcs_path": self.correction_data_gcs_path,
|
||||
"data_hash": self.data_hash,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "ReviewSession":
|
||||
created_at = data.get("created_at")
|
||||
if isinstance(created_at, str):
|
||||
created_at = datetime.fromisoformat(created_at.rstrip("Z")).replace(tzinfo=timezone.utc)
|
||||
|
||||
updated_at = data.get("updated_at")
|
||||
if isinstance(updated_at, str):
|
||||
updated_at = datetime.fromisoformat(updated_at.rstrip("Z")).replace(tzinfo=timezone.utc)
|
||||
|
||||
summary_data = data.get("summary", {})
|
||||
summary = ReviewSessionSummary.from_dict(summary_data) if isinstance(summary_data, dict) else ReviewSessionSummary()
|
||||
|
||||
return cls(
|
||||
session_id=data.get("session_id", str(uuid.uuid4())),
|
||||
job_id=data.get("job_id", ""),
|
||||
user_email=data.get("user_email", ""),
|
||||
created_at=created_at or datetime.now(timezone.utc),
|
||||
updated_at=updated_at or datetime.now(timezone.utc),
|
||||
edit_count=data.get("edit_count", 0),
|
||||
trigger=data.get("trigger", "auto"),
|
||||
audio_duration_seconds=data.get("audio_duration_seconds"),
|
||||
artist=data.get("artist"),
|
||||
title=data.get("title"),
|
||||
summary=summary,
|
||||
correction_data_gcs_path=data.get("correction_data_gcs_path", ""),
|
||||
data_hash=data.get("data_hash", ""),
|
||||
)
|
||||
@@ -95,6 +95,12 @@ class TenantDefaults(BaseModel):
|
||||
brand_prefix: Optional[str] = Field(
|
||||
None, description="Prefix for output filenames (e.g., 'VSTAR')"
|
||||
)
|
||||
dropbox_path: Optional[str] = Field(
|
||||
None, description="Tenant-specific Dropbox folder path (e.g., '/Karaoke/Vocal-Star')"
|
||||
)
|
||||
gdrive_folder_id: Optional[str] = Field(
|
||||
None, description="Tenant-specific Google Drive folder ID for output uploads"
|
||||
)
|
||||
youtube_description_template: Optional[str] = Field(
|
||||
None, description="Default YouTube description template"
|
||||
)
|
||||
|
||||
@@ -36,10 +36,15 @@ class PushSubscription(BaseModel):
|
||||
|
||||
Stores the push subscription endpoint and encryption keys needed
|
||||
to send push notifications to the user's browser/device.
|
||||
|
||||
Subscriptions are scoped by tenant_id to prevent cross-tenant
|
||||
notification leakage (e.g., a consumer job notification appearing
|
||||
on a tenant portal's service worker).
|
||||
"""
|
||||
endpoint: str # Push service endpoint URL
|
||||
keys: Dict[str, str] # p256dh and auth keys for encryption
|
||||
device_name: Optional[str] = None # e.g., "iPhone", "Chrome on Windows"
|
||||
tenant_id: Optional[str] = None # Tenant scope (None = consumer/default portal)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_used_at: Optional[datetime] = None # Last time a notification was sent
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from google.cloud.firestore_v1 import FieldFilter
|
||||
from backend.config import settings
|
||||
from backend.models.job import Job, JobStatus, TimelineEvent
|
||||
from backend.models.worker_log import WorkerLogEntry
|
||||
from backend.models.review_session import ReviewSession
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -75,18 +76,20 @@ class FirestoreService:
|
||||
status: JobStatus,
|
||||
progress: Optional[int] = None,
|
||||
message: Optional[str] = None,
|
||||
timeline_metadata: Optional[Dict[str, Any]] = None,
|
||||
**additional_fields
|
||||
) -> None:
|
||||
"""Update job status and add timeline event."""
|
||||
try:
|
||||
doc_ref = self.db.collection(self.collection).document(job_id)
|
||||
|
||||
|
||||
# Create timeline event
|
||||
timeline_event = TimelineEvent(
|
||||
status=status.value,
|
||||
timestamp=datetime.utcnow().isoformat(),
|
||||
progress=progress,
|
||||
message=message
|
||||
message=message,
|
||||
metadata=timeline_metadata,
|
||||
)
|
||||
|
||||
# Prepare updates
|
||||
@@ -153,7 +156,8 @@ class FirestoreService:
|
||||
query = query.where(filter=FieldFilter('user_email', '==', user_email.lower()))
|
||||
|
||||
# Filter by tenant_id (white-label portal scoping)
|
||||
if tenant_id:
|
||||
# Always filter: "" for consumer jobs, "vocalstar"/etc for tenant jobs
|
||||
if tenant_id is not None:
|
||||
query = query.where(filter=FieldFilter('tenant_id', '==', tenant_id))
|
||||
|
||||
# Date range filters
|
||||
@@ -176,11 +180,11 @@ class FirestoreService:
|
||||
# Fields needed by the dashboard summary view
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
|
||||
'state_data.audio_progress', 'state_data.lyrics_progress',
|
||||
'state_data.audio_complete', 'state_data.lyrics_complete',
|
||||
'state_data.backing_vocals_analysis',
|
||||
'state_data.backing_vocals_analysis', 'state_data.visibility_change_in_progress',
|
||||
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
|
||||
]
|
||||
|
||||
@@ -225,7 +229,8 @@ class FirestoreService:
|
||||
if user_email:
|
||||
query = query.where(filter=FieldFilter('user_email', '==', user_email.lower()))
|
||||
|
||||
if tenant_id:
|
||||
# Always filter: "" for consumer jobs, "vocalstar"/etc for tenant jobs
|
||||
if tenant_id is not None:
|
||||
query = query.where(filter=FieldFilter('tenant_id', '==', tenant_id))
|
||||
|
||||
if created_after:
|
||||
@@ -671,6 +676,217 @@ class FirestoreService:
|
||||
transaction = self.db.transaction()
|
||||
return _read_and_delete(transaction, doc_ref)
|
||||
|
||||
# ============================================
|
||||
# Review Session Subcollection Methods
|
||||
# ============================================
|
||||
# These methods store review session snapshots in a subcollection
|
||||
# (jobs/{job_id}/review_sessions) for lyrics review backup/restore.
|
||||
|
||||
def save_review_session(self, job_id: str, session: ReviewSession) -> str:
|
||||
"""
|
||||
Save a review session to the subcollection.
|
||||
|
||||
Stores at: jobs/{job_id}/review_sessions/{session_id}
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
session: ReviewSession instance
|
||||
|
||||
Returns:
|
||||
session_id
|
||||
"""
|
||||
try:
|
||||
session.job_id = job_id
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
|
||||
doc_ref = sessions_ref.document(session.session_id)
|
||||
doc_ref.set(session.to_dict())
|
||||
logger.info(f"Saved review session {session.session_id} for job {job_id}")
|
||||
return session.session_id
|
||||
except Exception as e:
|
||||
logger.error(f"Error saving review session for job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
def list_review_sessions(self, job_id: str) -> List[ReviewSession]:
|
||||
"""
|
||||
List all review sessions for a job, ordered by updated_at descending.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
|
||||
Returns:
|
||||
List of ReviewSession instances (metadata only, no correction_data)
|
||||
"""
|
||||
try:
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING)
|
||||
docs = query.stream()
|
||||
return [ReviewSession.from_dict(doc.to_dict()) for doc in docs]
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing review sessions for job {job_id}: {e}")
|
||||
return []
|
||||
|
||||
def get_review_session(self, job_id: str, session_id: str) -> Optional[ReviewSession]:
|
||||
"""
|
||||
Get a single review session by ID.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
session_id: Session ID
|
||||
|
||||
Returns:
|
||||
ReviewSession or None
|
||||
"""
|
||||
try:
|
||||
doc_ref = (
|
||||
self.db.collection(self.collection)
|
||||
.document(job_id)
|
||||
.collection("review_sessions")
|
||||
.document(session_id)
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
return ReviewSession.from_dict(doc.to_dict())
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting review session {session_id} for job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
def delete_review_session(self, job_id: str, session_id: str) -> None:
|
||||
"""
|
||||
Delete a review session.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
session_id: Session ID
|
||||
"""
|
||||
try:
|
||||
doc_ref = (
|
||||
self.db.collection(self.collection)
|
||||
.document(job_id)
|
||||
.collection("review_sessions")
|
||||
.document(session_id)
|
||||
)
|
||||
doc_ref.delete()
|
||||
logger.info(f"Deleted review session {session_id} for job {job_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting review session {session_id} for job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
def delete_review_sessions_subcollection(self, job_id: str, batch_size: int = 500) -> int:
|
||||
"""
|
||||
Delete all review sessions for a job (used when deleting a job).
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
batch_size: Number of documents to delete per batch
|
||||
|
||||
Returns:
|
||||
Number of sessions deleted
|
||||
"""
|
||||
try:
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
|
||||
deleted_count = 0
|
||||
|
||||
while True:
|
||||
docs = sessions_ref.limit(batch_size).stream()
|
||||
deleted_in_batch = 0
|
||||
|
||||
batch = self.db.batch()
|
||||
for doc in docs:
|
||||
batch.delete(doc.reference)
|
||||
deleted_in_batch += 1
|
||||
|
||||
if deleted_in_batch == 0:
|
||||
break
|
||||
|
||||
batch.commit()
|
||||
deleted_count += deleted_in_batch
|
||||
|
||||
if deleted_in_batch < batch_size:
|
||||
break
|
||||
|
||||
if deleted_count > 0:
|
||||
logger.info(f"Deleted {deleted_count} review sessions for job {job_id}")
|
||||
|
||||
return deleted_count
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting review sessions subcollection for job {job_id}: {e}")
|
||||
return 0
|
||||
|
||||
def get_latest_review_session_hash(self, job_id: str) -> Optional[str]:
|
||||
"""
|
||||
Get the data_hash of the most recent review session for deduplication.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
|
||||
Returns:
|
||||
data_hash string or None if no sessions exist
|
||||
"""
|
||||
try:
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
|
||||
query = (
|
||||
sessions_ref
|
||||
.order_by("updated_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(1)
|
||||
.select(["data_hash"])
|
||||
)
|
||||
docs = list(query.stream())
|
||||
if docs:
|
||||
return docs[0].to_dict().get("data_hash", "")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting latest review session hash for job {job_id}: {e}")
|
||||
return None
|
||||
|
||||
def search_review_sessions(
|
||||
self,
|
||||
query_text: str = "",
|
||||
job_id: Optional[str] = None,
|
||||
limit: int = 20,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Search review sessions across all jobs using collection group query.
|
||||
|
||||
Args:
|
||||
query_text: Search text (prefix-matched against artist_lower or title_lower)
|
||||
job_id: If provided, search only within this job
|
||||
limit: Maximum results
|
||||
|
||||
Returns:
|
||||
List of session dicts with job context
|
||||
"""
|
||||
try:
|
||||
if job_id:
|
||||
# Search within a specific job
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
|
||||
docs = query.stream()
|
||||
return [doc.to_dict() for doc in docs]
|
||||
|
||||
# Collection group query across all jobs
|
||||
sessions_ref = self.db.collection_group("review_sessions")
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
|
||||
docs = query.stream()
|
||||
results = [doc.to_dict() for doc in docs]
|
||||
|
||||
# Filter in Python for text search (Firestore doesn't support LIKE)
|
||||
if query_text:
|
||||
q_lower = query_text.lower()
|
||||
results = [
|
||||
r for r in results
|
||||
if q_lower in (r.get("artist") or "").lower()
|
||||
or q_lower in (r.get("title") or "").lower()
|
||||
or q_lower in (r.get("job_id") or "").lower()
|
||||
]
|
||||
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error searching review sessions: {e}")
|
||||
return []
|
||||
|
||||
def delete_search_session(self, session_id: str) -> None:
|
||||
"""Delete a search session after it has been consumed by job creation.
|
||||
|
||||
@@ -708,3 +924,35 @@ def get_firestore_client() -> firestore.Client:
|
||||
_firestore_client = firestore.Client(project=settings.google_cloud_project)
|
||||
return _firestore_client
|
||||
|
||||
|
||||
_log_service: Optional["FirestoreService"] = None
|
||||
|
||||
|
||||
def _get_log_service() -> "FirestoreService":
|
||||
"""Return a cached FirestoreService instance for log_to_job."""
|
||||
global _log_service
|
||||
if _log_service is None:
|
||||
_log_service = FirestoreService()
|
||||
return _log_service
|
||||
|
||||
|
||||
def log_to_job(job_id: str, worker: str, level: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> None:
|
||||
"""
|
||||
Write a log entry to a job's Firestore log subcollection.
|
||||
|
||||
This is a convenience function for API endpoints that need to log
|
||||
to a job's log history (workers already have JobLogAdapter for this).
|
||||
|
||||
Args:
|
||||
job_id: Job ID to log to
|
||||
worker: Worker/source name (e.g., "api", "edit", "admin")
|
||||
level: Log level (INFO, WARNING, ERROR)
|
||||
message: Log message
|
||||
metadata: Optional structured metadata dict
|
||||
"""
|
||||
try:
|
||||
entry = WorkerLogEntry.create(job_id, worker, level, message, metadata)
|
||||
_get_log_service().append_log_to_subcollection(job_id, entry)
|
||||
except Exception as e:
|
||||
logger.debug(f"Failed to write job log for {job_id}: {e}")
|
||||
|
||||
@@ -664,6 +664,49 @@ class FlacfetchClient:
|
||||
f"Clear all cache failed: {e.response.status_code} - {e.response.text}"
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# YouTube Availability Check
|
||||
# =========================================================================
|
||||
|
||||
async def check_youtube(self, url: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Check if a YouTube video is available for download from this server's location.
|
||||
|
||||
Calls the flacfetch /check-youtube endpoint which uses yt-dlp to detect
|
||||
geo-restrictions, private/removed videos, and other unavailability reasons.
|
||||
|
||||
Args:
|
||||
url: YouTube video URL or video ID
|
||||
|
||||
Returns:
|
||||
Dict with keys: available, video_id, title, error,
|
||||
is_geo_restricted, is_age_restricted, is_private, is_removed
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On request failure
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/check-youtube",
|
||||
headers=self._headers(),
|
||||
json={"url": url},
|
||||
timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"YouTube availability check failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"YouTube availability check failed: {e.response.status_code} - {e.response.text}"
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Cache Management
|
||||
# =========================================================================
|
||||
|
||||
async def get_cache_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Get statistics about the cache.
|
||||
|
||||
@@ -370,10 +370,20 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
|
||||
# Instrumental audio - respect user's selection from encoding config
|
||||
instrumental_selection = config.get("instrumental_selection", "clean")
|
||||
existing_instrumental = config.get("existing_instrumental")
|
||||
logger.info(f"Instrumental selection from config: {instrumental_selection}")
|
||||
if existing_instrumental:
|
||||
logger.info(f"Existing instrumental from config: {existing_instrumental}")
|
||||
|
||||
if instrumental_selection == "custom":
|
||||
# User uploaded a custom instrumental or created one via mute-region editing
|
||||
if existing_instrumental:
|
||||
# User-provided instrumental uploaded at job creation
|
||||
# Downloaded to work_dir by process_job before run_encoding is called
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*existing_instrumental*", "*Instrumental User*",
|
||||
)
|
||||
elif instrumental_selection == "custom":
|
||||
# Custom instrumental created via mute-region editing in review UI
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*custom_instrumental*.flac", "*Instrumental Custom*.flac",
|
||||
@@ -492,6 +502,17 @@ async def process_job(job_id: str, request: EncodeRequest):
|
||||
logger.info(f"Downloading from {request.input_gcs_path}")
|
||||
download_from_gcs(request.input_gcs_path, work_dir)
|
||||
|
||||
# Download existing instrumental if present (stored under uploads/, not jobs/)
|
||||
existing_instrumental = request.encoding_config.get("existing_instrumental") if request.encoding_config else None
|
||||
if existing_instrumental:
|
||||
# Extract bucket name from input_gcs_path (gs://bucket/jobs/...)
|
||||
bucket_name = request.input_gcs_path.replace("gs://", "").split("/", 1)[0]
|
||||
ext = Path(existing_instrumental).suffix.lower()
|
||||
dest = work_dir / f"existing_instrumental{ext}"
|
||||
gcs_uri = f"gs://{bucket_name}/{existing_instrumental}"
|
||||
logger.info(f"Downloading existing instrumental: {gcs_uri} -> {dest}")
|
||||
download_single_file_from_gcs(gcs_uri, dest)
|
||||
|
||||
# Run encoding in thread pool (CPU-bound)
|
||||
loop = asyncio.get_event_loop()
|
||||
output_dir = await loop.run_in_executor(
|
||||
|
||||
@@ -80,6 +80,17 @@ def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings:
|
||||
EffectiveDistributionSettings with private overrides applied if needed
|
||||
"""
|
||||
if getattr(job, 'is_private', False):
|
||||
# Tenant jobs: use the job's own distribution fields (set at creation from tenant config)
|
||||
# Non-tenant private jobs: override to NonPublished paths
|
||||
if getattr(job, 'tenant_id', None):
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=getattr(job, 'dropbox_path', None),
|
||||
brand_prefix=getattr(job, 'brand_prefix', None),
|
||||
enable_youtube_upload=False,
|
||||
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=None,
|
||||
)
|
||||
settings = get_settings()
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=settings.default_private_dropbox_path,
|
||||
|
||||
@@ -120,6 +120,21 @@ def check_job_consistency(job: Job) -> List[str]:
|
||||
f"encoding_stuck: status=encoding for {minutes} min without update (updated_at={updated_at.isoformat()})"
|
||||
)
|
||||
|
||||
# Check: job stuck in downloading_audio status beyond 10 minutes
|
||||
# Audio downloads typically complete in 30s-5min. If stuck longer,
|
||||
# the Cloud Run Job likely failed silently.
|
||||
if status == JobStatus.DOWNLOADING_AUDIO and job.updated_at:
|
||||
now = datetime.now(timezone.utc)
|
||||
updated_at = job.updated_at
|
||||
if updated_at.tzinfo is None:
|
||||
updated_at = updated_at.replace(tzinfo=timezone.utc)
|
||||
download_age = now - updated_at
|
||||
if download_age > timedelta(minutes=10):
|
||||
minutes = int(download_age.total_seconds() / 60)
|
||||
issues.append(
|
||||
f"downloading_audio_stuck: status=downloading_audio for {minutes} min without update (updated_at={updated_at.isoformat()})"
|
||||
)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
|
||||
@@ -120,8 +120,14 @@ class JobManager:
|
||||
customer_notes=job_create.customer_notes,
|
||||
# Private (non-published) track mode
|
||||
is_private=job_create.is_private,
|
||||
# Capture creation-time decision params for observability
|
||||
creation_params={
|
||||
"is_private": job_create.is_private,
|
||||
"is_admin": is_admin,
|
||||
"created_from": job_create.request_metadata.get("created_from", "unknown"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
self.firestore.create_job(job)
|
||||
logger.info(f"Created new job {job_id} with status PENDING")
|
||||
|
||||
@@ -407,7 +413,8 @@ class JobManager:
|
||||
progress: Optional[int] = None,
|
||||
message: Optional[str] = None,
|
||||
state_data_updates: Optional[Dict[str, Any]] = None,
|
||||
raise_on_invalid: bool = True
|
||||
raise_on_invalid: bool = True,
|
||||
timeline_metadata: Optional[Dict[str, Any]] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Transition job to new state with validation.
|
||||
@@ -420,6 +427,7 @@ class JobManager:
|
||||
state_data_updates: Updates to state_data field
|
||||
raise_on_invalid: If True (default), raise InvalidStateTransitionError
|
||||
on invalid transitions. If False, return False silently.
|
||||
timeline_metadata: Optional structured metadata to attach to the timeline event
|
||||
|
||||
Returns:
|
||||
True if transition succeeded, False if failed (only when raise_on_invalid=False)
|
||||
@@ -429,15 +437,15 @@ class JobManager:
|
||||
"""
|
||||
if not self.validate_state_transition(job_id, new_status, raise_on_invalid=raise_on_invalid):
|
||||
return False
|
||||
|
||||
|
||||
updates = {
|
||||
'status': new_status,
|
||||
'updated_at': datetime.utcnow()
|
||||
}
|
||||
|
||||
|
||||
if progress is not None:
|
||||
updates['progress'] = progress
|
||||
|
||||
|
||||
# Generate review token when entering AWAITING_REVIEW state
|
||||
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
|
||||
if new_status == JobStatus.AWAITING_REVIEW:
|
||||
@@ -446,14 +454,14 @@ class JobManager:
|
||||
updates['review_token'] = review_token
|
||||
updates['review_token_expires_at'] = None # No expiry - token is job-scoped
|
||||
logger.info(f"Generated review token for job {job_id} (no expiry)")
|
||||
|
||||
|
||||
# If we have state_data_updates, merge them with existing state_data
|
||||
merged_state_data = None
|
||||
if state_data_updates:
|
||||
job = self.get_job(job_id)
|
||||
if job:
|
||||
merged_state_data = {**job.state_data, **state_data_updates}
|
||||
|
||||
|
||||
# Update job status (includes timeline event), passing state_data if present
|
||||
if merged_state_data is not None:
|
||||
self.update_job_status(
|
||||
@@ -461,6 +469,7 @@ class JobManager:
|
||||
status=new_status,
|
||||
progress=progress,
|
||||
message=message,
|
||||
timeline_metadata=timeline_metadata,
|
||||
state_data=merged_state_data
|
||||
)
|
||||
else:
|
||||
@@ -468,7 +477,8 @@ class JobManager:
|
||||
job_id=job_id,
|
||||
status=new_status,
|
||||
progress=progress,
|
||||
message=message
|
||||
message=message,
|
||||
timeline_metadata=timeline_metadata,
|
||||
)
|
||||
|
||||
# Apply review token update separately if generated
|
||||
@@ -678,6 +688,7 @@ class JobManager:
|
||||
"user_email": job.user_email,
|
||||
"artist": job.artist,
|
||||
"title": job.title,
|
||||
"tenant_id": job.tenant_id or None,
|
||||
}
|
||||
|
||||
async def send_notification():
|
||||
@@ -947,14 +958,24 @@ class JobManager:
|
||||
message=message
|
||||
)
|
||||
|
||||
# Trigger both workers in parallel
|
||||
# Check if audio separation can be skipped
|
||||
# Jobs with an existing instrumental (e.g. tenant uploads) don't need
|
||||
# GPU-powered audio separation — saves 5-10 minutes of processing time
|
||||
worker_service = get_worker_service()
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
logger.info(f"Job {job_id}: Started processing (audio + lyrics workers triggered)")
|
||||
if job.existing_instrumental_gcs_path:
|
||||
logger.info(f"Job {job_id}: Skipping audio separation (existing instrumental provided)")
|
||||
# Mark audio as immediately complete and only trigger lyrics worker
|
||||
self.update_state_data(job_id, 'audio_complete', True)
|
||||
await worker_service.trigger_lyrics_worker(job_id)
|
||||
logger.info(f"Job {job_id}: Started processing (lyrics worker only, audio separation skipped)")
|
||||
else:
|
||||
# Trigger both workers in parallel
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
logger.info(f"Job {job_id}: Started processing (audio + lyrics workers triggered)")
|
||||
|
||||
def mark_audio_complete(self, job_id: str) -> None:
|
||||
"""
|
||||
|
||||
@@ -85,10 +85,14 @@ class PushNotificationService:
|
||||
title: str,
|
||||
body: str,
|
||||
url: str = "/app/",
|
||||
tag: Optional[str] = None
|
||||
tag: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
) -> int:
|
||||
"""
|
||||
Send a push notification to all of a user's subscribed devices.
|
||||
Send a push notification to a user's subscribed devices for a specific tenant.
|
||||
|
||||
Only sends to subscriptions matching the given tenant_id to prevent
|
||||
cross-tenant notification leakage.
|
||||
|
||||
Args:
|
||||
user_email: The user's email address
|
||||
@@ -96,6 +100,8 @@ class PushNotificationService:
|
||||
body: Notification body text
|
||||
url: URL to open when notification is clicked
|
||||
tag: Optional tag for notification grouping (replaces notifications with same tag)
|
||||
tenant_id: Tenant scope - only send to subscriptions for this tenant
|
||||
(None or "" = consumer/default portal)
|
||||
|
||||
Returns:
|
||||
Number of notifications successfully sent
|
||||
@@ -111,7 +117,30 @@ class PushNotificationService:
|
||||
return 0
|
||||
|
||||
user_data = user_doc.to_dict()
|
||||
subscriptions = user_data.get("push_subscriptions", [])
|
||||
all_subscriptions = user_data.get("push_subscriptions", [])
|
||||
|
||||
# Filter subscriptions to only those matching the target tenant
|
||||
# Normalize: None and "" both mean "consumer/default portal"
|
||||
target_tenant = tenant_id or None
|
||||
subscriptions = [
|
||||
sub for sub in all_subscriptions
|
||||
if (sub.get("tenant_id") or None) == target_tenant
|
||||
]
|
||||
|
||||
if not subscriptions and all_subscriptions:
|
||||
# Migration path: if no subscriptions match and none have tenant_id set,
|
||||
# it means they're legacy subscriptions created before tenant scoping.
|
||||
# Send to legacy subscriptions (those without tenant_id) only if
|
||||
# the target is the consumer portal (no tenant).
|
||||
has_any_tenant_scoped = any(sub.get("tenant_id") for sub in all_subscriptions)
|
||||
if not has_any_tenant_scoped and target_tenant is None:
|
||||
subscriptions = all_subscriptions
|
||||
logger.debug(f"Using legacy unscoped subscriptions for {user_email}")
|
||||
else:
|
||||
logger.debug(
|
||||
f"No matching subscriptions for tenant={target_tenant} "
|
||||
f"(user has {len(all_subscriptions)} total subscriptions)"
|
||||
)
|
||||
|
||||
if not subscriptions:
|
||||
logger.debug(f"User {user_email} has no push subscriptions")
|
||||
@@ -196,7 +225,7 @@ class PushNotificationService:
|
||||
Send notification when a job enters a blocking state requiring user action.
|
||||
|
||||
Args:
|
||||
job: Job dictionary with job_id, user_email, artist, title
|
||||
job: Job dictionary with job_id, user_email, artist, title, tenant_id
|
||||
action_type: Type of action needed ("lyrics" or "instrumental")
|
||||
|
||||
Returns:
|
||||
@@ -209,16 +238,17 @@ class PushNotificationService:
|
||||
job_id = job.get("job_id", "unknown")
|
||||
artist = job.get("artist", "Unknown Artist")
|
||||
title = job.get("title", "Unknown Title")
|
||||
tenant_id = job.get("tenant_id") or None
|
||||
|
||||
if action_type == "lyrics":
|
||||
notif_title = "Review Lyrics"
|
||||
notif_body = f'"{title}" by {artist} needs lyrics review'
|
||||
url = f"/review/{job_id}"
|
||||
url = f"/app/jobs#/{job_id}/review"
|
||||
tag = f"lyrics-{job_id}"
|
||||
else: # instrumental
|
||||
notif_title = "Select Instrumental"
|
||||
notif_body = f'"{title}" by {artist} needs instrumental selection'
|
||||
url = f"/instrumental/{job_id}"
|
||||
url = f"/app/jobs#/{job_id}/instrumental"
|
||||
tag = f"instrumental-{job_id}"
|
||||
|
||||
return await self.send_push(
|
||||
@@ -226,7 +256,8 @@ class PushNotificationService:
|
||||
title=notif_title,
|
||||
body=notif_body,
|
||||
url=url,
|
||||
tag=tag
|
||||
tag=tag,
|
||||
tenant_id=tenant_id,
|
||||
)
|
||||
|
||||
async def send_completion_notification(self, job: dict) -> int:
|
||||
@@ -234,7 +265,7 @@ class PushNotificationService:
|
||||
Send notification when a job completes successfully.
|
||||
|
||||
Args:
|
||||
job: Job dictionary with job_id, user_email, artist, title
|
||||
job: Job dictionary with job_id, user_email, artist, title, tenant_id
|
||||
|
||||
Returns:
|
||||
Number of notifications sent
|
||||
@@ -246,13 +277,15 @@ class PushNotificationService:
|
||||
job_id = job.get("job_id", "unknown")
|
||||
artist = job.get("artist", "Unknown Artist")
|
||||
title = job.get("title", "Unknown Title")
|
||||
tenant_id = job.get("tenant_id") or None
|
||||
|
||||
return await self.send_push(
|
||||
user_email=user_email,
|
||||
title="Video Ready!",
|
||||
body=f'Your karaoke video for "{title}" by {artist} is ready to download',
|
||||
url=f"/app/?job={job_id}",
|
||||
tag=f"complete-{job_id}"
|
||||
tag=f"complete-{job_id}",
|
||||
tenant_id=tenant_id,
|
||||
)
|
||||
|
||||
async def add_subscription(
|
||||
@@ -260,10 +293,11 @@ class PushNotificationService:
|
||||
user_email: str,
|
||||
endpoint: str,
|
||||
keys: dict,
|
||||
device_name: Optional[str] = None
|
||||
device_name: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Add a push subscription for a user.
|
||||
Add a push subscription for a user, scoped to a tenant.
|
||||
|
||||
Enforces max subscriptions per user - oldest removed if limit exceeded.
|
||||
|
||||
@@ -272,6 +306,7 @@ class PushNotificationService:
|
||||
endpoint: Push service endpoint URL
|
||||
keys: Encryption keys (p256dh, auth)
|
||||
device_name: Optional device identifier
|
||||
tenant_id: Tenant scope (None = consumer/default portal)
|
||||
|
||||
Returns:
|
||||
True if subscription was added successfully
|
||||
@@ -298,6 +333,7 @@ class PushNotificationService:
|
||||
"endpoint": endpoint,
|
||||
"keys": keys,
|
||||
"device_name": device_name,
|
||||
"tenant_id": tenant_id or None,
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"last_used_at": None
|
||||
}
|
||||
|
||||
@@ -449,16 +449,27 @@ class StripeAdminService:
|
||||
"""Get all payments for a user with total_spent."""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
query = (
|
||||
collection.where("customer_email", "==", email.lower())
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
)
|
||||
# Try with order_by first (requires composite index on customer_email + created_at)
|
||||
try:
|
||||
query = (
|
||||
collection.where("customer_email", "==", email.lower())
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
)
|
||||
docs = list(query.stream())
|
||||
except Exception:
|
||||
# Fallback: query without order_by if composite index doesn't exist yet
|
||||
logger.warning(
|
||||
f"Composite index missing for stripe_payments(customer_email, created_at). "
|
||||
f"Falling back to unordered query for {email}"
|
||||
)
|
||||
query = collection.where("customer_email", "==", email.lower())
|
||||
docs = list(query.stream())
|
||||
|
||||
payments = []
|
||||
total_spent = 0
|
||||
total_refunded = 0
|
||||
|
||||
for doc in query.stream():
|
||||
for doc in docs:
|
||||
data = doc.to_dict()
|
||||
data["session_id"] = doc.id
|
||||
total_spent += data.get("amount_total", 0)
|
||||
@@ -470,6 +481,9 @@ class StripeAdminService:
|
||||
|
||||
payments.append(data)
|
||||
|
||||
# Sort by created_at descending (handles both indexed and fallback paths)
|
||||
payments.sort(key=lambda p: p.get("created_at", ""), reverse=True)
|
||||
|
||||
first_payment = payments[-1]["created_at"] if payments else None
|
||||
last_payment = payments[0]["created_at"] if payments else None
|
||||
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
"""
|
||||
Visibility change service for completed jobs.
|
||||
|
||||
Handles changing a job's visibility between public and private:
|
||||
- Public -> Private: redistribute existing finals to private destination (fast, ~1-2 min)
|
||||
- Private -> Public: reset styles, regenerate screens, re-render, re-encode (slow, ~15-30 min)
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class VisibilityChangeService:
|
||||
"""Service for changing job visibility after completion."""
|
||||
|
||||
def __init__(self, job_manager: Optional[JobManager] = None):
|
||||
self.job_manager = job_manager or JobManager()
|
||||
|
||||
def validate_change(self, job, user_email: str, is_admin: bool, target_visibility: str) -> Optional[str]:
|
||||
"""Validate a visibility change request. Returns error message or None if valid."""
|
||||
if not job:
|
||||
return "Job not found"
|
||||
|
||||
if job.status != JobStatus.COMPLETE.value and job.status != "complete":
|
||||
return f"Can only change visibility on completed jobs. Current status: {job.status}"
|
||||
|
||||
if getattr(job, 'tenant_id', None):
|
||||
return "Cannot change visibility on tenant jobs"
|
||||
|
||||
current_is_private = getattr(job, 'is_private', False)
|
||||
target_is_private = target_visibility == "private"
|
||||
|
||||
if current_is_private == target_is_private:
|
||||
current = "private" if current_is_private else "public"
|
||||
return f"Job is already {current}"
|
||||
|
||||
# Check user owns the job or is admin
|
||||
if not is_admin and job.user_email != user_email:
|
||||
return "You can only change visibility on your own jobs"
|
||||
|
||||
# Check for in-progress visibility change
|
||||
state_data = job.state_data or {}
|
||||
if state_data.get('visibility_change_in_progress'):
|
||||
return "A visibility change is already in progress for this job"
|
||||
|
||||
return None
|
||||
|
||||
async def change_to_private(self, job_id: str, job, user_email: str) -> dict:
|
||||
"""
|
||||
Change a public job to private (fast path).
|
||||
|
||||
Deletes distributed outputs (YouTube/Dropbox/GDrive) but keeps GCS finals,
|
||||
then redistributes to private destination.
|
||||
"""
|
||||
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
|
||||
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
|
||||
# Set guard flag
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": True,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
try:
|
||||
# Step 1: Delete distributed outputs (keep GCS finals)
|
||||
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=True)
|
||||
|
||||
# Step 2: Update job to private
|
||||
job_ref.update({
|
||||
"is_private": True,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "complete",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Visibility changed to private by {user_email}",
|
||||
}]),
|
||||
})
|
||||
|
||||
# Step 3: Trigger redistribution via video worker
|
||||
from backend.workers.video_worker import redistribute_video
|
||||
success = await redistribute_video(job_id)
|
||||
|
||||
if not success:
|
||||
raise RuntimeError("Redistribution failed - check worker logs")
|
||||
|
||||
# Clear guard flag (redistribution updates state_data with new brand_code etc.)
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
})
|
||||
|
||||
logger.info(f"[job:{job_id}] Visibility change to private complete")
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Job changed to private. Outputs redistributed to private destination.",
|
||||
"reprocessing_required": False,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Visibility change to private failed: {e}", exc_info=True)
|
||||
# Clear guard flag on failure
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
})
|
||||
raise
|
||||
|
||||
async def change_to_public(self, job_id: str, job, user_email: str) -> dict:
|
||||
"""
|
||||
Change a private job to public (slow path).
|
||||
|
||||
Resets custom styles, deletes all outputs/screens/rendered video,
|
||||
and triggers full re-processing from screens worker onward.
|
||||
"""
|
||||
logger.info(f"[job:{job_id}] Starting visibility change: private -> public (by {user_email})")
|
||||
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
storage = StorageService()
|
||||
|
||||
# Step 1: Delete distributed outputs + GCS finals
|
||||
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=False)
|
||||
|
||||
# Step 2: Delete screens and rendered video from GCS
|
||||
for path in [
|
||||
f"jobs/{job_id}/screens/title.mov",
|
||||
f"jobs/{job_id}/screens/title.jpg",
|
||||
f"jobs/{job_id}/screens/title.png",
|
||||
f"jobs/{job_id}/screens/end.mov",
|
||||
f"jobs/{job_id}/screens/end.jpg",
|
||||
f"jobs/{job_id}/screens/end.png",
|
||||
f"jobs/{job_id}/videos/with_vocals.mkv",
|
||||
f"jobs/{job_id}/videos/with_vocals.mov",
|
||||
]:
|
||||
try:
|
||||
storage.delete_file(path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Delete custom style files from GCS
|
||||
try:
|
||||
style_prefix = f"jobs/{job_id}/style/"
|
||||
storage.delete_folder(style_prefix)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Step 3: Prepare nomad theme style files for the job
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
style_params_path, style_assets_dict, _youtube_desc = _prepare_theme_for_job(
|
||||
job_id=job_id, theme_id="nomad"
|
||||
)
|
||||
|
||||
# Step 4: Reset styles and update job fields
|
||||
# Step 5: Set status to LYRICS_COMPLETE with regen_restore_status
|
||||
# Step 6: Clear progress keys and set guard flag
|
||||
update_payload = {
|
||||
"is_private": False,
|
||||
"theme_id": "nomad",
|
||||
"color_overrides": {},
|
||||
"style_assets": style_assets_dict,
|
||||
"style_params_gcs_path": style_params_path,
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"state_data.visibility_change_in_progress": True,
|
||||
"state_data.regen_restore_status": "review_complete",
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.render_progress": DELETE_FIELD,
|
||||
"state_data.video_progress": DELETE_FIELD,
|
||||
"state_data.encoding_progress": DELETE_FIELD,
|
||||
"outputs_deleted_at": None,
|
||||
"outputs_deleted_by": None,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "lyrics_complete",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Visibility change to public initiated by {user_email}. "
|
||||
"Re-processing from screens generation.",
|
||||
}]),
|
||||
}
|
||||
job_ref.update(update_payload)
|
||||
|
||||
# Step 6: Trigger screens worker
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_screens_worker(job_id)
|
||||
|
||||
if not triggered:
|
||||
logger.error(f"[job:{job_id}] Failed to trigger screens worker for visibility change")
|
||||
# Restore to complete status on failure
|
||||
job_ref.update({
|
||||
"status": "complete",
|
||||
"is_private": True,
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
"state_data.regen_restore_status": DELETE_FIELD,
|
||||
})
|
||||
raise RuntimeError("Failed to trigger screens worker")
|
||||
|
||||
logger.info(f"[job:{job_id}] Visibility change to public initiated, screens worker triggered")
|
||||
return {
|
||||
"status": "processing",
|
||||
"message": "Visibility change to public started. The video will be re-rendered "
|
||||
"with default branding and published publicly. This takes ~15-30 minutes.",
|
||||
"reprocessing_required": True,
|
||||
}
|
||||
|
||||
async def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
|
||||
"""Delete distributed outputs (YouTube, Dropbox, GDrive) and recycle brand code."""
|
||||
import re
|
||||
|
||||
state_data = job.state_data or {}
|
||||
|
||||
# Delete YouTube video
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
try:
|
||||
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
|
||||
if video_id_match:
|
||||
video_id = video_id_match.group(1)
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False, non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict()
|
||||
)
|
||||
finalise.delete_youtube_video(video_id)
|
||||
logger.info(f"[job:{job_id}] Deleted YouTube video {video_id}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete YouTube video: {e}")
|
||||
|
||||
# Delete Dropbox folder
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
folder_name = f"{brand_code} - {safe_artist} - {safe_title}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
dropbox.delete_folder(full_path)
|
||||
logger.info(f"[job:{job_id}] Deleted Dropbox folder {full_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete Dropbox folder: {e}")
|
||||
|
||||
# Delete Google Drive files
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
gdrive.delete_files(file_ids)
|
||||
logger.info(f"[job:{job_id}] Deleted Google Drive files")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete Google Drive files: {e}")
|
||||
|
||||
# Delete GCS finals if requested
|
||||
if not keep_gcs_finals:
|
||||
try:
|
||||
storage = StorageService()
|
||||
deleted_count = storage.delete_folder(f"jobs/{job_id}/finals/")
|
||||
if deleted_count > 0:
|
||||
logger.info(f"[job:{job_id}] Deleted {deleted_count} GCS finals files")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete GCS finals: {e}")
|
||||
|
||||
# Recycle brand code
|
||||
if brand_code:
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
logger.info(f"[job:{job_id}] Recycled brand code {brand_code}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to recycle brand code: {e}")
|
||||
|
||||
# Clear distribution state_data
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
update = {}
|
||||
for key in ['youtube_url', 'brand_code', 'dropbox_link', 'gdrive_files']:
|
||||
if key in state_data:
|
||||
update[f"state_data.{key}"] = DELETE_FIELD
|
||||
if update:
|
||||
job_ref.update(update)
|
||||
@@ -361,7 +361,24 @@ class WorkerService:
|
||||
|
||||
# Convenience methods for specific workers
|
||||
# These provide a cleaner API and better IDE autocomplete
|
||||
|
||||
|
||||
async def trigger_audio_download_worker(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger audio download worker.
|
||||
|
||||
Downloads audio from the selected source (Spotify, YouTube, RED, OPS)
|
||||
and then triggers audio separation + lyrics workers.
|
||||
|
||||
Uses Cloud Run Jobs to avoid instance termination during long-running
|
||||
downloads. This replaces the BackgroundTasks approach that caused
|
||||
jobs to get stuck when Cloud Run scaled down instances.
|
||||
"""
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="audio-download-job",
|
||||
worker_module="audio_download_worker",
|
||||
)
|
||||
|
||||
async def trigger_audio_worker(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger audio separation worker.
|
||||
|
||||
@@ -68,6 +68,36 @@ class YouTubeDownloadService:
|
||||
"""Check if remote flacfetch is configured."""
|
||||
return self._flacfetch_client is not None
|
||||
|
||||
async def check_availability(self, url: str) -> Optional[dict]:
|
||||
"""
|
||||
Check if a YouTube video is available for download.
|
||||
|
||||
Uses the flacfetch /check-youtube endpoint to detect geo-restrictions,
|
||||
private/removed videos, etc. before creating a job.
|
||||
|
||||
Returns:
|
||||
Check result dict if check succeeds, None if check can't be
|
||||
performed (no remote configured, network error, etc.).
|
||||
Callers should treat None as "unknown, proceed anyway".
|
||||
"""
|
||||
if not self._flacfetch_client:
|
||||
return None
|
||||
|
||||
video_id = self._extract_video_id(url)
|
||||
if not video_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
result = await self._flacfetch_client.check_youtube(url)
|
||||
logger.info(
|
||||
f"YouTube availability check for {video_id}: "
|
||||
f"available={result.get('available')}"
|
||||
)
|
||||
return result
|
||||
except FlacfetchServiceError as e:
|
||||
logger.warning(f"YouTube availability check failed for {video_id}, proceeding anyway: {e}")
|
||||
return None
|
||||
|
||||
async def download(
|
||||
self,
|
||||
url: str,
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
"""
|
||||
Unit tests for admin edit reviews endpoints.
|
||||
|
||||
Tests the GET /api/admin/edit-reviews and GET /api/admin/edit-reviews/{job_id}
|
||||
endpoints for reviewing user lyrics corrections.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, AsyncMock
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# Create a test app with the admin router
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
# Override the require_admin dependency
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Create a test client."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _make_job_doc(job_id, artist="Test Artist", title="Test Song",
|
||||
user_email="user@example.com", status="complete",
|
||||
has_edit_log=True, has_corrections_updated=True):
|
||||
"""Create a mock Firestore document for a job."""
|
||||
doc = Mock()
|
||||
doc.id = job_id
|
||||
now = datetime.now(timezone.utc)
|
||||
state_data = {}
|
||||
if has_edit_log:
|
||||
state_data["last_edit_log_path"] = f"jobs/{job_id}/lyrics/edit_log_session1.json"
|
||||
state_data["last_edit_log_session"] = "session1"
|
||||
|
||||
file_urls = {"lyrics": {"corrections": f"jobs/{job_id}/lyrics/corrections.json"}}
|
||||
if has_corrections_updated:
|
||||
file_urls["lyrics"]["corrections_updated"] = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
doc.to_dict.return_value = {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"user_email": user_email,
|
||||
"status": status,
|
||||
"state_data": state_data,
|
||||
"file_urls": file_urls,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
return doc
|
||||
|
||||
|
||||
class TestListEditReviews:
|
||||
"""Tests for GET /api/admin/edit-reviews."""
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_returns_only_jobs_with_edit_logs(self, mock_get_user_service, client):
|
||||
"""Only jobs with edit logs should appear."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_job_doc("job-1", has_edit_log=True),
|
||||
_make_job_doc("job-2", has_edit_log=False),
|
||||
_make_job_doc("job-3", has_edit_log=True),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
response = client.get("/api/admin/edit-reviews")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 2
|
||||
assert len(data["reviews"]) == 2
|
||||
job_ids = [r["job_id"] for r in data["reviews"]]
|
||||
assert "job-1" in job_ids
|
||||
assert "job-3" in job_ids
|
||||
assert "job-2" not in job_ids
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_search_filter(self, mock_get_user_service, client):
|
||||
"""Search should filter by artist, title, and email."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_job_doc("job-1", artist="Beatles", title="Hey Jude"),
|
||||
_make_job_doc("job-2", artist="Queen", title="Bohemian Rhapsody"),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
response = client.get("/api/admin/edit-reviews?search=beatles")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["artist"] == "Beatles"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_pagination(self, mock_get_user_service, client):
|
||||
"""Pagination should work with offset and limit."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [_make_job_doc(f"job-{i}") for i in range(5)]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
response = client.get("/api/admin/edit-reviews?limit=2&offset=0")
|
||||
data = response.json()
|
||||
assert len(data["reviews"]) == 2
|
||||
assert data["total"] == 5
|
||||
assert data["has_more"] is True
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_exclude_test(self, mock_get_user_service, client):
|
||||
"""Test emails should be excluded when exclude_test=true."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_job_doc("job-1", user_email="real@example.com"),
|
||||
_make_job_doc("job-2", user_email="test@inbox.testmail.app"),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
response = client.get("/api/admin/edit-reviews?exclude_test=true")
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["user_email"] == "real@example.com"
|
||||
|
||||
|
||||
class TestGetEditReviewDetail:
|
||||
"""Tests for GET /api/admin/edit-reviews/{job_id}."""
|
||||
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_returns_404_for_missing_job(self, MockJobManager, MockStorage, client):
|
||||
MockJobManager.return_value.get_job.return_value = None
|
||||
response = client.get("/api/admin/edit-reviews/nonexistent")
|
||||
assert response.status_code == 404
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.AudioTranscodingService")
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_returns_full_snapshot(self, MockJobManager, MockStorage, MockTranscoding, client):
|
||||
"""Should return all available data for a job."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job"
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Song"
|
||||
job.user_email = "user@example.com"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.created_at = datetime(2026, 3, 1, tzinfo=timezone.utc)
|
||||
job.updated_at = datetime(2026, 3, 2, tzinfo=timezone.utc)
|
||||
job.input_media_gcs_path = "jobs/test-job/input.flac"
|
||||
job.file_urls = {
|
||||
"lyrics": {
|
||||
"corrections": "jobs/test-job/lyrics/corrections.json",
|
||||
"corrections_updated": "jobs/test-job/lyrics/corrections_updated.json",
|
||||
}
|
||||
}
|
||||
job.state_data = {
|
||||
"last_edit_log_path": "jobs/test-job/lyrics/edit_log_session1.json",
|
||||
}
|
||||
MockJobManager.return_value.get_job.return_value = job
|
||||
|
||||
storage = MockStorage.return_value
|
||||
storage.download_json.side_effect = lambda path: {
|
||||
"jobs/test-job/lyrics/corrections.json": {"original": True},
|
||||
"jobs/test-job/lyrics/corrections_updated.json": {"updated": True},
|
||||
"jobs/test-job/lyrics/edit_log_session1.json": {"entries": []},
|
||||
"jobs/test-job/lyrics/annotations.json": {"annotations": []},
|
||||
}.get(path, {})
|
||||
storage.file_exists.return_value = True
|
||||
|
||||
response = client.get("/api/admin/edit-reviews/test-job")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
assert data["job"]["job_id"] == "test-job"
|
||||
assert data["job"]["artist"] == "Test Artist"
|
||||
assert data["original_corrections"] == {"original": True}
|
||||
assert data["updated_corrections"] == {"updated": True}
|
||||
assert data["edit_log"] == {"entries": []}
|
||||
assert data["annotations"] == {"annotations": []}
|
||||
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_handles_missing_gcs_files_gracefully(self, MockJobManager, MockStorage, client):
|
||||
"""Should return null for missing GCS files, not error."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job"
|
||||
job.artist = "Test"
|
||||
job.title = "Song"
|
||||
job.user_email = "u@e.com"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.created_at = None
|
||||
job.updated_at = None
|
||||
job.input_media_gcs_path = None
|
||||
job.file_urls = {"lyrics": {}}
|
||||
job.state_data = {}
|
||||
MockJobManager.return_value.get_job.return_value = job
|
||||
|
||||
storage = MockStorage.return_value
|
||||
storage.file_exists.return_value = False
|
||||
storage.download_json.side_effect = Exception("Not found")
|
||||
|
||||
response = client.get("/api/admin/edit-reviews/test-job")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["original_corrections"] is None
|
||||
assert data["updated_corrections"] is None
|
||||
assert data["edit_log"] is None
|
||||
assert data["annotations"] is None
|
||||
assert data["audio_url"] is None
|
||||
@@ -0,0 +1,244 @@
|
||||
"""
|
||||
Tests for the audio download worker.
|
||||
|
||||
Tests the standalone worker that downloads audio from various sources
|
||||
(YouTube, Spotify, RED/OPS) and triggers processing workers.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.workers.audio_download_worker import (
|
||||
process_audio_download,
|
||||
_extract_gcs_path,
|
||||
_download_audio,
|
||||
)
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
|
||||
|
||||
def _make_job(
|
||||
job_id: str = "test-job-123",
|
||||
status=JobStatus.DOWNLOADING_AUDIO,
|
||||
source_name: str = "YouTube",
|
||||
source_id: str = "dQw4w9WgXcQ",
|
||||
state_data: dict = None,
|
||||
**kwargs,
|
||||
) -> Job:
|
||||
"""Helper to create test Job objects."""
|
||||
return Job(
|
||||
job_id=job_id,
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=status,
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data=state_data or {},
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
class TestExtractGcsPath:
|
||||
"""Tests for _extract_gcs_path helper."""
|
||||
|
||||
def test_strips_primary_bucket_prefix(self):
|
||||
path = "gs://karaoke-gen-storage-nomadkaraoke/uploads/123/audio/song.flac"
|
||||
assert _extract_gcs_path(path) == "uploads/123/audio/song.flac"
|
||||
|
||||
def test_strips_alternate_bucket_prefix(self):
|
||||
path = "gs://karaoke-gen-storage/uploads/123/audio/song.flac"
|
||||
assert _extract_gcs_path(path) == "uploads/123/audio/song.flac"
|
||||
|
||||
def test_unknown_gs_bucket_returned_as_is(self):
|
||||
"""Unknown bucket gs:// paths are returned unchanged (only known buckets stripped)."""
|
||||
path = "gs://other-bucket/uploads/123/audio/song.flac"
|
||||
# The function only strips known bucket prefixes
|
||||
assert _extract_gcs_path(path) == path
|
||||
|
||||
def test_returns_plain_path_unchanged(self):
|
||||
path = "uploads/123/audio/song.flac"
|
||||
assert _extract_gcs_path(path) == "uploads/123/audio/song.flac"
|
||||
|
||||
|
||||
class TestProcessAudioDownload:
|
||||
"""Tests for the main process_audio_download function."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_false_when_job_not_found(self):
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"):
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
result = await process_audio_download("nonexistent-job")
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_false_when_no_download_params(self):
|
||||
"""Job in wrong state with no download params should abort."""
|
||||
job = _make_job(
|
||||
status=JobStatus.PENDING,
|
||||
source_name=None,
|
||||
source_id=None,
|
||||
)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"):
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_download_success(self):
|
||||
"""Successful YouTube download triggers workers."""
|
||||
job = _make_job(source_name="YouTube", source_id="dQw4w9WgXcQ")
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
|
||||
|
||||
mock_ws = AsyncMock()
|
||||
mock_ws_factory.return_value = mock_ws
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is True
|
||||
mock_jm.update_job.assert_called_once_with("test-job-123", {
|
||||
'input_media_gcs_path': "uploads/test-job-123/audio/song.mp3",
|
||||
'filename': "song.mp3",
|
||||
})
|
||||
mock_jm.transition_to_state.assert_called_once()
|
||||
mock_ws.trigger_audio_worker.assert_awaited_once_with("test-job-123")
|
||||
mock_ws.trigger_lyrics_worker.assert_awaited_once_with("test-job-123")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_error_fails_job(self):
|
||||
"""DownloadError should fail the job and return False."""
|
||||
job = _make_job()
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.side_effect = DownloadError("Download timed out")
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is False
|
||||
mock_jm.fail_job.assert_called_once()
|
||||
assert "Download timed out" in mock_jm.fail_job.call_args[0][1]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_uses_state_data_selection_when_available(self):
|
||||
"""Should prefer state_data search results over job-level params."""
|
||||
job = _make_job(
|
||||
source_name="YouTube",
|
||||
source_id="fallback-id",
|
||||
state_data={
|
||||
'audio_search_results': [
|
||||
{'provider': 'Spotify', 'source_id': 'spotify123', 'target_file': None, 'url': None},
|
||||
],
|
||||
'selected_audio_index': 0,
|
||||
},
|
||||
)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.flac", "song.flac")
|
||||
|
||||
mock_ws = AsyncMock()
|
||||
mock_ws_factory.return_value = mock_ws
|
||||
|
||||
await process_audio_download("test-job-123")
|
||||
|
||||
# Should have called with Spotify params from state_data, not YouTube fallback
|
||||
call_kwargs = mock_dl.call_args[1]
|
||||
assert call_kwargs['source_name'] == 'Spotify'
|
||||
assert call_kwargs['source_id'] == 'spotify123'
|
||||
|
||||
|
||||
class TestDownloadAudio:
|
||||
"""Tests for _download_audio routing."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_routes_youtube_download(self):
|
||||
mock_storage = MagicMock()
|
||||
|
||||
with patch("backend.workers.audio_download_worker._download_youtube", new_callable=AsyncMock) as mock_yt:
|
||||
mock_yt.return_value = ("uploads/j/audio/song.mp3", "song.mp3")
|
||||
|
||||
result = await _download_audio(
|
||||
job_id="j", source_name="YouTube", source_id="vid123",
|
||||
target_file=None, download_url=None, remote_search_id=None,
|
||||
selection_index=None, selected={}, storage_service=mock_storage,
|
||||
)
|
||||
|
||||
assert result == ("uploads/j/audio/song.mp3", "song.mp3")
|
||||
mock_yt.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_routes_red_to_torrent(self):
|
||||
mock_storage = MagicMock()
|
||||
|
||||
with patch("backend.workers.audio_download_worker._download_torrent", new_callable=AsyncMock) as mock_torrent:
|
||||
mock_torrent.return_value = ("uploads/j/audio/song.flac", "song.flac")
|
||||
|
||||
await _download_audio(
|
||||
job_id="j", source_name="RED", source_id="123",
|
||||
target_file="track.flac", download_url=None, remote_search_id=None,
|
||||
selection_index=None, selected={}, storage_service=mock_storage,
|
||||
)
|
||||
|
||||
mock_torrent.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_routes_spotify_download(self):
|
||||
mock_storage = MagicMock()
|
||||
|
||||
with patch("backend.workers.audio_download_worker._download_spotify", new_callable=AsyncMock) as mock_sp:
|
||||
mock_sp.return_value = ("uploads/j/audio/song.ogg", "song.ogg")
|
||||
|
||||
await _download_audio(
|
||||
job_id="j", source_name="Spotify", source_id="track123",
|
||||
target_file=None, download_url=None, remote_search_id=None,
|
||||
selection_index=None, selected={}, storage_service=mock_storage,
|
||||
)
|
||||
|
||||
mock_sp.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_raises_for_unsupported_source(self):
|
||||
mock_storage = MagicMock()
|
||||
|
||||
with pytest.raises(DownloadError, match="Unsupported audio source"):
|
||||
await _download_audio(
|
||||
job_id="j", source_name="SoundCloud", source_id="123",
|
||||
target_file=None, download_url=None, remote_search_id=None,
|
||||
selection_index=None, selected={}, storage_service=mock_storage,
|
||||
)
|
||||
@@ -0,0 +1,369 @@
|
||||
"""
|
||||
Tests for the visibility change service.
|
||||
|
||||
Tests validation logic and the two visibility change flows:
|
||||
- Public -> Private (fast redistribution)
|
||||
- Private -> Public (full re-processing)
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.services.visibility_change_service import VisibilityChangeService
|
||||
|
||||
|
||||
def _make_job(
|
||||
job_id="test-123",
|
||||
status="complete",
|
||||
is_private=False,
|
||||
tenant_id="",
|
||||
user_email="user@example.com",
|
||||
state_data=None,
|
||||
):
|
||||
"""Create a mock job object for testing."""
|
||||
return SimpleNamespace(
|
||||
job_id=job_id,
|
||||
status=status,
|
||||
is_private=is_private,
|
||||
tenant_id=tenant_id,
|
||||
user_email=user_email,
|
||||
state_data=state_data or {},
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
outputs_deleted_at=None,
|
||||
dropbox_path="/Tracks-Organized",
|
||||
file_urls={"finals": {"lossy_4k_mp4": "gs://test/4k.mp4"}},
|
||||
)
|
||||
|
||||
|
||||
class TestValidation:
|
||||
"""Test validation logic for visibility changes."""
|
||||
|
||||
def setup_method(self):
|
||||
self.service = VisibilityChangeService(job_manager=MagicMock())
|
||||
|
||||
def test_validates_job_exists(self):
|
||||
error = self.service.validate_change(None, "user@example.com", False, "private")
|
||||
assert error == "Job not found"
|
||||
|
||||
def test_validates_complete_status(self):
|
||||
job = _make_job(status="generating_video")
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "completed jobs" in error
|
||||
|
||||
def test_validates_not_tenant_job(self):
|
||||
job = _make_job(tenant_id="vocalstar")
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "tenant" in error
|
||||
|
||||
def test_validates_different_visibility(self):
|
||||
job = _make_job(is_private=True)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "already private" in error
|
||||
|
||||
def test_validates_same_visibility_public(self):
|
||||
job = _make_job(is_private=False)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "public")
|
||||
assert "already public" in error
|
||||
|
||||
def test_validates_ownership(self):
|
||||
job = _make_job(user_email="owner@example.com")
|
||||
error = self.service.validate_change(job, "other@example.com", False, "private")
|
||||
assert "your own jobs" in error
|
||||
|
||||
def test_admin_can_change_any_job(self):
|
||||
job = _make_job(user_email="owner@example.com")
|
||||
error = self.service.validate_change(job, "admin@example.com", True, "private")
|
||||
assert error is None
|
||||
|
||||
def test_owner_can_change_own_job(self):
|
||||
job = _make_job(user_email="user@example.com")
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert error is None
|
||||
|
||||
def test_validates_no_concurrent_change(self):
|
||||
job = _make_job(state_data={"visibility_change_in_progress": True})
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "already in progress" in error
|
||||
|
||||
def test_valid_public_to_private(self):
|
||||
job = _make_job(is_private=False)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert error is None
|
||||
|
||||
def test_valid_private_to_public(self):
|
||||
job = _make_job(is_private=True)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "public")
|
||||
assert error is None
|
||||
|
||||
|
||||
class TestChangeToPrivate:
|
||||
"""Test public -> private visibility change."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calls_redistribute(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={
|
||||
"youtube_url": "https://youtube.com/watch?v=abc",
|
||||
"brand_code": "NOMAD-0001",
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock) as mock_delete, \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True) as mock_redist:
|
||||
|
||||
result = await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["reprocessing_required"] is False
|
||||
mock_delete.assert_called_once_with("test-123", job, keep_gcs_finals=True)
|
||||
mock_redist.assert_called_once_with("test-123")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sets_is_private_true(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True):
|
||||
|
||||
await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
# Check that is_private was set to True in one of the update calls
|
||||
update_calls = mock_job_ref.update.call_args_list
|
||||
found_private_update = any(
|
||||
call.args[0].get("is_private") is True
|
||||
for call in update_calls
|
||||
)
|
||||
assert found_private_update
|
||||
|
||||
|
||||
class TestChangeToPublic:
|
||||
"""Test private -> public visibility change."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_triggers_screens_worker(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={
|
||||
"brand_code": "NOMADNP-0001",
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)) as mock_theme, \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
result = await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
assert result["status"] == "processing"
|
||||
assert result["reprocessing_required"] is True
|
||||
mock_worker.trigger_screens_worker.assert_called_once_with("test-123")
|
||||
mock_theme.assert_called_once_with(job_id="test-123", theme_id="nomad")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resets_styles_to_nomad_theme(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)), \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
# Verify the update payload resets styles
|
||||
update_calls = mock_job_ref.update.call_args_list
|
||||
# Find the main update call (the one with theme_id)
|
||||
style_update = None
|
||||
for call in update_calls:
|
||||
payload = call.args[0]
|
||||
if "theme_id" in payload:
|
||||
style_update = payload
|
||||
break
|
||||
|
||||
assert style_update is not None
|
||||
assert style_update["theme_id"] == "nomad"
|
||||
assert style_update["color_overrides"] == {}
|
||||
assert style_update["style_assets"] == {"bg": "bg.png"}
|
||||
assert style_update["style_params_gcs_path"] == "jobs/test-123/style/style_params.json"
|
||||
assert style_update["is_private"] is False
|
||||
assert style_update["status"] == "lyrics_complete"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rollback_on_worker_failure(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {}, None)), \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=False)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
with pytest.raises(RuntimeError, match="Failed to trigger screens worker"):
|
||||
await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
# Verify rollback was attempted
|
||||
rollback_call = mock_job_ref.update.call_args_list[-1]
|
||||
payload = rollback_call.args[0]
|
||||
assert payload["status"] == "complete"
|
||||
assert payload["is_private"] is True
|
||||
|
||||
|
||||
class TestChangeToPrivateErrors:
|
||||
"""Test error handling in public -> private flow."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rollback_on_redistribute_failure(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=False):
|
||||
|
||||
with pytest.raises(RuntimeError, match="Redistribution failed"):
|
||||
await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
# Guard flag should be cleared on failure (DELETE_FIELD sentinel)
|
||||
last_update = mock_job_ref.update.call_args_list[-1]
|
||||
val = last_update.args[0].get("state_data.visibility_change_in_progress")
|
||||
assert "delete" in str(type(val)).lower() or "sentinel" in str(val).lower()
|
||||
|
||||
|
||||
class TestDeleteDistributedOutputs:
|
||||
"""Test cleanup of distributed outputs."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recycles_brand_code(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={"brand_code": "NOMAD-0042"})
|
||||
|
||||
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
|
||||
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)):
|
||||
mock_brand_svc = MagicMock()
|
||||
mock_bcs.return_value = mock_brand_svc
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
|
||||
|
||||
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_clears_distribution_state_keys(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={
|
||||
"youtube_url": "https://youtube.com/watch?v=abc",
|
||||
"brand_code": "NOMAD-0001",
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
|
||||
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 1)):
|
||||
mock_bcs.return_value = MagicMock()
|
||||
|
||||
# Patch YouTube deletion to avoid real service calls
|
||||
with patch("backend.services.youtube_service.get_youtube_service") as mock_yt, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service") as mock_dbx:
|
||||
mock_yt.return_value = MagicMock(is_configured=False)
|
||||
mock_dbx.return_value = MagicMock(is_configured=False)
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
|
||||
|
||||
update_call = mock_job_ref.update.call_args
|
||||
payload = update_call.args[0]
|
||||
# Verify keys are set to DELETE_FIELD sentinel
|
||||
for key in ["state_data.youtube_url", "state_data.brand_code", "state_data.dropbox_link"]:
|
||||
assert key in payload, f"Expected {key} in update payload"
|
||||
assert "sentinel" in str(payload[key]).lower() or "delete" in str(type(payload[key])).lower()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deletes_gcs_finals_when_not_kept(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.delete_folder.return_value = 3
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=False)
|
||||
|
||||
mock_storage.delete_folder.assert_called_once_with("jobs/test-123/finals/")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_gcs_finals_deletion_when_kept(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
|
||||
|
||||
mock_storage.delete_folder.assert_not_called()
|
||||
|
||||
|
||||
class TestStateTransitions:
|
||||
"""Test that the COMPLETE -> LYRICS_COMPLETE state transition is valid."""
|
||||
|
||||
def test_complete_allows_lyrics_complete_transition(self):
|
||||
from backend.models.job import STATE_TRANSITIONS, JobStatus
|
||||
allowed = STATE_TRANSITIONS[JobStatus.COMPLETE]
|
||||
assert JobStatus.LYRICS_COMPLETE in allowed
|
||||
@@ -0,0 +1,251 @@
|
||||
"""
|
||||
Unit tests for the edit completed track endpoint.
|
||||
|
||||
Tests POST /api/jobs/{job_id}/edit which allows users to reopen
|
||||
completed tracks for editing (lyrics, instrumental, metadata).
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import MagicMock, AsyncMock, patch, Mock
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def complete_job():
|
||||
"""A completed job with distribution data."""
|
||||
return Job(
|
||||
job_id="test-edit-123",
|
||||
status="complete",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
user_email="user@example.com",
|
||||
dropbox_path="/Karaoke/Organized",
|
||||
edit_count=0,
|
||||
state_data={
|
||||
"youtube_url": "https://youtu.be/abc123",
|
||||
"brand_code": "NOMAD-1234",
|
||||
"dropbox_link": "https://dropbox.com/...",
|
||||
"gdrive_files": {"mp4": "file_id_1", "mp4_720p": "file_id_2"},
|
||||
"audio_complete": True,
|
||||
"lyrics_complete": True,
|
||||
"render_progress": {"stage": "complete"},
|
||||
"video_progress": {"stage": "complete"},
|
||||
"encoding_progress": {"stage": "complete"},
|
||||
"review_complete": True,
|
||||
"corrected_lyrics": {"segments": []},
|
||||
"instrumental_selection": "clean",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(complete_job):
|
||||
"""Mock JobManager with common methods."""
|
||||
manager = MagicMock()
|
||||
manager.get_job.return_value = complete_job
|
||||
manager.transition_to_state.return_value = True
|
||||
return manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_worker_service():
|
||||
"""Mock WorkerService."""
|
||||
service = MagicMock()
|
||||
service.trigger_audio_worker = AsyncMock(return_value=True)
|
||||
service.trigger_lyrics_worker = AsyncMock(return_value=True)
|
||||
service.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
service.trigger_render_video_worker = AsyncMock(return_value=True)
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_job_manager, mock_worker_service):
|
||||
"""Create TestClient with mocked dependencies."""
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = "nomad"
|
||||
|
||||
def mock_job_manager_factory(*args, **kwargs):
|
||||
return mock_job_manager
|
||||
|
||||
# After edit, return updated job with review token
|
||||
updated_job = Job(
|
||||
job_id="test-edit-123",
|
||||
status="awaiting_review",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
user_email="user@example.com",
|
||||
review_token="test-review-token-abc",
|
||||
edit_count=1,
|
||||
)
|
||||
|
||||
def get_job_side_effect(job_id):
|
||||
# First call returns complete job, second returns updated job
|
||||
if mock_job_manager.get_job.call_count <= 1:
|
||||
return mock_job_manager.get_job.return_value
|
||||
return updated_job
|
||||
|
||||
mock_job_manager.get_job.side_effect = get_job_side_effect
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.jobs.StorageService') as mock_storage_cls, \
|
||||
patch('backend.api.routes.jobs.FirestoreService') as mock_fs_cls, \
|
||||
patch('backend.services.job_manager.JobManager', mock_job_manager_factory), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
mock_storage_cls.return_value.delete_folder.return_value = 3
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
yield TestClient(app)
|
||||
|
||||
|
||||
class TestEditCompletedTrackSuccess:
|
||||
"""Tests for successful edit initiation."""
|
||||
|
||||
def test_edit_returns_200(self, client, auth_headers):
|
||||
"""Edit a completed job returns 200."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_edit_returns_review_url(self, client, auth_headers):
|
||||
"""Response includes review URL."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
data = response.json()
|
||||
assert "review_url" in data
|
||||
assert "test-edit-123" in data["review_url"]
|
||||
assert "review" in data["review_url"]
|
||||
|
||||
def test_edit_returns_review_token(self, client, auth_headers):
|
||||
"""Response includes review token."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
data = response.json()
|
||||
assert data["review_token"] == "test-review-token-abc"
|
||||
|
||||
def test_edit_transitions_to_awaiting_review(self, client, mock_job_manager, auth_headers):
|
||||
"""Job state transitions to AWAITING_REVIEW."""
|
||||
client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
mock_job_manager.transition_to_state.assert_called_once_with(
|
||||
"test-edit-123",
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
progress=60,
|
||||
message="Track reopened for editing",
|
||||
)
|
||||
|
||||
def test_edit_without_metadata_change(self, client, auth_headers):
|
||||
"""Edit without metadata returns metadata_updated=false."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
data = response.json()
|
||||
assert data["metadata_updated"] is False
|
||||
|
||||
def test_edit_does_not_trigger_screens_without_metadata(self, client, mock_worker_service, auth_headers):
|
||||
"""Screens worker not triggered when metadata unchanged."""
|
||||
client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
mock_worker_service.trigger_screens_worker.assert_not_called()
|
||||
|
||||
|
||||
class TestEditWithMetadataUpdate:
|
||||
"""Tests for editing with artist/title changes."""
|
||||
|
||||
def test_edit_with_artist_change(self, client, auth_headers):
|
||||
"""Edit with new artist returns metadata_updated=true."""
|
||||
response = client.post(
|
||||
"/api/jobs/test-edit-123/edit",
|
||||
headers=auth_headers,
|
||||
json={"artist": "New Artist"},
|
||||
)
|
||||
data = response.json()
|
||||
assert data["metadata_updated"] is True
|
||||
|
||||
def test_edit_with_title_change(self, client, auth_headers):
|
||||
"""Edit with new title returns metadata_updated=true."""
|
||||
response = client.post(
|
||||
"/api/jobs/test-edit-123/edit",
|
||||
headers=auth_headers,
|
||||
json={"title": "New Song Title"},
|
||||
)
|
||||
data = response.json()
|
||||
assert data["metadata_updated"] is True
|
||||
|
||||
def test_edit_with_same_artist_no_metadata_update(self, client, auth_headers):
|
||||
"""Edit with same artist does not flag metadata_updated."""
|
||||
response = client.post(
|
||||
"/api/jobs/test-edit-123/edit",
|
||||
headers=auth_headers,
|
||||
json={"artist": "Test Artist"},
|
||||
)
|
||||
data = response.json()
|
||||
assert data["metadata_updated"] is False
|
||||
|
||||
def test_edit_triggers_screens_on_metadata_change(self, client, mock_worker_service, auth_headers):
|
||||
"""Screens worker triggered when metadata changes."""
|
||||
client.post(
|
||||
"/api/jobs/test-edit-123/edit",
|
||||
headers=auth_headers,
|
||||
json={"artist": "New Artist"},
|
||||
)
|
||||
mock_worker_service.trigger_screens_worker.assert_called_once_with("test-edit-123")
|
||||
|
||||
|
||||
class TestEditValidation:
|
||||
"""Tests for validation and error cases."""
|
||||
|
||||
def test_edit_non_complete_job_returns_400(self, client, mock_job_manager, auth_headers):
|
||||
"""Cannot edit a job that isn't complete."""
|
||||
pending_job = Job(
|
||||
job_id="test-pending",
|
||||
status="pending",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.side_effect = None
|
||||
mock_job_manager.get_job.return_value = pending_job
|
||||
|
||||
response = client.post("/api/jobs/test-pending/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 400
|
||||
assert "completed" in response.json()["detail"].lower() or "complete" in response.json()["detail"].lower()
|
||||
|
||||
def test_edit_already_deleted_outputs_returns_400(self, client, mock_job_manager, auth_headers):
|
||||
"""Cannot edit a job whose outputs are already deleted."""
|
||||
deleted_job = Job(
|
||||
job_id="test-deleted",
|
||||
status="complete",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.side_effect = None
|
||||
mock_job_manager.get_job.return_value = deleted_job
|
||||
|
||||
response = client.post("/api/jobs/test-deleted/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 400
|
||||
assert "already" in response.json()["detail"].lower()
|
||||
|
||||
def test_edit_nonexistent_job_returns_404(self, client, mock_job_manager, auth_headers):
|
||||
"""Cannot edit a job that doesn't exist."""
|
||||
mock_job_manager.get_job.side_effect = None
|
||||
mock_job_manager.get_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/nonexistent/edit", headers=auth_headers, json={})
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestEditCleanup:
|
||||
"""Tests for output cleanup during edit."""
|
||||
|
||||
def test_cleanup_results_in_response(self, client, auth_headers):
|
||||
"""Response includes cleanup results."""
|
||||
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
|
||||
data = response.json()
|
||||
assert "cleanup_results" in data
|
||||
assert "gcs_finals" in data["cleanup_results"]
|
||||
@@ -1048,3 +1048,101 @@ class TestWaitForDownloadRetryTolerance:
|
||||
"dl_test", timeout=10, poll_interval=0.01,
|
||||
)
|
||||
|
||||
|
||||
class TestCheckYoutube:
|
||||
"""Tests for FlacfetchClient.check_youtube()."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_youtube_available(self):
|
||||
"""Should return availability info for available video."""
|
||||
client = FlacfetchClient(base_url="http://test:8080", api_key="key")
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {
|
||||
"available": True,
|
||||
"video_id": "dQw4w9WgXcQ",
|
||||
"title": "Rick Astley - Never Gonna Give You Up",
|
||||
"error": None,
|
||||
"is_geo_restricted": False,
|
||||
}
|
||||
mock_response.raise_for_status = MagicMock()
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_class:
|
||||
mock_http = AsyncMock()
|
||||
mock_http.post = AsyncMock(return_value=mock_response)
|
||||
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
|
||||
mock_http.__aexit__ = AsyncMock(return_value=None)
|
||||
mock_class.return_value = mock_http
|
||||
|
||||
result = await client.check_youtube("https://youtube.com/watch?v=dQw4w9WgXcQ")
|
||||
|
||||
assert result["available"] is True
|
||||
assert result["video_id"] == "dQw4w9WgXcQ"
|
||||
mock_http.post.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_youtube_geo_restricted(self):
|
||||
"""Should return geo-restriction info for blocked video."""
|
||||
client = FlacfetchClient(base_url="http://test:8080", api_key="key")
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {
|
||||
"available": False,
|
||||
"video_id": "-yV25PrHglw",
|
||||
"title": None,
|
||||
"error": "This YouTube video is unavailable.",
|
||||
"is_geo_restricted": True,
|
||||
}
|
||||
mock_response.raise_for_status = MagicMock()
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_class:
|
||||
mock_http = AsyncMock()
|
||||
mock_http.post = AsyncMock(return_value=mock_response)
|
||||
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
|
||||
mock_http.__aexit__ = AsyncMock(return_value=None)
|
||||
mock_class.return_value = mock_http
|
||||
|
||||
result = await client.check_youtube("-yV25PrHglw")
|
||||
|
||||
assert result["available"] is False
|
||||
assert result["is_geo_restricted"] is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_youtube_network_error(self):
|
||||
"""Should raise FlacfetchServiceError on network error."""
|
||||
client = FlacfetchClient(base_url="http://test:8080", api_key="key")
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_class:
|
||||
mock_http = AsyncMock()
|
||||
mock_http.post = AsyncMock(side_effect=httpx.ConnectError("Connection refused"))
|
||||
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
|
||||
mock_http.__aexit__ = AsyncMock(return_value=None)
|
||||
mock_class.return_value = mock_http
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="YouTube availability check failed"):
|
||||
await client.check_youtube("some-id")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_youtube_http_error(self):
|
||||
"""Should raise FlacfetchServiceError on HTTP error."""
|
||||
client = FlacfetchClient(base_url="http://test:8080", api_key="key")
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 500
|
||||
mock_response.text = "Internal Server Error"
|
||||
mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
|
||||
"Server Error", request=MagicMock(), response=mock_response
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_class:
|
||||
mock_http = AsyncMock()
|
||||
mock_http.post = AsyncMock(return_value=mock_response)
|
||||
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
|
||||
mock_http.__aexit__ = AsyncMock(return_value=None)
|
||||
mock_class.return_value = mock_http
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="YouTube availability check failed"):
|
||||
await client.check_youtube("some-id")
|
||||
|
||||
@@ -163,6 +163,58 @@ class TestInstrumentalSelection:
|
||||
assert result.name == "instrumental.flac"
|
||||
|
||||
|
||||
class TestExistingInstrumental:
|
||||
"""Test that existing (user-uploaded) instrumentals are found correctly."""
|
||||
|
||||
def test_existing_instrumental_found_by_pattern(self, tmp_path):
|
||||
"""Test that existing_instrumental file is found when present."""
|
||||
existing = tmp_path / "existing_instrumental.mp3"
|
||||
existing.touch()
|
||||
|
||||
result = find_file(tmp_path, "*existing_instrumental*", "*Instrumental User*")
|
||||
assert result is not None
|
||||
assert "existing_instrumental" in result.name
|
||||
|
||||
def test_instrumental_user_found_by_pattern(self, tmp_path):
|
||||
"""Test that Instrumental User file is found when present."""
|
||||
user_file = tmp_path / "Artist - Title (Instrumental User).mp3"
|
||||
user_file.touch()
|
||||
|
||||
result = find_file(tmp_path, "*existing_instrumental*", "*Instrumental User*")
|
||||
assert result is not None
|
||||
assert "Instrumental User" in result.name
|
||||
|
||||
def test_existing_instrumental_takes_priority_over_separated(self, tmp_path):
|
||||
"""When existing instrumental is present alongside separated stems,
|
||||
the existing_instrumental config should cause it to be found first.
|
||||
|
||||
This tests the logic flow: if config has existing_instrumental,
|
||||
we search for *existing_instrumental* patterns BEFORE checking
|
||||
instrumental_selection.
|
||||
"""
|
||||
# Create both types
|
||||
existing = tmp_path / "existing_instrumental.flac"
|
||||
separated = tmp_path / "instrumental_clean.flac"
|
||||
custom = tmp_path / "custom_instrumental.flac"
|
||||
existing.touch()
|
||||
separated.touch()
|
||||
custom.touch()
|
||||
|
||||
# existing_instrumental pattern should find the right file
|
||||
result = find_file(tmp_path, "*existing_instrumental*", "*Instrumental User*")
|
||||
assert result is not None
|
||||
assert "existing_instrumental" in result.name
|
||||
|
||||
def test_existing_instrumental_not_found_returns_none(self, tmp_path):
|
||||
"""When no existing instrumental file exists, find_file returns None."""
|
||||
# Only separated stems exist
|
||||
tmp_path_file = tmp_path / "instrumental_clean.flac"
|
||||
tmp_path_file.touch()
|
||||
|
||||
result = find_file(tmp_path, "*existing_instrumental*", "*Instrumental User*")
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestInstrumentalSelectionRegression:
|
||||
"""Regression tests for instrumental selection bug.
|
||||
|
||||
|
||||
@@ -151,6 +151,7 @@ class TestUserEmailExtraction:
|
||||
# Mock YouTube download service to return a GCS path
|
||||
from unittest.mock import AsyncMock
|
||||
mock_yt_service = Mock()
|
||||
mock_yt_service.check_availability = AsyncMock(return_value=None)
|
||||
mock_yt_service.download = AsyncMock(return_value="uploads/test-job-456/audio/test.webm")
|
||||
mock_yt.return_value = mock_yt_service
|
||||
|
||||
|
||||
@@ -172,6 +172,36 @@ class TestCheckJobConsistency:
|
||||
issues = check_job_consistency(job)
|
||||
assert any("encoding_stuck" in i for i in issues)
|
||||
|
||||
def test_downloading_audio_recently_started_not_flagged(self):
|
||||
"""Download started 3 minutes ago should not be flagged."""
|
||||
job = create_test_job(status=JobStatus.DOWNLOADING_AUDIO)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=3)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("downloading_audio_stuck" in i for i in issues)
|
||||
|
||||
def test_downloading_audio_stuck_15_min_flagged(self):
|
||||
"""Download stuck for 15 minutes should be flagged."""
|
||||
job = create_test_job(status=JobStatus.DOWNLOADING_AUDIO)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=15)
|
||||
issues = check_job_consistency(job)
|
||||
assert any("downloading_audio_stuck" in i for i in issues)
|
||||
stuck_issue = [i for i in issues if "downloading_audio_stuck" in i][0]
|
||||
assert "15 min" in stuck_issue
|
||||
|
||||
def test_downloading_audio_at_9_min_not_flagged(self):
|
||||
"""Download at 9 minutes should not be flagged (must exceed 10)."""
|
||||
job = create_test_job(status=JobStatus.DOWNLOADING_AUDIO)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=9)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("downloading_audio_stuck" in i for i in issues)
|
||||
|
||||
def test_non_downloading_audio_not_affected(self):
|
||||
"""Non-downloading_audio job should not trigger this check."""
|
||||
job = create_test_job(status=JobStatus.DOWNLOADING)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=120)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("downloading_audio_stuck" in i for i in issues)
|
||||
|
||||
|
||||
class TestCheckJobConsistencyDetailed:
|
||||
"""Tests for check_job_consistency_detailed function."""
|
||||
|
||||
@@ -851,6 +851,74 @@ class TestStartJobProcessing:
|
||||
assert any('lyrics_start' in str(c) for c in call_order)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_audio_worker_when_existing_instrumental(self, job_manager, mock_firestore_service):
|
||||
"""Test that audio separation is skipped when job has existing instrumental.
|
||||
|
||||
Jobs with existing_instrumental_gcs_path (e.g. tenant uploads) don't need
|
||||
GPU-powered audio separation. Only lyrics worker should be triggered.
|
||||
"""
|
||||
mock_firestore_service.get_job.return_value = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
input_media_gcs_path="gs://bucket/audio.mp3",
|
||||
existing_instrumental_gcs_path="uploads/test123/audio/existing_instrumental.mp3"
|
||||
)
|
||||
|
||||
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker:
|
||||
mock_worker = Mock()
|
||||
mock_worker.trigger_audio_worker = AsyncMock()
|
||||
mock_worker.trigger_lyrics_worker = AsyncMock()
|
||||
mock_get_worker.return_value = mock_worker
|
||||
|
||||
await job_manager.start_job_processing("test123")
|
||||
|
||||
# Audio worker should NOT be triggered
|
||||
mock_worker.trigger_audio_worker.assert_not_called()
|
||||
|
||||
# Lyrics worker should still be triggered
|
||||
mock_worker.trigger_lyrics_worker.assert_called_once_with("test123")
|
||||
|
||||
# audio_complete should be set via update_job (update_state_data calls update_job)
|
||||
update_calls = mock_firestore_service.update_job.call_args_list
|
||||
audio_complete_set = any(
|
||||
call.args[1].get('state_data', {}).get('audio_complete') is True
|
||||
for call in update_calls
|
||||
if len(call.args) > 1 and isinstance(call.args[1], dict)
|
||||
)
|
||||
assert audio_complete_set, "audio_complete should be set to True in state_data"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_triggers_both_workers_when_no_existing_instrumental(self, job_manager, mock_firestore_service):
|
||||
"""Test that both workers are triggered when no existing instrumental.
|
||||
|
||||
Normal jobs (without existing_instrumental_gcs_path) should trigger
|
||||
both audio and lyrics workers in parallel.
|
||||
"""
|
||||
mock_firestore_service.get_job.return_value = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
input_media_gcs_path="gs://bucket/audio.mp3",
|
||||
existing_instrumental_gcs_path=None # No existing instrumental
|
||||
)
|
||||
|
||||
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker:
|
||||
mock_worker = Mock()
|
||||
mock_worker.trigger_audio_worker = AsyncMock()
|
||||
mock_worker.trigger_lyrics_worker = AsyncMock()
|
||||
mock_get_worker.return_value = mock_worker
|
||||
|
||||
await job_manager.start_job_processing("test123")
|
||||
|
||||
# Both workers should be triggered
|
||||
mock_worker.trigger_audio_worker.assert_called_once_with("test123")
|
||||
mock_worker.trigger_lyrics_worker.assert_called_once_with("test123")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
Tests for job observability improvements.
|
||||
|
||||
Covers:
|
||||
- TimelineEvent metadata field
|
||||
- log_to_job helper function
|
||||
- Timeline metadata in state transitions
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from backend.models.job import TimelineEvent
|
||||
|
||||
|
||||
class TestTimelineEventMetadata:
|
||||
"""Tests for the metadata field on TimelineEvent."""
|
||||
|
||||
def test_timeline_event_without_metadata(self):
|
||||
"""Existing events without metadata still work."""
|
||||
event = TimelineEvent(
|
||||
status="complete",
|
||||
timestamp="2026-03-07T12:00:00",
|
||||
progress=100,
|
||||
message="Done!",
|
||||
)
|
||||
data = event.model_dump(mode='json')
|
||||
assert data["status"] == "complete"
|
||||
assert data["metadata"] is None
|
||||
|
||||
def test_timeline_event_with_metadata(self):
|
||||
"""Events can include structured metadata."""
|
||||
metadata = {
|
||||
"action": "completed",
|
||||
"brand_code": "NOMAD-1234",
|
||||
"youtube_url": "https://youtube.com/watch?v=abc123",
|
||||
"gdrive_file_ids": {"mp4": "file1", "cdg": "file2"},
|
||||
}
|
||||
event = TimelineEvent(
|
||||
status="complete",
|
||||
timestamp="2026-03-07T12:00:00",
|
||||
progress=100,
|
||||
message="Karaoke generation complete!",
|
||||
metadata=metadata,
|
||||
)
|
||||
data = event.model_dump(mode='json')
|
||||
assert data["metadata"]["brand_code"] == "NOMAD-1234"
|
||||
assert data["metadata"]["youtube_url"] == "https://youtube.com/watch?v=abc123"
|
||||
assert data["metadata"]["gdrive_file_ids"]["mp4"] == "file1"
|
||||
|
||||
def test_timeline_event_with_edit_metadata(self):
|
||||
"""Edit-initiated events include previous outputs and cleanup results."""
|
||||
metadata = {
|
||||
"action": "edit_initiated",
|
||||
"initiated_by": "user@example.com",
|
||||
"edit_number": 1,
|
||||
"previous_outputs": {
|
||||
"youtube_url": "https://youtube.com/watch?v=old123",
|
||||
"brand_code": "NOMAD-0042",
|
||||
"dropbox_link": "https://dropbox.com/sh/old",
|
||||
},
|
||||
"cleanup_results": {
|
||||
"youtube": {"status": "success", "video_id": "old123"},
|
||||
"dropbox": {"status": "success", "path": "/Karaoke/NOMAD-0042"},
|
||||
"gdrive": {"status": "skipped", "reason": "no gdrive_files"},
|
||||
},
|
||||
}
|
||||
event = TimelineEvent(
|
||||
status="complete",
|
||||
timestamp="2026-03-07T12:00:00",
|
||||
message="Track edit initiated by user@example.com (edit #1)",
|
||||
metadata=metadata,
|
||||
)
|
||||
data = event.model_dump(mode='json')
|
||||
assert data["metadata"]["previous_outputs"]["youtube_url"] == "https://youtube.com/watch?v=old123"
|
||||
assert data["metadata"]["cleanup_results"]["youtube"]["status"] == "success"
|
||||
|
||||
def test_timeline_event_metadata_roundtrip(self):
|
||||
"""Metadata survives serialization/deserialization."""
|
||||
metadata = {"brand_code": "NOMAD-1234", "nested": {"key": "value"}}
|
||||
event = TimelineEvent(
|
||||
status="complete",
|
||||
timestamp="2026-03-07T12:00:00",
|
||||
metadata=metadata,
|
||||
)
|
||||
data = event.model_dump(mode='json')
|
||||
restored = TimelineEvent(**data)
|
||||
assert restored.metadata == metadata
|
||||
|
||||
|
||||
class TestLogToJob:
|
||||
"""Tests for the log_to_job helper function."""
|
||||
|
||||
@patch('backend.services.firestore_service._get_log_service')
|
||||
def test_log_to_job_writes_to_subcollection(self, mock_get_service):
|
||||
"""log_to_job creates a WorkerLogEntry and writes to Firestore."""
|
||||
mock_service = MagicMock()
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
from backend.services.firestore_service import log_to_job
|
||||
log_to_job("job123", "edit", "INFO", "Edit started", {"key": "value"})
|
||||
|
||||
mock_service.append_log_to_subcollection.assert_called_once()
|
||||
call_args = mock_service.append_log_to_subcollection.call_args
|
||||
assert call_args[0][0] == "job123"
|
||||
entry = call_args[0][1]
|
||||
assert entry.worker == "edit"
|
||||
assert entry.level == "INFO"
|
||||
assert entry.message == "Edit started"
|
||||
assert entry.metadata == {"key": "value"}
|
||||
|
||||
@patch('backend.services.firestore_service._get_log_service')
|
||||
def test_log_to_job_suppresses_errors(self, mock_get_service):
|
||||
"""log_to_job should never raise — logging failures must be silent."""
|
||||
mock_get_service.side_effect = Exception("Firestore down")
|
||||
|
||||
from backend.services.firestore_service import log_to_job
|
||||
# Should not raise
|
||||
log_to_job("job123", "edit", "INFO", "Edit started")
|
||||
|
||||
@patch('backend.services.firestore_service._get_log_service')
|
||||
def test_log_to_job_without_metadata(self, mock_get_service):
|
||||
"""log_to_job works without metadata."""
|
||||
mock_service = MagicMock()
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
from backend.services.firestore_service import log_to_job
|
||||
log_to_job("job123", "admin", "WARNING", "Something happened")
|
||||
|
||||
mock_service.append_log_to_subcollection.assert_called_once()
|
||||
entry = mock_service.append_log_to_subcollection.call_args[0][1]
|
||||
assert entry.metadata is None
|
||||
@@ -85,6 +85,50 @@ class TestJobModelIsPrivate:
|
||||
|
||||
assert job.is_private is False
|
||||
|
||||
def test_create_job_stores_creation_params(self):
|
||||
"""JobManager.create_job should store creation_params for observability."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
manager = JobManager()
|
||||
manager.firestore = Mock()
|
||||
manager.firestore.create_job = Mock()
|
||||
|
||||
job_create = JobCreate(
|
||||
artist="Test",
|
||||
title="Song",
|
||||
theme_id="nomad",
|
||||
is_private=True,
|
||||
request_metadata={"created_from": "guided_flow"},
|
||||
)
|
||||
|
||||
job = manager.create_job(job_create, is_admin=False)
|
||||
|
||||
assert job.creation_params == {
|
||||
"is_private": True,
|
||||
"is_admin": False,
|
||||
"created_from": "guided_flow",
|
||||
}
|
||||
|
||||
def test_creation_params_defaults_created_from_unknown(self):
|
||||
"""creation_params should default created_from to 'unknown' when not in metadata."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
manager = JobManager()
|
||||
manager.firestore = Mock()
|
||||
manager.firestore.create_job = Mock()
|
||||
|
||||
job_create = JobCreate(
|
||||
artist="Test",
|
||||
title="Song",
|
||||
theme_id="nomad",
|
||||
)
|
||||
|
||||
job = manager.create_job(job_create, is_admin=True)
|
||||
|
||||
assert job.creation_params["created_from"] == "unknown"
|
||||
assert job.creation_params["is_private"] is False
|
||||
assert job.creation_params["is_admin"] is True
|
||||
|
||||
|
||||
class TestGetEffectiveDistributionForJob:
|
||||
"""Tests for get_effective_distribution_for_job() helper."""
|
||||
@@ -406,6 +450,7 @@ class TestOrchestratorConfigPrivate:
|
||||
job.gdrive_folder_id = "folder-123"
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
job.tenant_id = None # Non-tenant job
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
|
||||
@@ -341,6 +341,404 @@ class TestSubscriptionManagement:
|
||||
assert "keys" not in result[0]
|
||||
|
||||
|
||||
class TestTenantIsolation:
|
||||
"""Tests for tenant-scoped push notification isolation."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_push_filters_by_tenant(self, push_service):
|
||||
"""send_push only sends to subscriptions matching the target tenant."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/consumer",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
},
|
||||
{
|
||||
"endpoint": "https://push.example.com/vocalstar",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "vocalstar",
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
# Send to consumer portal (tenant_id=None)
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id=None
|
||||
)
|
||||
assert result == 1
|
||||
assert mock_webpush.call_args[1]["subscription_info"]["endpoint"] == \
|
||||
"https://push.example.com/consumer"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_push_filters_by_tenant_name(self, push_service):
|
||||
"""send_push only sends to subscriptions for the specified tenant."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/consumer",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
},
|
||||
{
|
||||
"endpoint": "https://push.example.com/vocalstar",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "vocalstar",
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
# Send to vocalstar tenant
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id="vocalstar"
|
||||
)
|
||||
assert result == 1
|
||||
assert mock_webpush.call_args[1]["subscription_info"]["endpoint"] == \
|
||||
"https://push.example.com/vocalstar"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_push_no_cross_tenant_leakage(self, push_service):
|
||||
"""send_push never sends consumer notifications to tenant subscriptions."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/vocalstar",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "vocalstar",
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
# Consumer job should NOT send to vocalstar subscription
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id=None
|
||||
)
|
||||
assert result == 0
|
||||
mock_webpush.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_push_legacy_subscriptions_for_consumer(self, push_service):
|
||||
"""Legacy subscriptions (no tenant_id) are used for consumer notifications."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/legacy",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
# No tenant_id field at all (legacy)
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id=None
|
||||
)
|
||||
assert result == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_push_legacy_subscriptions_not_for_tenant(self, push_service):
|
||||
"""Legacy subscriptions (no tenant_id) are NOT used for tenant notifications."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/legacy",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
# No tenant_id field (legacy)
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id="vocalstar"
|
||||
)
|
||||
assert result == 0
|
||||
mock_webpush.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_push_empty_string_tenant_matches_none(self, push_service):
|
||||
"""Empty string tenant_id is treated as None (consumer portal)."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/consumer",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
# Empty string tenant_id should match None
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id=""
|
||||
)
|
||||
assert result == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_subscription_stores_tenant_id(self, push_service):
|
||||
"""add_subscription stores tenant_id on the subscription."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"push_subscriptions": []}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
result = await push_service.add_subscription(
|
||||
"test@example.com",
|
||||
"https://push.example.com/endpoint",
|
||||
{"p256dh": "key", "auth": "auth"},
|
||||
"Test Device",
|
||||
tenant_id="vocalstar"
|
||||
)
|
||||
|
||||
assert result is True
|
||||
update_call = push_service.db.collection.return_value.document.return_value.update.call_args
|
||||
subs = update_call[0][0]["push_subscriptions"]
|
||||
assert len(subs) == 1
|
||||
assert subs[0]["tenant_id"] == "vocalstar"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_completion_notification_uses_job_tenant(self, push_service):
|
||||
"""send_completion_notification passes job's tenant_id to send_push."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [{
|
||||
"endpoint": "https://push.example.com/endpoint",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "vocalstar",
|
||||
}]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
job = {
|
||||
"job_id": "test-job-123",
|
||||
"user_email": "test@example.com",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song",
|
||||
"tenant_id": "vocalstar",
|
||||
}
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
result = await push_service.send_completion_notification(job)
|
||||
assert result == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_blocking_notification_uses_job_tenant(self, push_service):
|
||||
"""send_blocking_notification passes job's tenant_id to send_push."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [{
|
||||
"endpoint": "https://push.example.com/endpoint",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "vocalstar",
|
||||
}]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
job = {
|
||||
"job_id": "test-job-123",
|
||||
"user_email": "test@example.com",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song",
|
||||
"tenant_id": "vocalstar",
|
||||
}
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
result = await push_service.send_blocking_notification(job, "lyrics")
|
||||
assert result == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_multi_tenant_user_receives_correct_notifications(self, push_service):
|
||||
"""User subscribed on both consumer and tenant portals gets isolated notifications."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/consumer-device",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
},
|
||||
{
|
||||
"endpoint": "https://push.example.com/vocalstar-device",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "vocalstar",
|
||||
},
|
||||
{
|
||||
"endpoint": "https://push.example.com/singa-device",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "singa",
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
# Consumer job -> only consumer device
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id=None
|
||||
)
|
||||
assert result == 1
|
||||
assert mock_webpush.call_args[1]["subscription_info"]["endpoint"] == \
|
||||
"https://push.example.com/consumer-device"
|
||||
|
||||
mock_webpush.reset_mock()
|
||||
|
||||
# Vocalstar job -> only vocalstar device
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id="vocalstar"
|
||||
)
|
||||
assert result == 1
|
||||
assert mock_webpush.call_args[1]["subscription_info"]["endpoint"] == \
|
||||
"https://push.example.com/vocalstar-device"
|
||||
|
||||
mock_webpush.reset_mock()
|
||||
|
||||
# Singa job -> only singa device
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id="singa"
|
||||
)
|
||||
assert result == 1
|
||||
assert mock_webpush.call_args[1]["subscription_info"]["endpoint"] == \
|
||||
"https://push.example.com/singa-device"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_subscription_replaces_endpoint_updates_tenant(self, push_service):
|
||||
"""Re-subscribing same endpoint with different tenant_id updates the tenant."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [{
|
||||
"endpoint": "https://push.example.com/endpoint",
|
||||
"keys": {"p256dh": "old-key", "auth": "old-auth"},
|
||||
"tenant_id": None,
|
||||
"device_name": "Chrome",
|
||||
"created_at": "2024-01-01T00:00:00Z",
|
||||
}]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
result = await push_service.add_subscription(
|
||||
"test@example.com",
|
||||
"https://push.example.com/endpoint",
|
||||
{"p256dh": "new-key", "auth": "new-auth"},
|
||||
"Chrome",
|
||||
tenant_id="vocalstar"
|
||||
)
|
||||
|
||||
assert result is True
|
||||
update_call = push_service.db.collection.return_value.document.return_value.update.call_args
|
||||
subs = update_call[0][0]["push_subscriptions"]
|
||||
assert len(subs) == 1
|
||||
assert subs[0]["tenant_id"] == "vocalstar"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_subscription_without_tenant_stores_none(self, push_service):
|
||||
"""add_subscription with no tenant_id stores None (consumer portal)."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"push_subscriptions": []}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
result = await push_service.add_subscription(
|
||||
"test@example.com",
|
||||
"https://push.example.com/endpoint",
|
||||
{"p256dh": "key", "auth": "auth"},
|
||||
"Test Device"
|
||||
)
|
||||
|
||||
assert result is True
|
||||
update_call = push_service.db.collection.return_value.document.return_value.update.call_args
|
||||
subs = update_call[0][0]["push_subscriptions"]
|
||||
assert subs[0]["tenant_id"] is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_completion_notification_consumer_job_no_tenant(self, push_service):
|
||||
"""Consumer job (no tenant_id) only notifies consumer subscriptions."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/consumer",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
},
|
||||
{
|
||||
"endpoint": "https://push.example.com/vocalstar",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "vocalstar",
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
job = {
|
||||
"job_id": "job-456",
|
||||
"user_email": "test@example.com",
|
||||
"artist": "Artist",
|
||||
"title": "Song",
|
||||
# No tenant_id -> consumer job
|
||||
}
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
result = await push_service.send_completion_notification(job)
|
||||
assert result == 1
|
||||
assert mock_webpush.call_args[1]["subscription_info"]["endpoint"] == \
|
||||
"https://push.example.com/consumer"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_push_unknown_tenant_sends_nothing(self, push_service):
|
||||
"""Sending to a tenant with no matching subscriptions returns 0."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/consumer",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
},
|
||||
{
|
||||
"endpoint": "https://push.example.com/vocalstar",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "vocalstar",
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
result = await push_service.send_push(
|
||||
"test@example.com", "Title", "Body", tenant_id="unknown-tenant"
|
||||
)
|
||||
assert result == 0
|
||||
mock_webpush.assert_not_called()
|
||||
|
||||
|
||||
class TestNotificationFormatting:
|
||||
"""Tests for blocking and completion notification formatting."""
|
||||
|
||||
@@ -352,7 +750,8 @@ class TestNotificationFormatting:
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [{
|
||||
"endpoint": "https://push.example.com/endpoint",
|
||||
"keys": {"p256dh": "key", "auth": "auth"}
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
}]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
@@ -361,7 +760,7 @@ class TestNotificationFormatting:
|
||||
"job_id": "test-job-123",
|
||||
"user_email": "test@example.com",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song"
|
||||
"title": "Test Song",
|
||||
}
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
@@ -373,7 +772,7 @@ class TestNotificationFormatting:
|
||||
assert payload["title"] == "Review Lyrics"
|
||||
assert "Test Song" in payload["body"]
|
||||
assert "Test Artist" in payload["body"]
|
||||
assert "/review/test-job-123" in payload["url"]
|
||||
assert "/app/jobs#/test-job-123/review" in payload["url"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_blocking_notification_instrumental(self, push_service):
|
||||
@@ -383,7 +782,8 @@ class TestNotificationFormatting:
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [{
|
||||
"endpoint": "https://push.example.com/endpoint",
|
||||
"keys": {"p256dh": "key", "auth": "auth"}
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
}]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
@@ -392,7 +792,7 @@ class TestNotificationFormatting:
|
||||
"job_id": "test-job-123",
|
||||
"user_email": "test@example.com",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song"
|
||||
"title": "Test Song",
|
||||
}
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
@@ -402,7 +802,7 @@ class TestNotificationFormatting:
|
||||
import json
|
||||
payload = json.loads(call_args[1]["data"])
|
||||
assert payload["title"] == "Select Instrumental"
|
||||
assert "/instrumental/test-job-123" in payload["url"]
|
||||
assert "/app/jobs#/test-job-123/instrumental" in payload["url"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_completion_notification(self, push_service):
|
||||
@@ -412,7 +812,8 @@ class TestNotificationFormatting:
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [{
|
||||
"endpoint": "https://push.example.com/endpoint",
|
||||
"keys": {"p256dh": "key", "auth": "auth"}
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
}]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
@@ -421,7 +822,7 @@ class TestNotificationFormatting:
|
||||
"job_id": "test-job-123",
|
||||
"user_email": "test@example.com",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song"
|
||||
"title": "Test Song",
|
||||
}
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
|
||||
@@ -171,12 +171,76 @@ class TestSubscribe:
|
||||
user_email="test@example.com",
|
||||
endpoint="https://push.example.com/endpoint",
|
||||
keys={"p256dh": "key1", "auth": "key2"},
|
||||
device_name="Test Device"
|
||||
device_name="Test Device",
|
||||
tenant_id=None,
|
||||
)
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_successful_subscription_with_tenant_id(self, client, mock_auth_result):
|
||||
"""Subscribe with explicit tenant_id passes it to add_subscription."""
|
||||
async def override_auth():
|
||||
return mock_auth_result
|
||||
|
||||
app.dependency_overrides[require_auth] = override_auth
|
||||
|
||||
try:
|
||||
with patch('backend.api.routes.push.get_settings') as mock_settings, \
|
||||
patch('backend.api.routes.push.get_push_notification_service') as mock_service:
|
||||
mock_settings.return_value.enable_push_notifications = True
|
||||
mock_service.return_value.add_subscription = AsyncMock(return_value=True)
|
||||
|
||||
response = client.post(
|
||||
"/api/push/subscribe",
|
||||
json={
|
||||
"endpoint": "https://push.example.com/endpoint",
|
||||
"keys": {"p256dh": "key1", "auth": "key2"},
|
||||
"device_name": "Test Device",
|
||||
"tenant_id": "vocalstar"
|
||||
}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_service.return_value.add_subscription.assert_called_once_with(
|
||||
user_email="test@example.com",
|
||||
endpoint="https://push.example.com/endpoint",
|
||||
keys={"p256dh": "key1", "auth": "key2"},
|
||||
device_name="Test Device",
|
||||
tenant_id="vocalstar",
|
||||
)
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_subscribe_empty_tenant_id_normalized_to_none(self, client, mock_auth_result):
|
||||
"""Subscribe with empty string tenant_id normalizes to None."""
|
||||
async def override_auth():
|
||||
return mock_auth_result
|
||||
|
||||
app.dependency_overrides[require_auth] = override_auth
|
||||
|
||||
try:
|
||||
with patch('backend.api.routes.push.get_settings') as mock_settings, \
|
||||
patch('backend.api.routes.push.get_push_notification_service') as mock_service:
|
||||
mock_settings.return_value.enable_push_notifications = True
|
||||
mock_service.return_value.add_subscription = AsyncMock(return_value=True)
|
||||
|
||||
response = client.post(
|
||||
"/api/push/subscribe",
|
||||
json={
|
||||
"endpoint": "https://push.example.com/endpoint",
|
||||
"keys": {"p256dh": "key1", "auth": "key2"},
|
||||
"tenant_id": ""
|
||||
}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
call_kwargs = mock_service.return_value.add_subscription.call_args[1]
|
||||
assert call_kwargs["tenant_id"] is None
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestUnsubscribe:
|
||||
"""Tests for POST /api/push/unsubscribe."""
|
||||
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
"""
|
||||
Unit tests for review session backup/restore feature.
|
||||
|
||||
Tests the ReviewSession model, Firestore CRUD methods, and API endpoints.
|
||||
"""
|
||||
import pytest
|
||||
import json
|
||||
import hashlib
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
|
||||
from backend.models.review_session import ReviewSession, ReviewSessionSummary
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def ensure_auth_overrides():
|
||||
"""Ensure auth dependency overrides are set for endpoint tests.
|
||||
|
||||
The global conftest autouse fixture should handle this, but some tests
|
||||
in the broader suite can leave dependency_overrides in a dirty state.
|
||||
This fixture ensures a clean slate for review session endpoint tests.
|
||||
"""
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_auth, require_review_auth
|
||||
|
||||
async def mock_require_auth():
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Test admin token",
|
||||
is_admin=True,
|
||||
user_email="test@example.com",
|
||||
)
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
return (job_id, "full")
|
||||
|
||||
app.dependency_overrides[require_auth] = mock_require_auth
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
|
||||
|
||||
# ============================================
|
||||
# Model Tests
|
||||
# ============================================
|
||||
|
||||
|
||||
class TestReviewSessionSummary:
|
||||
def test_to_dict(self):
|
||||
summary = ReviewSessionSummary(
|
||||
total_segments=10,
|
||||
total_words=100,
|
||||
corrections_made=5,
|
||||
changed_words=[{"original": "hello", "corrected": "hallo", "segment_index": 0}],
|
||||
)
|
||||
d = summary.to_dict()
|
||||
assert d["total_segments"] == 10
|
||||
assert d["corrections_made"] == 5
|
||||
assert len(d["changed_words"]) == 1
|
||||
|
||||
def test_from_dict(self):
|
||||
data = {
|
||||
"total_segments": 15,
|
||||
"total_words": 200,
|
||||
"corrections_made": 8,
|
||||
"changed_words": [],
|
||||
}
|
||||
summary = ReviewSessionSummary.from_dict(data)
|
||||
assert summary.total_segments == 15
|
||||
assert summary.corrections_made == 8
|
||||
|
||||
def test_from_dict_missing_fields(self):
|
||||
summary = ReviewSessionSummary.from_dict({})
|
||||
assert summary.total_segments == 0
|
||||
assert summary.changed_words == []
|
||||
|
||||
|
||||
class TestReviewSession:
|
||||
def test_to_dict_and_from_dict_roundtrip(self):
|
||||
session = ReviewSession(
|
||||
session_id="test-session-1",
|
||||
job_id="job-123",
|
||||
user_email="user@example.com",
|
||||
edit_count=42,
|
||||
trigger="preview",
|
||||
audio_duration_seconds=222.5,
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
data_hash="abc123hash",
|
||||
correction_data_gcs_path="jobs/job-123/review_sessions/test-session-1.json",
|
||||
summary=ReviewSessionSummary(total_segments=10, total_words=100, corrections_made=5),
|
||||
)
|
||||
d = session.to_dict()
|
||||
restored = ReviewSession.from_dict(d)
|
||||
|
||||
assert restored.session_id == "test-session-1"
|
||||
assert restored.job_id == "job-123"
|
||||
assert restored.edit_count == 42
|
||||
assert restored.trigger == "preview"
|
||||
assert restored.audio_duration_seconds == 222.5
|
||||
assert restored.artist == "Test Artist"
|
||||
assert restored.data_hash == "abc123hash"
|
||||
assert restored.summary.total_segments == 10
|
||||
|
||||
def test_from_dict_string_timestamps(self):
|
||||
data = {
|
||||
"session_id": "s1",
|
||||
"created_at": "2026-03-07T12:00:00Z",
|
||||
"updated_at": "2026-03-07T12:15:00Z",
|
||||
}
|
||||
session = ReviewSession.from_dict(data)
|
||||
assert session.created_at.year == 2026
|
||||
assert session.updated_at.minute == 15
|
||||
|
||||
def test_default_values(self):
|
||||
session = ReviewSession()
|
||||
assert session.trigger == "auto"
|
||||
assert session.edit_count == 0
|
||||
assert session.audio_duration_seconds is None
|
||||
assert session.session_id # auto-generated
|
||||
|
||||
|
||||
# ============================================
|
||||
# API Endpoint Tests
|
||||
# ============================================
|
||||
|
||||
|
||||
class TestSaveReviewSessionEndpoint:
|
||||
"""Tests for POST /api/review/{job_id}/sessions"""
|
||||
|
||||
@patch("backend.api.routes.review.StorageService")
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
@patch("backend.api.routes.review.JobManager")
|
||||
def test_save_session_success(self, MockJobManager, MockFirestore, MockStorage, test_client):
|
||||
mock_job = MagicMock(spec=Job)
|
||||
mock_job.artist = "Test Artist"
|
||||
mock_job.title = "Test Song"
|
||||
mock_job.state_data = {"backing_vocals_analysis": {"total_duration_seconds": 180.0}}
|
||||
|
||||
MockJobManager.return_value.get_job.return_value = mock_job
|
||||
MockFirestore.return_value.get_latest_review_session_hash.return_value = None
|
||||
MockStorage.return_value.upload_json.return_value = None
|
||||
MockFirestore.return_value.save_review_session.return_value = "session-id"
|
||||
|
||||
response = test_client.post(
|
||||
"/api/review/job-123/sessions",
|
||||
json={
|
||||
"correction_data": {"corrected_segments": [], "original_segments": []},
|
||||
"edit_count": 5,
|
||||
"trigger": "manual",
|
||||
"summary": {"total_segments": 10, "total_words": 100, "corrections_made": 5},
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "saved"
|
||||
assert "session_id" in data
|
||||
|
||||
@patch("backend.api.routes.review.StorageService")
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
@patch("backend.api.routes.review.JobManager")
|
||||
def test_save_session_deduplication(self, MockJobManager, MockFirestore, MockStorage, test_client):
|
||||
"""Should skip save if data hash matches latest session."""
|
||||
mock_job = MagicMock(spec=Job)
|
||||
mock_job.artist = "Test Artist"
|
||||
mock_job.title = "Test Song"
|
||||
mock_job.state_data = {}
|
||||
|
||||
correction_data = {"corrected_segments": [{"text": "hello"}], "original_segments": []}
|
||||
data_json = json.dumps(correction_data, sort_keys=True, default=str)
|
||||
expected_hash = hashlib.sha256(data_json.encode()).hexdigest()
|
||||
|
||||
MockJobManager.return_value.get_job.return_value = mock_job
|
||||
MockFirestore.return_value.get_latest_review_session_hash.return_value = expected_hash
|
||||
|
||||
response = test_client.post(
|
||||
"/api/review/job-123/sessions",
|
||||
json={"correction_data": correction_data, "edit_count": 5, "trigger": "auto"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "skipped"
|
||||
assert response.json()["reason"] == "identical_data"
|
||||
# GCS upload should NOT have been called
|
||||
MockStorage.return_value.upload_json.assert_not_called()
|
||||
|
||||
@patch("backend.api.routes.review.JobManager")
|
||||
def test_save_session_job_not_found(self, MockJobManager, test_client):
|
||||
MockJobManager.return_value.get_job.return_value = None
|
||||
response = test_client.post(
|
||||
"/api/review/job-123/sessions",
|
||||
json={"correction_data": {"foo": "bar"}, "edit_count": 1},
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
@patch("backend.api.routes.review.JobManager")
|
||||
def test_save_session_missing_correction_data(self, MockJobManager, test_client):
|
||||
mock_job = MagicMock(spec=Job)
|
||||
MockJobManager.return_value.get_job.return_value = mock_job
|
||||
response = test_client.post(
|
||||
"/api/review/job-123/sessions",
|
||||
json={"edit_count": 1},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
class TestListReviewSessionsEndpoint:
|
||||
"""Tests for GET /api/review/{job_id}/sessions"""
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_list_sessions(self, MockFirestore, test_client):
|
||||
session = ReviewSession(
|
||||
session_id="s1",
|
||||
job_id="job-123",
|
||||
user_email="user@test.com",
|
||||
edit_count=10,
|
||||
trigger="auto",
|
||||
artist="Artist",
|
||||
title="Song",
|
||||
)
|
||||
MockFirestore.return_value.list_review_sessions.return_value = [session]
|
||||
|
||||
response = test_client.get("/api/review/job-123/sessions")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["sessions"]) == 1
|
||||
assert data["sessions"][0]["session_id"] == "s1"
|
||||
assert data["sessions"][0]["edit_count"] == 10
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_list_sessions_empty(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.list_review_sessions.return_value = []
|
||||
response = test_client.get("/api/review/job-123/sessions")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["sessions"] == []
|
||||
|
||||
|
||||
class TestGetReviewSessionEndpoint:
|
||||
"""Tests for GET /api/review/{job_id}/sessions/{session_id}"""
|
||||
|
||||
@patch("backend.api.routes.review.StorageService")
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_get_session_with_data(self, MockFirestore, MockStorage, test_client):
|
||||
session = ReviewSession(
|
||||
session_id="s1",
|
||||
job_id="job-123",
|
||||
correction_data_gcs_path="jobs/job-123/review_sessions/s1.json",
|
||||
)
|
||||
MockFirestore.return_value.get_review_session.return_value = session
|
||||
MockStorage.return_value.download_json.return_value = {"corrected_segments": []}
|
||||
|
||||
response = test_client.get("/api/review/job-123/sessions/s1")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["session_id"] == "s1"
|
||||
assert data["correction_data"] == {"corrected_segments": []}
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_get_session_not_found(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.get_review_session.return_value = None
|
||||
response = test_client.get("/api/review/job-123/sessions/nonexistent")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestDeleteReviewSessionEndpoint:
|
||||
"""Tests for DELETE /api/review/{job_id}/sessions/{session_id}"""
|
||||
|
||||
@patch("backend.api.routes.review.StorageService")
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_delete_session(self, MockFirestore, MockStorage, test_client):
|
||||
session = ReviewSession(
|
||||
session_id="s1",
|
||||
job_id="job-123",
|
||||
correction_data_gcs_path="jobs/job-123/review_sessions/s1.json",
|
||||
)
|
||||
MockFirestore.return_value.get_review_session.return_value = session
|
||||
|
||||
response = test_client.delete("/api/review/job-123/sessions/s1")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "deleted"
|
||||
MockStorage.return_value.delete_file.assert_called_once()
|
||||
MockFirestore.return_value.delete_review_session.assert_called_once()
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_delete_session_not_found(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.get_review_session.return_value = None
|
||||
response = test_client.delete("/api/review/job-123/sessions/nonexistent")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestSearchReviewSessionsEndpoint:
|
||||
"""Tests for GET /api/review/sessions/search"""
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_search_sessions(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.search_review_sessions.return_value = [
|
||||
{"session_id": "s1", "job_id": "j1", "artist": "Artist A"},
|
||||
]
|
||||
response = test_client.get("/api/review/sessions/search?q=Artist")
|
||||
assert response.status_code == 200
|
||||
assert len(response.json()["sessions"]) == 1
|
||||
|
||||
@patch("backend.api.routes.review.FirestoreService")
|
||||
def test_search_sessions_empty(self, MockFirestore, test_client):
|
||||
MockFirestore.return_value.search_review_sessions.return_value = []
|
||||
response = test_client.get("/api/review/sessions/search?q=nonexistent")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["sessions"] == []
|
||||
@@ -382,6 +382,27 @@ class TestSummaryEndpoint:
|
||||
reduces payload size for the dashboard polling use case.
|
||||
"""
|
||||
|
||||
def test_summary_projection_includes_visibility_fields(self):
|
||||
"""Verify SUMMARY_FIELD_PATHS includes is_private and visibility_change_in_progress.
|
||||
|
||||
These fields are required for the Change Visibility button on the dashboard.
|
||||
Without them, the button shows incorrect state (always 'Make Private').
|
||||
"""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
paths = FirestoreService.SUMMARY_FIELD_PATHS
|
||||
assert 'is_private' in paths, "is_private must be in summary projection for visibility button"
|
||||
assert 'state_data.visibility_change_in_progress' in paths, \
|
||||
"visibility_change_in_progress must be in summary projection to prevent concurrent changes"
|
||||
|
||||
def test_prune_state_data_keeps_visibility_change_key(self):
|
||||
"""Verify _prune_state_data preserves visibility_change_in_progress."""
|
||||
from backend.api.routes.jobs import _prune_state_data
|
||||
|
||||
data = {'state_data': {'visibility_change_in_progress': True, 'corrected_lyrics': 'strip me'}}
|
||||
result = _prune_state_data(data)
|
||||
assert 'visibility_change_in_progress' in result['state_data']
|
||||
assert 'corrected_lyrics' not in result['state_data']
|
||||
|
||||
def test_prune_state_data_keeps_allowed_keys(self):
|
||||
"""Verify _prune_state_data keeps only dashboard-required keys."""
|
||||
from backend.api.routes.jobs import _prune_state_data
|
||||
@@ -603,3 +624,68 @@ class TestScreensWorkerBackingVocalsAnalysis:
|
||||
analysis = job.state_data.get('backing_vocals_analysis', {})
|
||||
assert analysis.get('recommended_selection') is not None
|
||||
|
||||
|
||||
class TestContentDispositionHeader:
|
||||
"""Tests for Content-Disposition header building in download_file.
|
||||
|
||||
Verifies that filenames with non-latin-1 characters (CJK, Cyrillic, etc.)
|
||||
use RFC 5987 filename*=UTF-8'' encoding instead of crashing.
|
||||
"""
|
||||
|
||||
def _build_content_disposition(self, filename: str) -> str:
|
||||
"""Replicate the Content-Disposition logic from download_file."""
|
||||
from urllib.parse import quote
|
||||
try:
|
||||
filename.encode('latin-1')
|
||||
return f'attachment; filename="{filename}"'
|
||||
except UnicodeEncodeError:
|
||||
ascii_filename = filename.encode('ascii', 'replace').decode('ascii')
|
||||
utf8_filename = quote(filename)
|
||||
return f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{utf8_filename}"
|
||||
|
||||
def test_ascii_filename_uses_simple_header(self):
|
||||
header = self._build_content_disposition("Artist - Song (Final Karaoke).mp4")
|
||||
assert header == 'attachment; filename="Artist - Song (Final Karaoke).mp4"'
|
||||
assert "filename*" not in header
|
||||
|
||||
def test_latin1_accented_filename_uses_simple_header(self):
|
||||
header = self._build_content_disposition("Café - Señorita.mp4")
|
||||
assert header == 'attachment; filename="Café - Señorita.mp4"'
|
||||
assert "filename*" not in header
|
||||
|
||||
def test_chinese_filename_uses_rfc5987(self):
|
||||
header = self._build_content_disposition("周杰倫 - 青花瓷 (Final Karaoke).mp4")
|
||||
assert "filename*=UTF-8''" in header
|
||||
# ASCII fallback should be present
|
||||
assert 'filename="' in header
|
||||
# Should be encodable as latin-1 (the whole header)
|
||||
# The ASCII fallback part is safe; the UTF-8 part is percent-encoded
|
||||
assert "%E5%91%A8" in header # 周 percent-encoded
|
||||
|
||||
def test_japanese_filename_uses_rfc5987(self):
|
||||
header = self._build_content_disposition("宇多田ヒカル - First Love.mp4")
|
||||
assert "filename*=UTF-8''" in header
|
||||
|
||||
def test_korean_filename_uses_rfc5987(self):
|
||||
header = self._build_content_disposition("방탄소년단 - Dynamite.mp4")
|
||||
assert "filename*=UTF-8''" in header
|
||||
|
||||
def test_cyrillic_filename_uses_rfc5987(self):
|
||||
header = self._build_content_disposition("Тату - Нас не догонят.mp4")
|
||||
assert "filename*=UTF-8''" in header
|
||||
|
||||
def test_rfc5987_header_is_latin1_safe(self):
|
||||
"""The entire header string must be encodable as latin-1 for HTTP."""
|
||||
header = self._build_content_disposition("周杰倫 - 青花瓷.mp4")
|
||||
# The header uses percent-encoding for non-ASCII, so it should be ASCII-safe
|
||||
header.encode('latin-1') # Should not raise
|
||||
|
||||
def test_rfc5987_preserves_original_filename(self):
|
||||
"""The UTF-8 encoded filename should decode back to the original."""
|
||||
from urllib.parse import unquote
|
||||
header = self._build_content_disposition("周杰倫 - 青花瓷.mp4")
|
||||
# Extract the filename* value
|
||||
utf8_part = header.split("filename*=UTF-8''")[1]
|
||||
decoded = unquote(utf8_part)
|
||||
assert decoded == "周杰倫 - 青花瓷.mp4"
|
||||
|
||||
@@ -103,8 +103,11 @@ class TestSelectEndpointAppliesOverrides:
|
||||
bg_tasks = Mock(spec=BackgroundTasks)
|
||||
auth_result = Mock()
|
||||
|
||||
# Mock the audio search service
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'):
|
||||
# Mock the audio search service and worker service
|
||||
mock_worker_service = AsyncMock()
|
||||
mock_worker_service.trigger_audio_download_worker.return_value = True
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'), \
|
||||
patch('backend.api.routes.audio_search.get_worker_service', return_value=mock_worker_service):
|
||||
from backend.api.routes.audio_search import select_audio_source
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
@@ -156,7 +159,10 @@ class TestSelectEndpointAppliesOverrides:
|
||||
bg_tasks = Mock(spec=BackgroundTasks)
|
||||
auth_result = Mock()
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'):
|
||||
mock_worker_service = AsyncMock()
|
||||
mock_worker_service.trigger_audio_download_worker.return_value = True
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'), \
|
||||
patch('backend.api.routes.audio_search.get_worker_service', return_value=mock_worker_service):
|
||||
from backend.api.routes.audio_search import select_audio_source
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
@@ -207,7 +213,10 @@ class TestSelectEndpointAppliesOverrides:
|
||||
bg_tasks = Mock(spec=BackgroundTasks)
|
||||
auth_result = Mock()
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'):
|
||||
mock_worker_service = AsyncMock()
|
||||
mock_worker_service.trigger_audio_download_worker.return_value = True
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'), \
|
||||
patch('backend.api.routes.audio_search.get_worker_service', return_value=mock_worker_service):
|
||||
from backend.api.routes.audio_search import select_audio_source
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
|
||||
@@ -448,9 +448,13 @@ def create_from_search_client(mock_job_manager_cfs):
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
mock_worker_service = AsyncMock()
|
||||
mock_worker_service.trigger_audio_download_worker.return_value = True
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.api.routes.jobs.get_worker_service", return_value=mock_worker_service), \
|
||||
patch("backend.api.routes.audio_search._validate_and_prepare_selection"), \
|
||||
patch("backend.api.routes.audio_search._download_audio_and_trigger_workers"), \
|
||||
patch("backend.api.routes.audio_search.extract_request_metadata", return_value={}), \
|
||||
@@ -820,9 +824,13 @@ class TestCreateJobFromSearch:
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
mock_worker_service = AsyncMock()
|
||||
mock_worker_service.trigger_audio_download_worker.return_value = True
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.api.routes.jobs.get_worker_service", return_value=mock_worker_service), \
|
||||
patch("backend.api.routes.audio_search._validate_and_prepare_selection"), \
|
||||
patch("backend.api.routes.audio_search._download_audio_and_trigger_workers"), \
|
||||
patch("backend.api.routes.audio_search.extract_request_metadata", return_value={}), \
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
"""
|
||||
Unit tests for tenant-aware job defaults and distribution overrides.
|
||||
|
||||
Tests that:
|
||||
- Tenant config fields (brand_prefix, dropbox_path, gdrive_folder_id) are applied to jobs
|
||||
- All tenant jobs are forced private
|
||||
- Locked theme overrides user selection
|
||||
- Private tenant jobs use tenant-specific paths (not NonPublished)
|
||||
- Non-tenant private jobs still use NonPublished paths
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from backend.models.tenant import TenantConfig, TenantDefaults, TenantFeatures, TenantBranding, TenantAuth
|
||||
from backend.services.job_defaults_service import (
|
||||
get_effective_distribution_settings,
|
||||
get_effective_distribution_for_job,
|
||||
EffectiveDistributionSettings,
|
||||
)
|
||||
|
||||
|
||||
def _make_tenant_config(**defaults_kwargs) -> TenantConfig:
|
||||
"""Create a TenantConfig with custom defaults for testing."""
|
||||
return TenantConfig(
|
||||
id="vocalstar",
|
||||
name="Vocal Star",
|
||||
subdomain="vocalstar.nomadkaraoke.com",
|
||||
defaults=TenantDefaults(
|
||||
locked_theme="vocalstar",
|
||||
distribution_mode="cloud_only",
|
||||
brand_prefix="VSTAR",
|
||||
dropbox_path="/Karaoke/Vocal-Star",
|
||||
gdrive_folder_id="gdrive-folder-123",
|
||||
**defaults_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _make_job_mock(**kwargs):
|
||||
"""Create a mock job object with the given attributes."""
|
||||
defaults = {
|
||||
"is_private": False,
|
||||
"tenant_id": None,
|
||||
"dropbox_path": None,
|
||||
"gdrive_folder_id": None,
|
||||
"brand_prefix": None,
|
||||
"enable_youtube_upload": False,
|
||||
"discord_webhook_url": None,
|
||||
"youtube_description_template": None,
|
||||
}
|
||||
defaults.update(kwargs)
|
||||
job = MagicMock()
|
||||
for key, value in defaults.items():
|
||||
setattr(job, key, value)
|
||||
return job
|
||||
|
||||
|
||||
class TestApplyTenantOverrides:
|
||||
"""Tests for _apply_tenant_overrides() in file_upload.py."""
|
||||
|
||||
def _get_apply_fn(self):
|
||||
"""Import the function under test."""
|
||||
from backend.api.routes.file_upload import _apply_tenant_overrides
|
||||
return _apply_tenant_overrides
|
||||
|
||||
def test_tenant_defaults_applied_to_distribution(self):
|
||||
"""Tenant brand_prefix, dropbox_path, gdrive_folder_id are applied to distribution settings."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None,
|
||||
gdrive_folder_id=None,
|
||||
discord_webhook_url=None,
|
||||
brand_prefix=None,
|
||||
enable_youtube_upload=True,
|
||||
youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, theme, is_private, yt_upload = apply_fn(
|
||||
dist, tenant_config, "default", False, True
|
||||
)
|
||||
|
||||
assert new_dist.brand_prefix == "VSTAR"
|
||||
assert new_dist.dropbox_path == "/Karaoke/Vocal-Star"
|
||||
assert new_dist.gdrive_folder_id == "gdrive-folder-123"
|
||||
|
||||
def test_tenant_job_forced_private(self):
|
||||
"""All tenant jobs are forced to is_private=True."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
_, _, is_private, _ = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert is_private is True
|
||||
|
||||
def test_tenant_locked_theme_applied(self):
|
||||
"""locked_theme overrides the user's theme selection."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
_, theme, _, _ = apply_fn(dist, tenant_config, "user-selected-theme", False, True)
|
||||
assert theme == "vocalstar"
|
||||
|
||||
def test_tenant_youtube_upload_disabled(self):
|
||||
"""YouTube upload is disabled for tenant jobs."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
_, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert yt_upload is False
|
||||
|
||||
def test_request_values_take_precedence(self):
|
||||
"""Explicit request-level values are not overridden by tenant defaults."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path="/Custom/Path",
|
||||
gdrive_folder_id="custom-folder",
|
||||
discord_webhook_url=None,
|
||||
brand_prefix="CUSTOM",
|
||||
enable_youtube_upload=True,
|
||||
youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert new_dist.brand_prefix == "CUSTOM"
|
||||
assert new_dist.dropbox_path == "/Custom/Path"
|
||||
assert new_dist.gdrive_folder_id == "custom-folder"
|
||||
|
||||
def test_no_tenant_config_passthrough(self):
|
||||
"""When no tenant config, all values pass through unchanged."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path="/Some/Path", gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix="NOMAD", enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, theme, is_private, yt_upload = apply_fn(
|
||||
dist, None, "nomad", False, True
|
||||
)
|
||||
assert new_dist.brand_prefix == "NOMAD"
|
||||
assert new_dist.dropbox_path == "/Some/Path"
|
||||
assert theme == "nomad"
|
||||
assert is_private is False
|
||||
assert yt_upload is True
|
||||
|
||||
def test_partial_tenant_defaults_only_overrides_set_fields(self):
|
||||
"""When tenant config has only some defaults, only those are applied."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
# Only brand_prefix set, no dropbox_path or gdrive_folder_id
|
||||
tenant_config = TenantConfig(
|
||||
id="partial",
|
||||
name="Partial Tenant",
|
||||
subdomain="partial.nomadkaraoke.com",
|
||||
defaults=TenantDefaults(
|
||||
brand_prefix="PART",
|
||||
dropbox_path=None,
|
||||
gdrive_folder_id=None,
|
||||
locked_theme=None,
|
||||
),
|
||||
)
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, theme, is_private, yt_upload = apply_fn(
|
||||
dist, tenant_config, "user-theme", False, True
|
||||
)
|
||||
|
||||
# brand_prefix applied
|
||||
assert new_dist.brand_prefix == "PART"
|
||||
# dropbox/gdrive remain None since tenant has None
|
||||
assert new_dist.dropbox_path is None
|
||||
assert new_dist.gdrive_folder_id is None
|
||||
# No locked_theme, so user theme preserved
|
||||
assert theme == "user-theme"
|
||||
# Still forced private and no YT
|
||||
assert is_private is True
|
||||
assert yt_upload is False
|
||||
|
||||
|
||||
class TestTenantJobDistribution:
|
||||
"""Tests for get_effective_distribution_for_job() with tenant jobs."""
|
||||
|
||||
def test_private_tenant_job_uses_tenant_paths(self):
|
||||
"""Private tenant jobs use their own Dropbox/GDrive paths, not NonPublished."""
|
||||
job = _make_job_mock(
|
||||
is_private=True,
|
||||
tenant_id="vocalstar",
|
||||
dropbox_path="/Karaoke/Vocal-Star",
|
||||
gdrive_folder_id="gdrive-folder-123",
|
||||
brand_prefix="VSTAR",
|
||||
)
|
||||
|
||||
result = get_effective_distribution_for_job(job)
|
||||
|
||||
assert result.dropbox_path == "/Karaoke/Vocal-Star"
|
||||
assert result.gdrive_folder_id == "gdrive-folder-123"
|
||||
assert result.brand_prefix == "VSTAR"
|
||||
assert result.enable_youtube_upload is False
|
||||
|
||||
@patch("backend.services.job_defaults_service.get_settings")
|
||||
def test_non_tenant_private_job_still_uses_nonpublished(self, mock_settings):
|
||||
"""Non-tenant private jobs still get the NonPublished path override."""
|
||||
mock_settings.return_value = MagicMock(
|
||||
default_private_dropbox_path="/Tracks-NonPublished",
|
||||
default_private_brand_prefix="NOMADNP",
|
||||
)
|
||||
|
||||
job = _make_job_mock(
|
||||
is_private=True,
|
||||
tenant_id=None,
|
||||
dropbox_path="/Some/User/Path",
|
||||
brand_prefix="SOMETHING",
|
||||
)
|
||||
|
||||
result = get_effective_distribution_for_job(job)
|
||||
|
||||
assert result.dropbox_path == "/Tracks-NonPublished"
|
||||
assert result.brand_prefix == "NOMADNP"
|
||||
assert result.enable_youtube_upload is False
|
||||
assert result.gdrive_folder_id is None
|
||||
|
||||
def test_non_private_job_uses_own_settings(self):
|
||||
"""Non-private jobs (tenant or not) use their own distribution settings."""
|
||||
job = _make_job_mock(
|
||||
is_private=False,
|
||||
tenant_id="vocalstar",
|
||||
dropbox_path="/Karaoke/Vocal-Star",
|
||||
gdrive_folder_id="gdrive-folder-123",
|
||||
brand_prefix="VSTAR",
|
||||
enable_youtube_upload=False,
|
||||
)
|
||||
|
||||
result = get_effective_distribution_for_job(job)
|
||||
|
||||
assert result.dropbox_path == "/Karaoke/Vocal-Star"
|
||||
assert result.gdrive_folder_id == "gdrive-folder-123"
|
||||
assert result.brand_prefix == "VSTAR"
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
Tests for whitelabel tenant separation (magic link redirect fix, frontend URL, verify response,
|
||||
tenant-scoped tokens).
|
||||
tenant-scoped tokens, push notification isolation).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from unittest.mock import MagicMock, Mock, patch, AsyncMock
|
||||
|
||||
from backend.models.tenant import TenantConfig, TenantAuth, TenantBranding
|
||||
from backend.models.user import VerifyMagicLinkResponse, UserPublic
|
||||
@@ -281,6 +281,46 @@ class TestRequireAuthTenantOverride:
|
||||
assert result.tenant_id == "token-tenant"
|
||||
assert request.state.tenant_id == "token-tenant"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auth_result_with_tenant_id_loads_tenant_config(self):
|
||||
"""When auth_result has tenant_id and tenant_config is missing, it loads the config."""
|
||||
from backend.api.dependencies import require_auth
|
||||
|
||||
request = self._make_request(initial_tenant_id=None)
|
||||
request.state.tenant_config = None
|
||||
|
||||
mock_auth_result = AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.UNLIMITED,
|
||||
remaining_uses=-1,
|
||||
message="ok",
|
||||
tenant_id="vocalstar",
|
||||
)
|
||||
mock_auth_service = MagicMock()
|
||||
mock_auth_service.validate_token_full.return_value = mock_auth_result
|
||||
|
||||
mock_tenant_config = TenantConfig(
|
||||
id="vocalstar",
|
||||
name="Vocal Star",
|
||||
subdomain="vocalstar.nomadkaraoke.com",
|
||||
is_active=True,
|
||||
)
|
||||
mock_tenant_service = MagicMock()
|
||||
mock_tenant_service.get_tenant_config.return_value = mock_tenant_config
|
||||
|
||||
with patch("backend.api.dependencies.get_auth_service", return_value=mock_auth_service), \
|
||||
patch("backend.services.tenant_service.get_tenant_service", return_value=mock_tenant_service):
|
||||
result = await require_auth(
|
||||
request=request,
|
||||
auth_service=mock_auth_service,
|
||||
credentials=MagicMock(credentials="valid-token"),
|
||||
token=None,
|
||||
)
|
||||
|
||||
assert request.state.tenant_id == "vocalstar"
|
||||
assert request.state.tenant_config == mock_tenant_config
|
||||
mock_tenant_service.get_tenant_config.assert_called_once_with("vocalstar")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auth_result_without_tenant_id_leaves_request_state_unchanged(self):
|
||||
"""When auth_result has no tenant_id, request.state.tenant_id is not changed."""
|
||||
@@ -308,3 +348,151 @@ class TestRequireAuthTenantOverride:
|
||||
|
||||
assert result.tenant_id is None
|
||||
assert request.state.tenant_id == "hostname-tenant"
|
||||
|
||||
|
||||
class TestPushNotificationTenantIsolation:
|
||||
"""Tests that push notifications respect tenant boundaries end-to-end.
|
||||
|
||||
These tests verify the full flow from job_manager -> push_notification_service,
|
||||
ensuring that tenant_id is correctly propagated and used for filtering.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def push_service(self):
|
||||
"""Create PushNotificationService with mocked dependencies."""
|
||||
mock_settings = Mock()
|
||||
mock_settings.enable_push_notifications = True
|
||||
mock_settings.max_push_subscriptions_per_user = 5
|
||||
mock_settings.vapid_subject = "mailto:test@example.com"
|
||||
mock_settings.get_secret = Mock(side_effect=lambda x: {
|
||||
"vapid-public-key": "test-public-key",
|
||||
"vapid-private-key": "test-private-key"
|
||||
}.get(x))
|
||||
|
||||
mock_db = Mock()
|
||||
|
||||
with patch('backend.services.push_notification_service.get_settings', return_value=mock_settings):
|
||||
from backend.services.push_notification_service import PushNotificationService
|
||||
service = PushNotificationService(db=mock_db)
|
||||
return service
|
||||
|
||||
def _setup_multi_tenant_user(self, push_service):
|
||||
"""Set up a user with subscriptions across multiple tenants."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"push_subscriptions": [
|
||||
{
|
||||
"endpoint": "https://push.example.com/consumer",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": None,
|
||||
},
|
||||
{
|
||||
"endpoint": "https://push.example.com/vocalstar",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "vocalstar",
|
||||
},
|
||||
{
|
||||
"endpoint": "https://push.example.com/singa",
|
||||
"keys": {"p256dh": "key", "auth": "auth"},
|
||||
"tenant_id": "singa",
|
||||
},
|
||||
]
|
||||
}
|
||||
push_service.db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_job_manager_passes_tenant_id_in_job_dict(self):
|
||||
"""JobManager._send_push_notification includes tenant_id in job dict."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
job = Mock()
|
||||
job.job_id = "job-123"
|
||||
job.user_email = "user@test.com"
|
||||
job.artist = "Artist"
|
||||
job.title = "Song"
|
||||
job.tenant_id = "vocalstar"
|
||||
|
||||
captured_job_dict = {}
|
||||
|
||||
async def capture_completion(job_dict):
|
||||
captured_job_dict.update(job_dict)
|
||||
return 1
|
||||
|
||||
with patch('backend.services.push_notification_service.get_push_notification_service') as mock_get:
|
||||
mock_service = Mock()
|
||||
mock_service.is_enabled.return_value = True
|
||||
mock_service.send_completion_notification = AsyncMock(side_effect=capture_completion)
|
||||
mock_get.return_value = mock_service
|
||||
|
||||
manager = JobManager.__new__(JobManager)
|
||||
manager._send_push_notification(job, "complete")
|
||||
|
||||
# Give the async task a moment to execute
|
||||
import asyncio
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
assert captured_job_dict.get("tenant_id") == "vocalstar"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_consumer_job_never_notifies_tenant_subscriptions(self, push_service):
|
||||
"""A consumer portal job must never trigger notifications on tenant subscriptions."""
|
||||
self._setup_multi_tenant_user(push_service)
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
job = {
|
||||
"job_id": "consumer-job-1",
|
||||
"user_email": "user@test.com",
|
||||
"artist": "Artist",
|
||||
"title": "Song",
|
||||
# No tenant_id = consumer job
|
||||
}
|
||||
|
||||
await push_service.send_completion_notification(job)
|
||||
|
||||
# Should only send to consumer endpoint
|
||||
assert mock_webpush.call_count == 1
|
||||
sent_endpoint = mock_webpush.call_args[1]["subscription_info"]["endpoint"]
|
||||
assert sent_endpoint == "https://push.example.com/consumer"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tenant_job_never_notifies_consumer_subscriptions(self, push_service):
|
||||
"""A tenant job must never trigger notifications on consumer subscriptions."""
|
||||
self._setup_multi_tenant_user(push_service)
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
job = {
|
||||
"job_id": "vocalstar-job-1",
|
||||
"user_email": "user@test.com",
|
||||
"artist": "Artist",
|
||||
"title": "Song",
|
||||
"tenant_id": "vocalstar",
|
||||
}
|
||||
|
||||
await push_service.send_completion_notification(job)
|
||||
|
||||
# Should only send to vocalstar endpoint
|
||||
assert mock_webpush.call_count == 1
|
||||
sent_endpoint = mock_webpush.call_args[1]["subscription_info"]["endpoint"]
|
||||
assert sent_endpoint == "https://push.example.com/vocalstar"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tenant_a_never_notifies_tenant_b(self, push_service):
|
||||
"""Tenant A job must never trigger notifications on Tenant B subscriptions."""
|
||||
self._setup_multi_tenant_user(push_service)
|
||||
|
||||
with patch('backend.services.push_notification_service.webpush') as mock_webpush:
|
||||
job = {
|
||||
"job_id": "singa-job-1",
|
||||
"user_email": "user@test.com",
|
||||
"artist": "Artist",
|
||||
"title": "Song",
|
||||
"tenant_id": "singa",
|
||||
}
|
||||
|
||||
await push_service.send_blocking_notification(job, "lyrics")
|
||||
|
||||
# Should only send to singa endpoint, never vocalstar or consumer
|
||||
assert mock_webpush.call_count == 1
|
||||
sent_endpoint = mock_webpush.call_args[1]["subscription_info"]["endpoint"]
|
||||
assert sent_endpoint == "https://push.example.com/singa"
|
||||
@@ -209,6 +209,39 @@ class TestSanitizationInContext:
|
||||
# Note: The test above with 'é' passes latin-1; smart quotes do not
|
||||
assert can_encode
|
||||
|
||||
def test_content_disposition_cjk_uses_rfc5987(self):
|
||||
"""Verify CJK filenames use RFC 5987 encoding in Content-Disposition.
|
||||
|
||||
Chinese/Japanese/Korean characters can't be encoded in latin-1,
|
||||
so the download endpoint must use filename*=UTF-8'' encoding.
|
||||
"""
|
||||
from urllib.parse import quote
|
||||
|
||||
artist = "周杰倫"
|
||||
title = "青花瓷"
|
||||
|
||||
safe_artist = sanitize_filename(artist) if artist else None
|
||||
safe_title = sanitize_filename(title) if title else None
|
||||
filename = f"{safe_artist} - {safe_title} (Final Karaoke).mp4"
|
||||
|
||||
# CJK characters cannot be encoded as latin-1
|
||||
with pytest.raises(UnicodeEncodeError):
|
||||
filename.encode('latin-1')
|
||||
|
||||
# The download endpoint should fall back to RFC 5987 encoding
|
||||
ascii_filename = filename.encode('ascii', 'replace').decode('ascii')
|
||||
utf8_filename = quote(filename)
|
||||
content_disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{utf8_filename}"
|
||||
|
||||
# ASCII fallback should be safe
|
||||
ascii_filename.encode('latin-1')
|
||||
|
||||
# UTF-8 encoded filename should contain the original characters when decoded
|
||||
from urllib.parse import unquote
|
||||
decoded = unquote(utf8_filename)
|
||||
assert "周杰倫" in decoded
|
||||
assert "青花瓷" in decoded
|
||||
|
||||
def test_google_drive_query_safe(self):
|
||||
"""Verify filenames don't break Google Drive API queries."""
|
||||
base_name = "Artist\u2019s \u201cSong\u201d"
|
||||
|
||||
@@ -809,6 +809,119 @@ class TestVideoWorkerOrchestratorEncoding:
|
||||
mock_storage.download_file.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_encoding_gce_stale_cache_retries(self):
|
||||
"""Test that stale GCE cache (files deleted from GCS) triggers retry with new job ID.
|
||||
|
||||
When admin deletes outputs and re-runs, the GCE worker may return a cached
|
||||
'complete' result but the actual files no longer exist in GCS. The orchestrator
|
||||
should detect this (0 files downloaded) and retry with a suffixed job ID.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path=os.path.join(temp_dir, "title.mov"),
|
||||
karaoke_video_path=os.path.join(temp_dir, "karaoke.mov"),
|
||||
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
|
||||
output_dir=temp_dir,
|
||||
)
|
||||
|
||||
mock_storage = MagicMock()
|
||||
# First call: all downloads fail (404 - stale cache)
|
||||
# Second call: downloads succeed
|
||||
call_count = [0]
|
||||
def download_side_effect(gcs_path, local_path):
|
||||
call_count[0] += 1
|
||||
if call_count[0] <= 4:
|
||||
# First 4 calls fail (stale cache)
|
||||
raise Exception(f"404 No such object: {gcs_path}")
|
||||
else:
|
||||
# Subsequent calls succeed (retry)
|
||||
with open(local_path, 'w') as f:
|
||||
f.write("fake video")
|
||||
|
||||
mock_storage.download_file = MagicMock(side_effect=download_side_effect)
|
||||
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
config,
|
||||
storage=mock_storage,
|
||||
)
|
||||
|
||||
with patch.object(orchestrator, "_get_encoding_backend") as mock_get:
|
||||
from backend.services.encoding_interface import EncodingOutput
|
||||
|
||||
gce_output = EncodingOutput(
|
||||
success=True,
|
||||
lossless_4k_mp4_path="jobs/test-job/finals/output_4k_lossless.mp4",
|
||||
lossy_4k_mp4_path="jobs/test-job/finals/output_4k_lossy.mp4",
|
||||
lossy_720p_mp4_path="jobs/test-job/finals/output_720p.mp4",
|
||||
lossless_mkv_path="jobs/test-job/finals/output_4k.mkv",
|
||||
encoding_time_seconds=0.0, # Instant = cached
|
||||
encoding_backend="gce",
|
||||
)
|
||||
|
||||
mock_backend = MagicMock()
|
||||
mock_backend.name = "gce"
|
||||
# First encode returns stale cache, second returns fresh results
|
||||
mock_backend.encode = AsyncMock(return_value=gce_output)
|
||||
mock_backend._get_service = MagicMock(return_value=MagicMock())
|
||||
mock_get.return_value = mock_backend
|
||||
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
# encode should be called twice: once for stale cache, once for retry
|
||||
assert mock_backend.encode.call_count == 2
|
||||
|
||||
# The retry call should use a different job_id
|
||||
retry_call_args = mock_backend.encode.call_args_list[1]
|
||||
retry_input = retry_call_args[0][0]
|
||||
assert retry_input.options["job_id"].startswith("test-job_retry_")
|
||||
|
||||
# Result should have local paths from the successful retry
|
||||
assert orchestrator.result.final_video is not None
|
||||
assert orchestrator.result.final_video.startswith(temp_dir)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_gce_encoded_files_zero_downloads_raises(self):
|
||||
"""Test that _download_gce_encoded_files raises when zero files download."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path=os.path.join(temp_dir, "title.mov"),
|
||||
karaoke_video_path=os.path.join(temp_dir, "karaoke.mov"),
|
||||
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
|
||||
output_dir=temp_dir,
|
||||
)
|
||||
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.download_file = MagicMock(
|
||||
side_effect=Exception("404 Not Found")
|
||||
)
|
||||
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
config,
|
||||
storage=mock_storage,
|
||||
)
|
||||
|
||||
from backend.services.encoding_interface import EncodingOutput
|
||||
output = EncodingOutput(
|
||||
success=True,
|
||||
lossless_4k_mp4_path="jobs/test-job/finals/out.mp4",
|
||||
lossless_mkv_path="jobs/test-job/finals/out.mkv",
|
||||
lossy_4k_mp4_path="jobs/test-job/finals/out_lossy.mp4",
|
||||
lossy_720p_mp4_path="jobs/test-job/finals/out_720p.mp4",
|
||||
encoding_time_seconds=0.0,
|
||||
encoding_backend="gce",
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="stale"):
|
||||
await orchestrator._download_gce_encoded_files(output)
|
||||
|
||||
|
||||
class TestVideoWorkerOrchestratorOrganization:
|
||||
"""Test organization stage."""
|
||||
|
||||
@@ -923,6 +1036,29 @@ class TestVideoWorkerOrchestratorDistribution:
|
||||
assert orchestrator.result.dropbox_link == "https://dropbox.com/link"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_to_youtube_no_video_file_adds_warning(self):
|
||||
"""Test that YouTube upload adds distribution warning when no video file exists."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_youtube_upload=True,
|
||||
youtube_credentials={"token": "test"},
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
# No video files set on result — all are None
|
||||
|
||||
await orchestrator._upload_to_youtube()
|
||||
|
||||
assert len(orchestrator.result.distribution_warnings) == 1
|
||||
assert "no video file available" in orchestrator.result.distribution_warnings[0].lower()
|
||||
assert orchestrator.result.youtube_url is None
|
||||
|
||||
|
||||
class TestVideoWorkerOrchestratorNotifications:
|
||||
"""Test notifications stage."""
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import os
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from backend.services.flacfetch_client import FlacfetchServiceError
|
||||
from backend.services.youtube_download_service import (
|
||||
YouTubeDownloadService,
|
||||
YouTubeDownloadError,
|
||||
@@ -375,3 +376,82 @@ class TestYouTubeDownloadServiceIntegration:
|
||||
# Should contain artist and title parts
|
||||
assert 'Artist' in output_filename
|
||||
assert 'Title' in output_filename
|
||||
|
||||
|
||||
class TestCheckAvailability:
|
||||
"""Tests for YouTubeDownloadService.check_availability()."""
|
||||
|
||||
def setup_method(self):
|
||||
"""Reset singleton before each test."""
|
||||
reset_youtube_download_service()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_result_when_available(self):
|
||||
"""Should return availability result for available video."""
|
||||
mock_client = AsyncMock()
|
||||
mock_client.check_youtube = AsyncMock(return_value={
|
||||
"available": True,
|
||||
"video_id": "dQw4w9WgXcQ",
|
||||
"title": "Test Video",
|
||||
})
|
||||
|
||||
with patch("backend.services.youtube_download_service.get_flacfetch_client", return_value=mock_client):
|
||||
service = YouTubeDownloadService()
|
||||
result = await service.check_availability("https://youtube.com/watch?v=dQw4w9WgXcQ")
|
||||
|
||||
assert result is not None
|
||||
assert result["available"] is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_result_when_geo_restricted(self):
|
||||
"""Should return availability result for geo-restricted video."""
|
||||
mock_client = AsyncMock()
|
||||
mock_client.check_youtube = AsyncMock(return_value={
|
||||
"available": False,
|
||||
"video_id": "-yV25PrHglw",
|
||||
"is_geo_restricted": True,
|
||||
"error": "Not available in your region",
|
||||
})
|
||||
|
||||
with patch("backend.services.youtube_download_service.get_flacfetch_client", return_value=mock_client):
|
||||
service = YouTubeDownloadService()
|
||||
result = await service.check_availability("https://youtube.com/watch?v=-yV25PrHglw")
|
||||
|
||||
assert result is not None
|
||||
assert result["available"] is False
|
||||
assert result["is_geo_restricted"] is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_none_when_remote_not_configured(self):
|
||||
"""Should return None when no remote flacfetch configured."""
|
||||
with patch("backend.services.youtube_download_service.get_flacfetch_client", return_value=None):
|
||||
service = YouTubeDownloadService()
|
||||
result = await service.check_availability("https://youtube.com/watch?v=dQw4w9WgXcQ")
|
||||
|
||||
assert result is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_none_on_network_error(self):
|
||||
"""Should return None on network error (graceful degradation)."""
|
||||
mock_client = AsyncMock()
|
||||
mock_client.check_youtube = AsyncMock(
|
||||
side_effect=FlacfetchServiceError("Connection refused")
|
||||
)
|
||||
|
||||
with patch("backend.services.youtube_download_service.get_flacfetch_client", return_value=mock_client):
|
||||
service = YouTubeDownloadService()
|
||||
result = await service.check_availability("https://youtube.com/watch?v=dQw4w9WgXcQ")
|
||||
|
||||
assert result is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_none_for_invalid_url(self):
|
||||
"""Should return None for URLs that don't parse as YouTube."""
|
||||
mock_client = AsyncMock()
|
||||
|
||||
with patch("backend.services.youtube_download_service.get_flacfetch_client", return_value=mock_client):
|
||||
service = YouTubeDownloadService()
|
||||
result = await service.check_availability("https://not-youtube.com/video")
|
||||
|
||||
assert result is None
|
||||
mock_client.check_youtube.assert_not_called()
|
||||
@@ -0,0 +1,363 @@
|
||||
"""
|
||||
Audio download worker.
|
||||
|
||||
Downloads audio from the selected source (Spotify, YouTube, RED, OPS) and
|
||||
triggers audio separation + lyrics transcription workers.
|
||||
|
||||
This runs as a Cloud Run Job to avoid the instance termination issue where
|
||||
Cloud Run would shut down instances mid-download when using BackgroundTasks.
|
||||
The download can take 30s-5min depending on the source.
|
||||
|
||||
Flow:
|
||||
1. Read job from Firestore to get download params
|
||||
2. Download audio via flacfetch (Spotify/RED/OPS) or YouTube service
|
||||
3. Upload to GCS at uploads/{job_id}/audio/
|
||||
4. Update Firestore with input_media_gcs_path
|
||||
5. Transition job from DOWNLOADING_AUDIO to DOWNLOADING
|
||||
6. Trigger audio separation + lyrics transcription workers
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _extract_gcs_path(filepath: str) -> str:
|
||||
"""Extract relative GCS path from a full gs:// URL or path."""
|
||||
bucket_prefix = "gs://karaoke-gen-storage-nomadkaraoke/"
|
||||
if filepath.startswith(bucket_prefix):
|
||||
return filepath[len(bucket_prefix):]
|
||||
# Also handle the older bucket name
|
||||
bucket_prefix_alt = "gs://karaoke-gen-storage/"
|
||||
if filepath.startswith(bucket_prefix_alt):
|
||||
return filepath[len(bucket_prefix_alt):]
|
||||
# Check for any gs:// prefix
|
||||
if filepath.startswith("gs://"):
|
||||
parts = filepath.split("/", 3)
|
||||
if len(parts) == 2:
|
||||
return parts[1]
|
||||
return filepath
|
||||
|
||||
|
||||
async def process_audio_download(job_id: str) -> bool:
|
||||
"""
|
||||
Download audio for a job and trigger processing workers.
|
||||
|
||||
This is the main entry point, called by the Cloud Run Job CLI.
|
||||
|
||||
Args:
|
||||
job_id: Job ID to process
|
||||
|
||||
Returns:
|
||||
True if download and worker triggers succeeded, False otherwise
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage_service = StorageService()
|
||||
|
||||
try:
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.error(f"[job:{job_id}] Job not found")
|
||||
return False
|
||||
|
||||
# Validate job is in correct state
|
||||
if job.status not in (JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED):
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Unexpected status {job.status}, expected DOWNLOADING_AUDIO"
|
||||
)
|
||||
# Still proceed if there's download params - this handles retry cases
|
||||
if not (job.source_name and job.source_id):
|
||||
logger.error(f"[job:{job_id}] No download params available, aborting")
|
||||
return False
|
||||
|
||||
# Get download params from job
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
selection_index = job.state_data.get('selected_audio_index')
|
||||
remote_search_id = job.state_data.get('remote_search_id')
|
||||
|
||||
if selection_index is not None and search_results:
|
||||
selected = search_results[selection_index]
|
||||
source_name = selected.get('provider')
|
||||
source_id = selected.get('source_id')
|
||||
target_file = selected.get('target_file')
|
||||
download_url = selected.get('url')
|
||||
elif job.source_name and job.source_id:
|
||||
# Fallback to job-level params (set by _validate_and_prepare_selection)
|
||||
source_name = job.source_name
|
||||
source_id = job.source_id
|
||||
target_file = job.target_file
|
||||
download_url = job.download_url
|
||||
selected = {'artist': job.artist, 'title': job.title}
|
||||
else:
|
||||
raise DownloadError("No audio source selection found in job data")
|
||||
|
||||
logger.info(
|
||||
f"[job:{job_id}] Starting audio download: "
|
||||
f"source={source_name}, id={source_id}"
|
||||
)
|
||||
|
||||
# Route to appropriate download handler
|
||||
audio_gcs_path, filename = await _download_audio(
|
||||
job_id=job_id,
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
remote_search_id=remote_search_id,
|
||||
selection_index=selection_index,
|
||||
selected=selected,
|
||||
storage_service=storage_service,
|
||||
)
|
||||
|
||||
# Update job with GCS path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': filename,
|
||||
})
|
||||
|
||||
# Transition from DOWNLOADING_AUDIO to DOWNLOADING
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=15,
|
||||
message="Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
# Trigger audio separation and lyrics workers
|
||||
worker_service = get_worker_service()
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
logger.info(f"[job:{job_id}] Audio download complete, workers triggered")
|
||||
return True
|
||||
|
||||
except (DownloadError, FlacfetchServiceError) as e:
|
||||
logger.error(f"[job:{job_id}] Download failed: {e}")
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Download failed: {e}", exc_info=True)
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def _download_audio(
|
||||
job_id: str,
|
||||
source_name: str,
|
||||
source_id: str,
|
||||
target_file: str | None,
|
||||
download_url: str | None,
|
||||
remote_search_id: str | None,
|
||||
selection_index: int | None,
|
||||
selected: dict,
|
||||
storage_service: StorageService,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
Download audio from the selected source and return (gcs_path, filename).
|
||||
|
||||
Routes to the appropriate download handler based on source type.
|
||||
"""
|
||||
if source_name == 'YouTube':
|
||||
return await _download_youtube(job_id, source_id, download_url, selected)
|
||||
|
||||
elif source_name in ('RED', 'OPS'):
|
||||
return await _download_torrent(
|
||||
job_id, source_name, source_id, target_file,
|
||||
download_url, remote_search_id, selection_index
|
||||
)
|
||||
|
||||
elif source_name == 'Spotify':
|
||||
return await _download_spotify(
|
||||
job_id, source_id, download_url
|
||||
)
|
||||
|
||||
else:
|
||||
raise DownloadError(f"Unsupported audio source: {source_name}")
|
||||
|
||||
|
||||
async def _download_youtube(
|
||||
job_id: str,
|
||||
source_id: str,
|
||||
download_url: str | None,
|
||||
selected: dict,
|
||||
) -> tuple[str, str]:
|
||||
"""Download from YouTube via YouTubeDownloadService."""
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
|
||||
youtube_service = get_youtube_download_service()
|
||||
|
||||
if not source_id and download_url:
|
||||
source_id = youtube_service._extract_video_id(download_url)
|
||||
|
||||
if not source_id:
|
||||
raise DownloadError("No video ID available for YouTube download")
|
||||
|
||||
logger.info(f"[job:{job_id}] YouTube download: video_id={source_id}")
|
||||
|
||||
try:
|
||||
audio_gcs_path = await youtube_service.download_by_id(
|
||||
video_id=source_id,
|
||||
job_id=job_id,
|
||||
artist=selected.get('artist'),
|
||||
title=selected.get('title'),
|
||||
)
|
||||
filename = os.path.basename(audio_gcs_path)
|
||||
return audio_gcs_path, filename
|
||||
except YouTubeDownloadError as e:
|
||||
raise DownloadError(f"YouTube download failed: {e}")
|
||||
|
||||
|
||||
async def _download_torrent(
|
||||
job_id: str,
|
||||
source_name: str,
|
||||
source_id: str | None,
|
||||
target_file: str | None,
|
||||
download_url: str | None,
|
||||
remote_search_id: str | None,
|
||||
selection_index: int | None,
|
||||
) -> tuple[str, str]:
|
||||
"""Download from torrent source (RED/OPS) via flacfetch."""
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
raise DownloadError(
|
||||
f"Cannot download from {source_name} without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
)
|
||||
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
|
||||
if source_id:
|
||||
logger.info(f"[job:{job_id}] Torrent download: {source_name} ID={source_id}")
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
else:
|
||||
if not remote_search_id:
|
||||
raise DownloadError(
|
||||
f"No source_id or remote_search_id available for {source_name} download"
|
||||
)
|
||||
logger.info(f"[job:{job_id}] Torrent download via search-based download")
|
||||
download_id = await flacfetch_client.download(
|
||||
search_id=remote_search_id,
|
||||
result_index=selection_index,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
logger.info(f"[job:{job_id}] Torrent download complete: {audio_gcs_path}")
|
||||
return audio_gcs_path, filename
|
||||
|
||||
|
||||
async def _download_spotify(
|
||||
job_id: str,
|
||||
source_id: str,
|
||||
download_url: str | None,
|
||||
) -> tuple[str, str]:
|
||||
"""Download from Spotify via flacfetch."""
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
raise DownloadError(
|
||||
"Cannot download from Spotify without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
)
|
||||
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
logger.info(f"[job:{job_id}] Spotify download: source_id={source_id}")
|
||||
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
source_name="Spotify",
|
||||
source_id=source_id,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
logger.info(f"[job:{job_id}] Spotify download complete: {audio_gcs_path}")
|
||||
return audio_gcs_path, filename
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
CLI entry point for running audio download worker as a Cloud Run Job.
|
||||
|
||||
Usage:
|
||||
python -m backend.workers.audio_download_worker --job-id abc123
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Audio download 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 audio download worker for job {job_id}")
|
||||
|
||||
try:
|
||||
success = asyncio.run(process_audio_download(job_id))
|
||||
if success:
|
||||
logger.info(f"Audio download completed successfully for job {job_id}")
|
||||
sys.exit(0)
|
||||
else:
|
||||
logger.error(f"Audio download failed for job {job_id}")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Audio download worker crashed: {e}", exc_info=True)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -190,15 +190,36 @@ async def generate_screens(job_id: str) -> bool:
|
||||
job_log.info("Transcoding review audio to OGG Opus...")
|
||||
await _transcode_review_audio(job_id, job_manager, job_log)
|
||||
|
||||
# Transition to AWAITING_REVIEW (combined lyrics + instrumental review)
|
||||
# Human must review lyrics AND select instrumental before video can be rendered
|
||||
logger.info(f"[job:{job_id}] Screens generated, awaiting combined review")
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_REVIEW,
|
||||
progress=55,
|
||||
message="Ready for review. Please review lyrics and select your instrumental."
|
||||
)
|
||||
# Check if this is an admin screen regeneration (restore original status)
|
||||
state_data = job_manager.get_job(job_id).state_data or {}
|
||||
regen_restore_status = state_data.get('regen_restore_status')
|
||||
|
||||
if regen_restore_status:
|
||||
# Admin/visibility-change regen: restore target status instead of going to review
|
||||
logger.info(f"[job:{job_id}] Screen regen complete, restoring status to {regen_restore_status}")
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD as _DEL
|
||||
db = job_manager.firestore.db
|
||||
db.collection("jobs").document(job_id).update({
|
||||
"status": regen_restore_status,
|
||||
"state_data.regen_restore_status": _DEL,
|
||||
})
|
||||
|
||||
# If restoring to review_complete, trigger render worker to continue pipeline
|
||||
# (used by visibility change: private -> public)
|
||||
if regen_restore_status == JobStatus.REVIEW_COMPLETE.value:
|
||||
logger.info(f"[job:{job_id}] Triggering render worker for visibility change pipeline")
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
else:
|
||||
# Normal flow: transition to combined review
|
||||
logger.info(f"[job:{job_id}] Screens generated, awaiting combined review")
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_REVIEW,
|
||||
progress=55,
|
||||
message="Ready for review. Please review lyrics and select your instrumental."
|
||||
)
|
||||
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
|
||||
@@ -349,6 +349,8 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
}
|
||||
if result.distribution_warnings:
|
||||
state_update['distribution_warnings'] = result.distribution_warnings
|
||||
# Clear visibility change guard flag if set (from visibility change flow)
|
||||
state_update.pop('visibility_change_in_progress', None)
|
||||
job_manager.update_job(job_id, {'state_data': state_update})
|
||||
|
||||
# Send Pushbullet alert if any distribution uploads failed
|
||||
@@ -362,14 +364,27 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
)
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
duration = time.time() - start_time
|
||||
completion_metadata = {
|
||||
"action": "completed",
|
||||
"brand_code": result.brand_code,
|
||||
"youtube_url": result.youtube_url,
|
||||
"youtube_upload_queued": result.youtube_upload_queued,
|
||||
"dropbox_link": result.dropbox_link,
|
||||
"gdrive_file_ids": result.gdrive_files,
|
||||
"edit_count": getattr(job, 'edit_count', 0),
|
||||
"duration_seconds": round(duration, 1),
|
||||
}
|
||||
if result.distribution_warnings:
|
||||
completion_metadata["distribution_warnings"] = result.distribution_warnings
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.COMPLETE,
|
||||
progress=100,
|
||||
message="Karaoke generation complete!"
|
||||
message="Karaoke generation complete!",
|
||||
timeline_metadata=completion_metadata,
|
||||
)
|
||||
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("brand_code", result.brand_code or '')
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=video orchestrator=true status=success duration={duration:.1f}s")
|
||||
@@ -410,6 +425,158 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
logger.debug(f"Cleaned up temp directory: {temp_dir}")
|
||||
|
||||
|
||||
async def redistribute_video(job_id: str) -> bool:
|
||||
"""
|
||||
Redistribute existing finals for a completed job (no re-encoding).
|
||||
|
||||
Used by visibility change (public -> private) to redistribute existing
|
||||
encoded files to a different destination without re-rendering or re-encoding.
|
||||
|
||||
Downloads finals from GCS, runs only organization + distribution stages.
|
||||
"""
|
||||
from backend.workers.video_worker_orchestrator import (
|
||||
VideoWorkerOrchestrator,
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
job_log = create_job_logger(job_id, "video-redistribute")
|
||||
|
||||
logger.info(f"[job:{job_id}] WORKER_START worker=video-redistribute")
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.error(f"[job:{job_id}] Job not found for redistribution")
|
||||
return False
|
||||
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_redist_{job_id}_")
|
||||
|
||||
try:
|
||||
# Download existing finals from GCS by listing the finals folder
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
|
||||
downloaded_files = {}
|
||||
blobs = storage.list_files(f"jobs/{job_id}/finals/")
|
||||
for blob_name in blobs:
|
||||
filename = os.path.basename(blob_name)
|
||||
if not filename:
|
||||
continue
|
||||
local_path = os.path.join(temp_dir, filename)
|
||||
try:
|
||||
storage.download_file(blob_name, local_path)
|
||||
downloaded_files[filename] = local_path
|
||||
job_log.info(f"Downloaded {filename} from GCS")
|
||||
except Exception as e:
|
||||
job_log.warning(f"Could not download {filename}: {e}")
|
||||
|
||||
# Also download CDG/TXT packages if they exist
|
||||
package_blobs = storage.list_files(f"jobs/{job_id}/packages/")
|
||||
for blob_name in package_blobs:
|
||||
filename = os.path.basename(blob_name)
|
||||
if not filename:
|
||||
continue
|
||||
local_path = os.path.join(temp_dir, filename)
|
||||
try:
|
||||
storage.download_file(blob_name, local_path)
|
||||
downloaded_files[filename] = local_path
|
||||
job_log.info(f"Downloaded package {filename} from GCS")
|
||||
except Exception as e:
|
||||
job_log.warning(f"Could not download package {filename}: {e}")
|
||||
|
||||
if not downloaded_files:
|
||||
raise RuntimeError("No finals files found in GCS for redistribution")
|
||||
|
||||
# Get effective distribution settings for the (now-updated) job
|
||||
# Re-read job since is_private was just toggled
|
||||
job = job_manager.get_job(job_id)
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
# Load YouTube credentials if needed
|
||||
youtube_credentials = None
|
||||
if dist.enable_youtube_upload:
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
youtube_credentials = youtube_service.get_credentials_dict()
|
||||
|
||||
# Create a minimal orchestrator config for distribution only
|
||||
config = OrchestratorConfig(
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
# Input files - not needed for distribution, but required by dataclass
|
||||
title_video_path="",
|
||||
karaoke_video_path="",
|
||||
instrumental_audio_path="",
|
||||
output_dir=temp_dir,
|
||||
# Distribution settings
|
||||
enable_youtube_upload=dist.enable_youtube_upload,
|
||||
brand_prefix=dist.brand_prefix,
|
||||
discord_webhook_url=dist.discord_webhook_url,
|
||||
youtube_credentials=youtube_credentials,
|
||||
youtube_description_template=dist.youtube_description,
|
||||
dropbox_path=dist.dropbox_path,
|
||||
gdrive_folder_id=dist.gdrive_folder_id,
|
||||
enable_cdg=getattr(job, 'enable_cdg', False),
|
||||
enable_txt=getattr(job, 'enable_txt', False),
|
||||
)
|
||||
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
config=config,
|
||||
job_manager=job_manager,
|
||||
storage=storage,
|
||||
job_logger=job_log,
|
||||
)
|
||||
|
||||
# Map downloaded files to orchestrator result attributes by filename patterns
|
||||
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
|
||||
|
||||
# Run only organization + distribution + notifications
|
||||
await orchestrator._run_organization()
|
||||
await orchestrator._run_distribution()
|
||||
await orchestrator._run_notifications()
|
||||
|
||||
# Update job state_data with new distribution results
|
||||
state_update = dict(job.state_data or {})
|
||||
state_update['brand_code'] = orchestrator.result.brand_code
|
||||
state_update['youtube_url'] = orchestrator.result.youtube_url
|
||||
state_update['dropbox_link'] = orchestrator.result.dropbox_link
|
||||
state_update['gdrive_files'] = orchestrator.result.gdrive_files
|
||||
state_update.pop('visibility_change_in_progress', None)
|
||||
|
||||
job_manager.update_job(job_id, {
|
||||
'state_data': state_update,
|
||||
'outputs_deleted_at': None,
|
||||
'outputs_deleted_by': None,
|
||||
})
|
||||
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=video-redistribute status=success")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] WORKER_END worker=video-redistribute status=error error={e}")
|
||||
return False
|
||||
|
||||
finally:
|
||||
if os.path.exists(temp_dir):
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
|
||||
async def generate_video(job_id: str) -> bool:
|
||||
"""
|
||||
Generate final karaoke videos.
|
||||
@@ -705,14 +872,24 @@ async def generate_video_legacy(job_id: str) -> bool:
|
||||
})
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
duration = time.time() - start_time
|
||||
completion_metadata = {
|
||||
"action": "completed",
|
||||
"brand_code": result.get('brand_code'),
|
||||
"youtube_url": result.get('youtube_url'),
|
||||
"dropbox_link": result.get('dropbox_link'),
|
||||
"gdrive_file_ids": result.get('gdrive_files'),
|
||||
"edit_count": getattr(job, 'edit_count', 0),
|
||||
"duration_seconds": round(duration, 1),
|
||||
}
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.COMPLETE,
|
||||
progress=100,
|
||||
message="Karaoke generation complete!"
|
||||
message="Karaoke generation complete!",
|
||||
timeline_metadata=completion_metadata,
|
||||
)
|
||||
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("brand_code", result.get('brand_code', ''))
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=video status=success duration={duration:.1f}s")
|
||||
|
||||
@@ -426,7 +426,35 @@ class VideoWorkerOrchestrator:
|
||||
# For GCE encoding, download the encoded files from GCS to local directory
|
||||
# This is required for YouTube upload and other local file operations
|
||||
if encoding_backend.name == "gce" and self.storage:
|
||||
await self._download_gce_encoded_files(output)
|
||||
try:
|
||||
await self._download_gce_encoded_files(output)
|
||||
except RuntimeError as e:
|
||||
if "stale" in str(e).lower():
|
||||
# GCE worker returned cached result but files were deleted from GCS.
|
||||
# Re-encode with a suffixed job ID so GCE treats it as a new job.
|
||||
import uuid
|
||||
retry_suffix = uuid.uuid4().hex[:8]
|
||||
retry_job_id = f"{self.config.job_id}_retry_{retry_suffix}"
|
||||
self.job_log.warning(
|
||||
f"Stale GCE cache detected, re-encoding as {retry_job_id}: {e}"
|
||||
)
|
||||
|
||||
# Update the encoding input with the retry job ID
|
||||
encoding_input.options["job_id"] = retry_job_id
|
||||
|
||||
output = await encoding_backend.encode(encoding_input)
|
||||
if not output.success:
|
||||
raise Exception(f"Encoding failed on retry: {output.error_message}")
|
||||
|
||||
self.result.final_video = output.lossless_4k_mp4_path
|
||||
self.result.final_video_mkv = output.lossless_mkv_path
|
||||
self.result.final_video_lossy = output.lossy_4k_mp4_path
|
||||
self.result.final_video_720p = output.lossy_720p_mp4_path
|
||||
self.result.encoding_time_seconds = output.encoding_time_seconds
|
||||
|
||||
await self._download_gce_encoded_files(output)
|
||||
else:
|
||||
raise
|
||||
|
||||
self.job_log.info(f"Encoding complete ({encoding_backend.name}) in {output.encoding_time_seconds:.1f}s")
|
||||
|
||||
@@ -480,6 +508,15 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
self.job_log.info(f"Downloaded {downloaded_count} encoded files from GCS")
|
||||
|
||||
# If zero files were downloaded, the GCE cache was stale (files deleted from GCS
|
||||
# but GCE worker still reports job as "complete"). This happens when admin deletes
|
||||
# outputs then re-runs the video worker. Raise to trigger re-encoding.
|
||||
if downloaded_count == 0:
|
||||
raise RuntimeError(
|
||||
"GCE encoding returned cached result but all output files are missing from GCS. "
|
||||
"The GCE worker's job cache is stale — clearing it and retrying."
|
||||
)
|
||||
|
||||
async def _run_organization(self):
|
||||
"""Run the organization stage (brand code generation)."""
|
||||
self.job_log.info("Starting organization stage")
|
||||
@@ -573,7 +610,9 @@ class VideoWorkerOrchestrator:
|
||||
video_to_upload = self.result.final_video_lossy
|
||||
|
||||
if not video_to_upload:
|
||||
self.job_log.warning("No video file available for YouTube upload")
|
||||
warning = "YouTube upload skipped: no video file available on disk"
|
||||
self.job_log.warning(warning)
|
||||
self.result.distribution_warnings.append(warning)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -599,7 +638,7 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
if video_url:
|
||||
self.result.youtube_url = video_url
|
||||
self.job_log.info(f"Uploaded to YouTube: {video_url}")
|
||||
self.job_log.info(f"Uploaded to YouTube: {video_url} (video_id={video_id})")
|
||||
|
||||
# Record upload in pending buffer (bridges ~7min GCP monitoring delay)
|
||||
try:
|
||||
@@ -676,7 +715,7 @@ class VideoWorkerOrchestrator:
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"Failed to create Dropbox sharing link: {e}")
|
||||
|
||||
self.job_log.info("Dropbox upload complete")
|
||||
self.job_log.info(f"Dropbox upload complete: {remote_folder}")
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Dropbox upload failed: {e}")
|
||||
@@ -713,7 +752,7 @@ class VideoWorkerOrchestrator:
|
||||
)
|
||||
|
||||
self.result.gdrive_files = uploaded
|
||||
self.job_log.info(f"Google Drive upload complete: {len(uploaded)} files")
|
||||
self.job_log.info(f"Google Drive upload complete: {len(uploaded)} files (ids={uploaded})")
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Google Drive upload failed: {e}")
|
||||
|
||||
+127
@@ -156,6 +156,37 @@ Query parameters:
|
||||
DELETE /api/jobs/{job_id}
|
||||
```
|
||||
|
||||
#### Change Visibility
|
||||
|
||||
Toggle a completed job between public and private. Only the job owner or admin can use this.
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/change-visibility
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"target_visibility": "private" // or "public"
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"job_id": "abc123",
|
||||
"message": "Job changed to private. Outputs redistributed to private destination.",
|
||||
"previous_visibility": "public",
|
||||
"new_visibility": "private",
|
||||
"reprocessing_required": false
|
||||
}
|
||||
```
|
||||
|
||||
**Two flows depending on direction:**
|
||||
- **Public → Private**: Fast (~1-2 min). Deletes distributed outputs (YouTube/Dropbox/GDrive), keeps GCS finals, redistributes to private destination.
|
||||
- **Private → Public**: Slow (~15-30 min). Clears custom styles, resets to Nomad theme, regenerates screens, re-renders and re-encodes video.
|
||||
|
||||
**Validation:** Job must be `complete`, not a tenant job, not already at target visibility, and no concurrent visibility change in progress.
|
||||
|
||||
### Review
|
||||
|
||||
The combined review flow allows users to review lyrics AND select instrumental track in a single session.
|
||||
@@ -264,6 +295,43 @@ Error (duration mismatch):
|
||||
}
|
||||
```
|
||||
|
||||
#### Edit Completed Track
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/edit
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "Updated Artist", // optional, only if changing
|
||||
"title": "Updated Title" // optional, only if changing
|
||||
}
|
||||
```
|
||||
|
||||
Reopens a completed track for editing. Cleans up all distributed outputs (YouTube, Dropbox, GDrive, GCS finals), recycles the brand code, and resets the job to `awaiting_review`. A new review token is issued automatically. No additional credits consumed.
|
||||
|
||||
If `artist` or `title` are provided and differ from current values, title/end screens are deleted and the screens worker is triggered to regenerate them in the background.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"job_id": "abc123",
|
||||
"message": "Track reopened for editing. Previous outputs have been removed.",
|
||||
"review_url": "/app/jobs#/abc123/review",
|
||||
"review_token": "...",
|
||||
"metadata_updated": true,
|
||||
"cleanup_results": {
|
||||
"youtube": {"status": "success", "video_id": "xyz"},
|
||||
"dropbox": {"status": "success", "path": "/Karaoke/..."},
|
||||
"gdrive": {"status": "success"},
|
||||
"gcs_finals": {"status": "success", "deleted_count": 4},
|
||||
"brand_code": {"status": "recycled", "code": "NOMAD-1234"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Requirements:** Job must be in `complete` state with `outputs_deleted_at` not set. User must own the job or be admin.
|
||||
|
||||
#### Get Style Upload URLs
|
||||
|
||||
```http
|
||||
@@ -373,6 +441,65 @@ Content-Type: application/json
|
||||
|
||||
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
|
||||
|
||||
#### Review Sessions
|
||||
|
||||
Server-side backup/restore of lyrics review editing sessions. Correction data is stored in GCS; metadata in Firestore subcollection `jobs/{job_id}/review_sessions/{session_id}`.
|
||||
|
||||
##### Save Review Session
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/sessions
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"correction_data": { "corrected_segments": [...], "original_segments": [...] },
|
||||
"edit_count": 5,
|
||||
"trigger": "auto", // "auto" | "preview" | "manual"
|
||||
"summary": {
|
||||
"total_segments": 10,
|
||||
"total_words": 100,
|
||||
"corrections_made": 5,
|
||||
"changed_words": [{"original": "hello", "corrected": "hallo", "segment_index": 0}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Deduplicates via SHA-256 hash of correction_data. Returns `{"status": "skipped", "reason": "identical_data"}` if data hasn't changed since last save.
|
||||
|
||||
Auth: Review token (same as correction data access).
|
||||
|
||||
##### List Review Sessions
|
||||
|
||||
```http
|
||||
GET /api/review/{job_id}/sessions
|
||||
```
|
||||
|
||||
Returns session metadata (no correction_data). Ordered by most recent first.
|
||||
|
||||
##### Get Review Session
|
||||
|
||||
```http
|
||||
GET /api/review/{job_id}/sessions/{session_id}
|
||||
```
|
||||
|
||||
Returns full session including correction_data downloaded from GCS.
|
||||
|
||||
##### Delete Review Session
|
||||
|
||||
```http
|
||||
DELETE /api/review/{job_id}/sessions/{session_id}
|
||||
```
|
||||
|
||||
Deletes both GCS data and Firestore metadata.
|
||||
|
||||
##### Search Review Sessions (Cross-Job)
|
||||
|
||||
```http
|
||||
GET /api/review/sessions/search?q=artist+name&limit=20
|
||||
```
|
||||
|
||||
Searches across all jobs. Requires admin auth. Matches against artist, title, and job_id fields.
|
||||
|
||||
### Instrumental Selection (Finalise-Only Jobs)
|
||||
|
||||
For finalise-only jobs (where audio prep was done externally), instrumental selection is handled separately:
|
||||
|
||||
@@ -302,6 +302,7 @@ Audio and lyrics workers run as **Cloud Run Jobs** - standalone batch containers
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Cloud Run Jobs (via WorkerService) │
|
||||
│ │
|
||||
│ audio-download-job - 30s-5 min (flacfetch/YouTube) │
|
||||
│ lyrics-transcription-job - 5-15 min (AudioShake + correction)│
|
||||
│ audio-separation-job - 10-20 min (Modal API) │
|
||||
│ video-encoding-job - up to 60 min (optional) │
|
||||
@@ -311,9 +312,10 @@ Audio and lyrics workers run as **Cloud Run Jobs** - standalone batch containers
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Why Cloud Run Jobs**: When using FastAPI BackgroundTasks, Cloud Run would terminate instances when HTTP requests completed, even if background work was still running. Job c94cc9d6 failed because the lyrics worker was killed mid-processing after AudioShake completed. Cloud Run Jobs solve this by running workers as standalone processes that complete naturally.
|
||||
**Why Cloud Run Jobs**: When using FastAPI BackgroundTasks, Cloud Run would terminate instances when HTTP requests completed, even if background work was still running. Cloud Run Jobs solve this by running workers as standalone processes that complete naturally. This applies to audio downloads (jobs 51b8231d, 89e497b1 were killed mid-download), lyrics transcription (job c94cc9d6 killed mid-processing), and audio separation.
|
||||
|
||||
**CLI Entry Points**: Each worker has a `main()` function for Cloud Run Job execution:
|
||||
- `python -m backend.workers.audio_download_worker --job-id abc123`
|
||||
- `python -m backend.workers.lyrics_worker --job-id abc123`
|
||||
- `python -m backend.workers.audio_worker --job-id abc123`
|
||||
- `python -m backend.workers.video_worker --job-id abc123`
|
||||
@@ -453,10 +455,11 @@ if tenant_config and not tenant_config.features.audio_search:
|
||||
### Active Tenants
|
||||
|
||||
**Vocal Star** (`vocalstar.nomadkaraoke.com`)
|
||||
- Features: File upload only (no audio search, no YouTube URL)
|
||||
- Distribution: Download only (no YouTube/Dropbox/GDrive)
|
||||
- Features: File upload only (no audio search, no YouTube URL), streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio)
|
||||
- Distribution: Cloud only (Dropbox + Google Drive to tenant-specific folders, no YouTube)
|
||||
- Theme: Locked to "vocalstar" theme (yellow/blue)
|
||||
- Auth: Restricted to `@vocal-star.com` and `@vocalstarmusic.com` emails
|
||||
- All jobs automatically private with VSTAR brand prefix
|
||||
- Setup: `python scripts/setup-vocalstar-tenant.py`
|
||||
|
||||
**Singa** (`singa.nomadkaraoke.com`)
|
||||
|
||||
@@ -664,6 +664,21 @@ export function PrimaryButton({ children, ...props }) {
|
||||
|
||||
---
|
||||
|
||||
## Public Video Style Consistency Rule
|
||||
|
||||
**All videos published to Nomad Karaoke distribution channels (YouTube, Google Drive, venue libraries) MUST use the standard Nomad Karaoke visual style.** No customization of colors, backgrounds, fonts, or other visual elements is permitted for public videos.
|
||||
|
||||
This ensures:
|
||||
- Consistent brand identity across the entire Nomad Karaoke catalog
|
||||
- Professional, recognizable appearance at venues worldwide
|
||||
- Uniform experience for audiences browsing the YouTube channel or venue libraries
|
||||
|
||||
Only the **display artist name** and **display title** text can be overridden for public videos (e.g. to format a soundtrack or cover correctly).
|
||||
|
||||
Custom video styling (backgrounds, colors, fonts) is available exclusively for **private** deliveries where the user takes full responsibility for distribution.
|
||||
|
||||
---
|
||||
|
||||
## Checklist for Brand Compliance
|
||||
|
||||
### Landing Pages
|
||||
|
||||
@@ -113,13 +113,13 @@ Notifications are sent when:
|
||||
| `karaoke-backend@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Post-job trigger |
|
||||
| `karaoke-backend@` SA | `roles/run.invoker` | gdrive-validator Cloud Run service | Gen2 function HTTP access |
|
||||
|
||||
### Known Gaps
|
||||
### Known Gaps (Historical Only)
|
||||
|
||||
The validator knows about expected sequence gaps (historical missing numbers). These are configured identically in both:
|
||||
The validator knows about expected sequence gaps from the pre-generator era (before Dec 2024). These are configured identically in both:
|
||||
- `infrastructure/functions/gdrive_validator/main.py` (Cloud Function)
|
||||
- `scripts/validate_and_sync.py` (local script)
|
||||
|
||||
When a new gap is discovered intentionally (e.g., a track was removed), update the `KNOWN_GAPS` dict in **both** files.
|
||||
**Do NOT add new entries to `KNOWN_GAPS`.** All new gaps are bugs — see [Sequence Gap Detected](#sequence-gap-detected) for the investigation and fix procedure.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -189,11 +189,62 @@ The post-job trigger uses a 5-minute Cloud Tasks delay (via `gdrive-validation-q
|
||||
5. The trigger only fires for non-private jobs (jobs with `gdrive_folder_id` set)
|
||||
6. If Cloud Tasks scheduling fails, the orchestrator falls back to immediate validation
|
||||
|
||||
### False Positive Gaps
|
||||
### Sequence Gap Detected
|
||||
|
||||
If the validator reports gaps that are intentional:
|
||||
1. Add the gap number(s) to `KNOWN_GAPS` in both `main.py` and `scripts/validate_and_sync.py`
|
||||
2. Redeploy the cloud function with `./deploy.sh`
|
||||
**IMPORTANT: Never add new entries to `KNOWN_GAPS`.** The existing known gaps are historical (pre-generator era, over a year old). Every new gap is a real bug that must be investigated and fixed.
|
||||
|
||||
**Investigation steps:**
|
||||
|
||||
1. **Identify the missing brand code(s)** from the alert (e.g., "MP4: missing 1295")
|
||||
|
||||
2. **Check if a job exists** with that brand code:
|
||||
```python
|
||||
# Query Firestore for the brand code
|
||||
db.collection('jobs').where(
|
||||
filter=FieldFilter('state_data.brand_code', '==', 'NOMAD-XXXX')
|
||||
).get()
|
||||
```
|
||||
|
||||
3. **If no job found**, the brand code was allocated but the job was deleted, failed, or re-triggered with a new brand code. Check Cloud Run logs for the allocation:
|
||||
```bash
|
||||
gcloud logging read \
|
||||
'resource.type="cloud_run_revision" AND resource.labels.service_name="karaoke-backend" AND "Allocated brand code: NOMAD-XXXX"' \
|
||||
--project=nomadkaraoke --limit=10 --format="table(timestamp,jsonPayload.message)" --freshness=7d
|
||||
```
|
||||
|
||||
4. **Find the job that consumed it** by checking logs around the allocation timestamp:
|
||||
```bash
|
||||
# Search for the brand code in all log messages
|
||||
gcloud logging read \
|
||||
'resource.type="cloud_run_revision" AND resource.labels.service_name="karaoke-backend" AND "NOMAD-XXXX"' \
|
||||
--project=nomadkaraoke --limit=50 --format="table(timestamp,jsonPayload.message)" --freshness=7d
|
||||
```
|
||||
|
||||
5. **Determine root cause** — common scenarios:
|
||||
- **Job re-triggered** (admin reset): First run allocates brand code N, second run allocates N+M. Brand code N is orphaned.
|
||||
- **E2E test cleanup missed recycling**: Test job consumed a number but cleanup didn't return it.
|
||||
- **Job failed mid-distribution**: Brand code allocated but GDrive upload never happened.
|
||||
|
||||
6. **Fix — recycle the brand code** so the next public job fills the gap:
|
||||
```python
|
||||
import os
|
||||
os.environ['GOOGLE_CLOUD_PROJECT'] = 'nomadkaraoke'
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project='nomadkaraoke')
|
||||
|
||||
doc_ref = db.collection('brand_code_counters').document('NOMAD')
|
||||
doc = doc_ref.get()
|
||||
data = doc.to_dict()
|
||||
recycled = data.get('recycled', [])
|
||||
recycled.append(XXXX) # The missing number
|
||||
recycled.sort()
|
||||
doc_ref.update({'recycled': recycled, 'last_updated': firestore.SERVER_TIMESTAMP})
|
||||
```
|
||||
The `BrandCodeService` always allocates the smallest recycled number first, so the next public job will fill the gap.
|
||||
|
||||
7. **Check for orphan files** in GDrive that need manual cleanup (e.g., a CDG zip from a partial first run). Local `gcloud` auth typically lacks GDrive write scopes, so report orphan files to the user for manual deletion.
|
||||
|
||||
8. **Add the incident to History** (below) so future agents can see patterns.
|
||||
|
||||
### Duplicate Brand Code Detected
|
||||
|
||||
@@ -222,3 +273,4 @@ The cloud function does metadata-only checks via the GDrive API (fast, cheap, ca
|
||||
- **2025-12-24**: Initial cloud function deployed with Pushbullet notifications and daily Cloud Scheduler trigger
|
||||
- **2026-02-28**: Added SendGrid email (primary), kept Pushbullet (fallback). Added post-job trigger from backend. Added `scripts/check_public_share.py` for manual invocation. Motivated by NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours.
|
||||
- **2026-03-02**: NOMAD-1276 incident fix. Post-job trigger now uses 5-minute Cloud Tasks delay instead of immediate invocation, preventing false "all clear" when E2E test files are still in GDrive during cleanup. Also fixed cross-folder gap detection (uses global max across all folders) and added 28 unit tests for the Cloud Function.
|
||||
- **2026-03-06**: NOMAD-1295 gap. Stale GCE encoding cache (#499) caused job `f4a552bf` to produce bad output on first run (allocated NOMAD-1295, only CDG uploaded). Admin re-triggered the job, which allocated a new brand code (NOMAD-1297) without recycling 1295. Fix: recycled 1295 back to the pool. Updated docs to clarify that new gaps must always be investigated and fixed, never added to KNOWN_GAPS.
|
||||
+45
-2
@@ -36,6 +36,9 @@ Audio separation and lyrics transcription run in parallel. Both can fail indepen
|
||||
### GCE Instance Selection for FFmpeg
|
||||
AMD EPYC (C4D series) significantly outperforms Intel Xeon (C4 series) for CPU-bound FFmpeg encoding with libass. C4D-highcpu-32 is ~5x faster than C4-standard-8. C4D requires `hyperdisk-balanced` disk type.
|
||||
|
||||
### Large Documents: GCS + Firestore Metadata (Mar 2026)
|
||||
When a document's payload can exceed Firestore's 1MB limit (e.g., CorrectionData at 100KB+ per session), store the payload in GCS and keep only metadata in Firestore. Use SHA-256 hash deduplication to avoid re-uploading identical data. For cross-document queries (e.g., searching sessions across jobs), use Firestore collection group queries on the metadata subcollection with Python-side text filtering — Firestore doesn't support LIKE/substring queries natively.
|
||||
|
||||
### Queue Instead of Skip for External API Limits (Mar 2026)
|
||||
When an external API has a daily quota (e.g., YouTube Data API v3's 10,000 units/day), **never silently skip** the operation when the limit is reached. Instead: (1) Track actual quota units consumed, not just operation counts — a hard "10 uploads/day" limit was far too conservative when each upload costs ~300 of 10,000 available units, (2) Queue failed operations for automatic retry when quota resets — users expected YouTube uploads and got nothing, with no notification, (3) Send follow-up notifications when deferred operations complete. **GCP Cloud Monitoring as single source of truth**: Initially we self-tracked per-operation costs in Firestore, but the estimates drifted from reality (4,493 estimated vs 2,682 actual). GCP Cloud Monitoring's `serviceruntime.googleapis.com/quota/rate/net_usage` metric has only ~7 min delay — viable as the primary data source. Use a lightweight Firestore "pending buffer" for the delay window, with entries auto-expiring after 10 min. Sum raw per-minute datapoints (no aggregation) to match the GCP Console number. Use the external API's timezone for reset calculations (YouTube resets at midnight Pacific Time, not UTC).
|
||||
|
||||
@@ -301,7 +304,18 @@ Escape special chars in Google Drive API queries: `'` → `\'`, `\` → `\\\\`.
|
||||
For subprocess without shell, FFmpeg filter paths need: apostrophes escaped as `'\\''`, special chars as `\\[char]`.
|
||||
|
||||
### Unicode in HTTP Headers
|
||||
Sanitize user input (artist/title) to ASCII for HTTP headers. Smart quotes, em dashes from copy/paste cause encoding errors.
|
||||
Sanitize user input (artist/title) to ASCII for HTTP headers. Smart quotes, em dashes from copy/paste cause encoding errors. For CJK characters (Chinese, Japanese, Korean) that can't be replaced with ASCII equivalents, use RFC 5987 `filename*=UTF-8''` encoding in Content-Disposition headers instead of trying to force latin-1.
|
||||
|
||||
### CJK Characters in Title Cards (Mar 2026)
|
||||
**What happened**: Job `f8a36b60` with Chinese artist/title rendered question marks on the title card, and download links failed with `'latin-1' codec can't encode characters`.
|
||||
|
||||
**Root cause (title card)**: The title screen uses `Montserrat-Bold.ttf` which has no CJK glyphs. PIL renders missing glyphs as question marks. The karaoke subtitle renderer already uses Noto Sans (with `fonts-noto-cjk` installed in Docker), but the title card `VideoGenerator` had no font fallback.
|
||||
|
||||
**Root cause (downloads)**: `sanitize_filename()` correctly preserves CJK characters (they're valid in filenames), but the `Content-Disposition` header used simple `filename="..."` which requires latin-1 encoding. CJK characters can't be encoded in latin-1.
|
||||
|
||||
**Fix**: (1) Added CJK font fallback in `VideoGenerator._render_all_text()` - detects CJK characters per text element and uses system Noto Sans CJK font via `fontconfig` (`fc-match`). (2) Added RFC 5987 encoding for Content-Disposition headers when filename contains non-latin-1 characters.
|
||||
|
||||
**Pattern**: When rendering text with PIL, the configured font may not support all scripts. Check if text contains characters outside the font's coverage and fall back to a system font with broader Unicode support (Noto Sans CJK). For HTTP headers, always handle the case where filenames contain characters beyond latin-1.
|
||||
|
||||
### Unicode in File Paths (Feb 2026)
|
||||
**What happened**: Job `1eab1172` with Russian title "я куплю тебе дом" (Cyrillic) failed with FFmpeg exit code 183. The temp subtitle file path contained Unicode characters: `temp_subtitles_zivert___я_куплю_тебе_дом_1770150285852.ass`.
|
||||
@@ -378,7 +392,10 @@ Cloud Run throttles CPU to near-zero when the main request handler returns, even
|
||||
When multiple workers run in parallel via BackgroundTasks, Cloud Run can shut down when one worker completes, killing others mid-processing. This happens because each worker endpoint returns quickly after spawning its BackgroundTask - when the audio worker's task completes, Cloud Run sees the container as idle. **Initial Fix**: Implement a `WorkerRegistry` that tracks active workers per job. Register at worker start, unregister in finally block. Add shutdown handler in FastAPI lifespan that calls `worker_registry.wait_for_completion(timeout=600)` before allowing shutdown. **Pattern**: `backend/workers/registry.py` provides the global registry; workers import and call `await worker_registry.register(job_id, "audio")` / `unregister()`.
|
||||
|
||||
### Cloud Run Jobs for Long-Running Workers (Better Solution)
|
||||
The WorkerRegistry approach helped but didn't fully solve the problem - job c94cc9d6 was still killed mid-processing because Cloud Run sent "Shutting down user disabled instance" while lyrics worker was still running. **Better fix**: Use Cloud Run Jobs for long-running workers (lyrics, audio). Cloud Run Jobs run to completion without HTTP request lifecycle concerns. Workers have CLI entry points (`python -m backend.workers.lyrics_worker --job-id abc123`) and are triggered via `google.cloud.run_v2.JobsClient.run_job()`. Jobs can run up to 24 hours vs 30-minute HTTP timeout. Keep fast workers (screens, render) on HTTP with WorkerRegistry. **Pattern**: See `infrastructure/modules/cloud_run.py` for job definitions and `backend/services/worker_service.py` for triggering logic.
|
||||
The WorkerRegistry approach helped but didn't fully solve the problem - job c94cc9d6 was still killed mid-processing because Cloud Run sent "Shutting down user disabled instance" while lyrics worker was still running. **Better fix**: Use Cloud Run Jobs for long-running workers (lyrics, audio separation, audio download). Cloud Run Jobs run to completion without HTTP request lifecycle concerns. Workers have CLI entry points (`python -m backend.workers.lyrics_worker --job-id abc123`) and are triggered via `google.cloud.run_v2.JobsClient.run_job()`. Jobs can run up to 24 hours vs 30-minute HTTP timeout. Keep fast workers (screens, render) on HTTP with WorkerRegistry. **Pattern**: See `infrastructure/modules/cloud_run.py` for job definitions and `backend/services/worker_service.py` for triggering logic.
|
||||
|
||||
### Audio Downloads Must Use Cloud Run Jobs (Not BackgroundTasks)
|
||||
Audio downloads via the guided flow (create-from-search, select audio source) used FastAPI `BackgroundTasks` to run downloads after the HTTP response returned. Cloud Run terminated "idle" instances (no active HTTP requests) within 1-2 minutes, silently killing downloads mid-progress. Jobs 51b8231d and 89e497b1 got permanently stuck at `downloading_audio` with no error. **Fix**: Move audio downloads to a Cloud Run Job (`audio-download-job`) just like lyrics and audio separation workers. The `audio_download_worker.py` extracts the download logic into a standalone process. **Defense in depth**: A Cloud Scheduler job runs every 5 minutes to detect and fail jobs stuck in `downloading_audio` for >10 minutes, enabling automatic retry.
|
||||
|
||||
### Add Progress Logging for Long Operations
|
||||
Operations over ~30 seconds should log progress periodically (time-based, not count-based). Count-based logging like "log every 20 items" can miss entirely if items complete slowly. Time-based logging (every 30s) ensures visibility regardless of processing speed.
|
||||
@@ -439,6 +456,9 @@ except Exception as e:
|
||||
|
||||
## Testing Insights
|
||||
|
||||
### New Features Must Test the Summary Projection (Mar 2026)
|
||||
When adding new fields that the dashboard needs, you must add them to **both** `SUMMARY_FIELD_PATHS` (Firestore projection) and `_SUMMARY_STATE_DATA_KEYS` (Python prune allowlist). The dashboard uses `fields=summary` which projects only listed fields — any unlisted field comes back as `undefined`. Unit tests that mock the job object directly won't catch this because they bypass the projection layer entirely. **Always add a regression test** asserting the field is in `SUMMARY_FIELD_PATHS` when introducing new fields the frontend depends on. The Change Visibility feature shipped with `is_private` missing from the projection, causing the button to always show "Make Private".
|
||||
|
||||
### Test Webhook Handlers with Unit Tests
|
||||
Webhook handlers contain critical business logic. Test exact parameters passed to service methods, not just that "something happened."
|
||||
|
||||
@@ -856,3 +876,26 @@ Even with idempotent endpoints (PR #413) and basic retry logic (PR #242), jobs c
|
||||
3. **Cloud Run service naming matters for debugging** — The service is `karaoke-backend`, not `karaoke-gen-api`. Wrong name returns empty logs, wasting investigation time.
|
||||
4. **Cross-folder gap detection needs global context** — Per-folder max misses trailing gaps when folders have different highest numbers. Use the global max across all folders as the upper bound.
|
||||
|
||||
### Verifying Request Bodies via Cloud Trace Request Size (2026-03-07)
|
||||
|
||||
**Problem:** A job was created with `is_private=true` but the user believed they selected "Published." No request body logging existed to prove what the frontend actually sent.
|
||||
|
||||
**Solution:** Cloud Trace captures `/http/request/size` on every span. By computing the exact byte length of the JSON body with `is_private: true` vs `is_private: false` (compact serialization, no spaces), the sizes matched exactly — 143 bytes for `true`, confirming the frontend sent `is_private: true`.
|
||||
|
||||
**Prevention:** Added two observability mechanisms:
|
||||
1. **`creation_params`** — A dict stored on the job Firestore document capturing the user's original choices (`is_private`, `is_admin`, `created_from`). Persists forever, no log retention concerns.
|
||||
2. **OTel span attributes** — `job.is_private`, `job.source`, `job_id` added to all 4 job creation endpoint spans. Searchable in Cloud Trace for 30 days.
|
||||
|
||||
**Key insight:** When investigating "what did the client send?", Cloud Trace request size can serve as a forensic tool even without request body logging. Compact JSON serialization (`JSON.stringify` with no spaces) is deterministic, so byte-level size matching is reliable.
|
||||
|
||||
### Timeline Metadata for Job Traceability (2026-03-07)
|
||||
|
||||
**Problem:** After shipping the "edit completed tracks" feature, tracing what happened to edited jobs was very difficult. Timeline events only had `status`, `timestamp`, `progress`, `message` — no output details. Cleanup operations (YouTube deletion, Dropbox removal) weren't logged to Firestore. Previous outputs were overwritten in `state_data` with no history. API endpoints (edit, admin-delete) logged to Cloud Run stdout but not to the job's Firestore log subcollection.
|
||||
|
||||
**Solution:**
|
||||
1. **`TimelineEvent.metadata`** — Optional `Dict[str, Any]` field on timeline events. Completion events now capture `brand_code`, `youtube_url`, `dropbox_link`, `gdrive_file_ids`, `duration_seconds`. Edit/delete events capture `previous_outputs` and `cleanup_results`.
|
||||
2. **`log_to_job()` helper** — Module-level function in `firestore_service.py` that writes to the job's Firestore log subcollection. Wraps errors silently so logging never breaks the caller. Used by API endpoints that previously only logged to stdout.
|
||||
3. **Plumbed `timeline_metadata`** through `job_manager.transition_to_state()` → `firestore_service.update_job_status()`.
|
||||
|
||||
**Key insight:** The job's Firestore document (timeline + log subcollection) should be the single source of truth for "what happened to this job." Cloud Logging has retention limits and requires knowing which service to search. Timeline metadata makes the job self-documenting — any agent or human can read the timeline and understand the full lifecycle without cross-referencing logs.
|
||||
|
||||
+12
-1
@@ -34,6 +34,7 @@
|
||||
| **Custom video styling (private jobs)** | Working |
|
||||
| **Song lookup autocomplete** | Working (via karaoke-decide catalog) |
|
||||
| **Community version detection** | Working (via karaokenerds.com) |
|
||||
| **Review session backup/restore** | Working (auto-save + restore UI) |
|
||||
|
||||
## Known Issues
|
||||
|
||||
@@ -45,6 +46,16 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Review Session Backup/Restore** (2026-03-08): Server-side auto-save of lyrics review sessions replaces fragile localStorage-only mechanism. Sessions auto-save every 60s (if dirty), on preview video generation, and on page unload. Deduplication via SHA-256 hash prevents redundant saves. Correction data stored in GCS (can exceed Firestore's 1MB doc limit); metadata in Firestore subcollection (`jobs/{jobId}/review_sessions/{sessionId}`). Restore UI shows split-pane session browser with edit diff preview. Cross-job session search allows reusing edits across different jobs (with duration mismatch warning). On load, automatically prompts to restore if saved sessions exist. See [archive/2026-03-07-lyrics-review-sessions-plan.md](archive/2026-03-07-lyrics-review-sessions-plan.md).
|
||||
|
||||
- **Job Observability Improvements** (2026-03-07): Enhanced timeline events with a `metadata` field to capture structured output details (brand codes, YouTube video IDs, Dropbox paths, GDrive file IDs) at key moments — job completion, edit initiation, and admin output deletion. Added `log_to_job()` helper for API endpoints to write to Firestore job log subcollections (previously only workers logged there). Edit and admin-delete endpoints now snapshot previous outputs before cleanup and log each cleanup step. Distribution logging enhanced with video IDs, folder paths, and file IDs. See [plans/improve-job-observability.plan.md](../.claude/plans/improve-job-observability.plan.md).
|
||||
|
||||
- **Edit Completed Tracks** (2026-03-06): Users can now edit completed karaoke tracks — correcting lyrics, changing instrumental selection, or updating artist/title metadata — without consuming additional credits. Clicking "Edit" on a completed job opens a confirmation modal (with optional artist/title editing), then cleans up all distributed outputs (YouTube video deleted, Dropbox folder removed, GDrive files deleted, GCS finals purged, brand code recycled), resets the job to `awaiting_review`, and redirects to the existing review screen. After re-review, the standard pipeline re-renders and re-distributes with a fresh brand code. New endpoint: `POST /api/jobs/{job_id}/edit`. New Job model field: `edit_count`. State machine updated: `COMPLETE → AWAITING_REVIEW` transition allowed. See [archive/2026-03-06-edit-completed-tracks-plan.md](archive/2026-03-06-edit-completed-tracks-plan.md) and [API.md](API.md#edit-completed-track).
|
||||
|
||||
- **Change Visibility** (2026-03-06): Users can now toggle completed jobs between public and private via a "Make Public"/"Make Private" button on the job card. Two distinct flows: Public→Private is fast (~1-2 min, redistributes existing finals), Private→Public is slow (~15-30 min, resets styles to Nomad theme, regenerates screens, re-renders video). Confirmation modal explains the implications. Tenant jobs excluded. See [archive/2026-03-06-change-visibility-plan.md](archive/2026-03-06-change-visibility-plan.md) and [API.md](API.md#change-visibility).
|
||||
|
||||
- **Tenant Portal UI Rework** (2026-03-04): Replaced the multi-step consumer wizard with a streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) for B2B tenant portals. Vocal Star's portal now uses the new `TenantJobFlow` component instead of `GuidedJobFlow`. All tenant jobs are automatically private with tenant-specific distribution: Dropbox delivery to `/MediaUnsynced/Karaoke/Tracks-VocalStar`, Google Drive upload to tenant folder, VSTAR brand prefix. Backend adds `_apply_tenant_overrides()` helper that forces private, applies locked theme, and overlays tenant distribution settings. Private tenant jobs now use their own Dropbox/GDrive paths instead of the NonPublished override. Frontend conditionally renders `TenantJobFlow` vs `GuidedJobFlow` based on tenant detection. See [archive/2026-03-04-tenant-portal-ui-rework.md](archive/2026-03-04-tenant-portal-ui-rework.md).
|
||||
|
||||
- **Custom Video Styling for Private Jobs** (2026-03-04): Users who select "Private (no YouTube upload)" can now customize their karaoke video styling. New options in the guided flow's customize step: upload a custom **karaoke background image** (replaces the starfield behind lyrics), upload a custom **title card background image**, and change **artist/title text colors** via color pickers. Both backgrounds show accurate canvas-based live previews. Style assets are uploaded to GCS via signed URLs after job creation (non-blocking — job falls back to default theme on upload failure). Backend: 2 new endpoints (`style-upload-urls`, `style-uploads-complete`) that validate ownership, cutoff status, and merge custom assets into the theme's `style_params.json`. See [API.md](API.md#get-style-upload-urls).
|
||||
|
||||
- **Tenant Portal Frontend Separation** (2026-03-03): B2B tenants now served from a dedicated Cloudflare Pages project (`karaoke-gen-tenant`) built with `NEXT_PUBLIC_TENANT_PORTAL=true` to tree-shake consumer content. A Cloudflare edge function injects `window.__TENANT_CONFIG__` and CSS variables into HTML at the edge, eliminating the initial API round-trip for tenant config. Magic link emails now use tenant-specific URLs (e.g., `vocalstar.nomadkaraoke.com/auth/verify`). Admins can preview any tenant's branding via `?preview_tenant=<id>`. See [ARCHITECTURE.md](ARCHITECTURE.md#tenant-portal-frontend-b2b-deployment).
|
||||
@@ -120,7 +131,7 @@
|
||||
|
||||
- **Fast Preview Video Option** (2026-01-10): Added toggle in lyrics review UI to render preview videos with black background (~10s) instead of theme background image (~30-60s). Default is now black background for faster iteration during review. Users can enable theme background via checkbox when they want to verify the final look. See [API.md](API.md#generate-preview).
|
||||
|
||||
- **Frontend Consolidation** (2026-01-09): Consolidated three separate frontends into a single Next.js application. Previously: (1) Main frontend (Next.js + Tailwind), (2) Lyrics Review (React + Vite + MUI, ~14k lines), and (3) Instrumental Review (vanilla HTML/JS, ~1.7k lines) were deployed separately. Now all UIs are unified in the main frontend at `/app/jobs/{id}/review` and `/app/jobs/{id}/instrumental`. Benefits: single deployment to Cloudflare Pages, no external redirects during user workflows, unified design system (Radix/Tailwind), simpler authentication via job ownership model. See [archive/2026-01-09-frontend-consolidation-plan.md](archive/2026-01-09-frontend-consolidation-plan.md) and [tasks/](tasks/).
|
||||
- **Frontend Consolidation** (2026-01-09): Consolidated three separate frontends into a single Next.js application. Previously: (1) Main frontend (Next.js + Tailwind), (2) Lyrics Review (React + Vite + MUI, ~14k lines), and (3) Instrumental Review (vanilla HTML/JS, ~1.7k lines) were deployed separately. Now all UIs are unified in the main frontend at `/app/jobs#/{id}/review` and `/app/jobs#/{id}/instrumental`. Benefits: single deployment to Cloudflare Pages, no external redirects during user workflows, unified design system (Radix/Tailwind), simpler authentication via job ownership model. See [archive/2026-01-09-frontend-consolidation-plan.md](archive/2026-01-09-frontend-consolidation-plan.md) and [tasks/](tasks/).
|
||||
|
||||
- **Admin Login Token for Made-For-You Orders** (2026-01-10): Added one-click admin login via email. When a made-for-you order is placed, the admin notification email now includes a direct link with an embedded login token (`?admin_token=TOKEN`). Clicking this link auto-authenticates the admin and opens the job directly - no manual login required. Tokens expire after 24 hours. Also added: BCC to `done@nomadkaraoke.com` on all job completion emails, fixed timezone display (EST→ET for DST correctness). See [API.md](API.md#verify-magic-link).
|
||||
|
||||
|
||||
+1
-1
@@ -495,7 +495,7 @@ async function debug() {
|
||||
const page = await browser.newContext().then(c => c.newPage());
|
||||
|
||||
await page.addInitScript(t => localStorage.setItem('karaoke_access_token', t), TOKEN);
|
||||
await page.goto(`https://gen.nomadkaraoke.com/app/jobs/${JOB_ID}/review/`);
|
||||
await page.goto(`https://gen.nomadkaraoke.com/app/jobs#/${JOB_ID}/review`);
|
||||
|
||||
// Debug interactively - the browser stays open
|
||||
await page.pause(); // Opens Playwright inspector
|
||||
|
||||
@@ -4,6 +4,31 @@ Operational runbooks for known production issues.
|
||||
|
||||
---
|
||||
|
||||
## Job stuck at `downloading_audio` status
|
||||
|
||||
**Cause:** Before v0.130.0, audio downloads ran as FastAPI BackgroundTasks. Cloud Run would terminate "idle" instances mid-download. Since v0.130.0, downloads use a Cloud Run Job (`audio-download-job`) and a Cloud Scheduler recovery job runs every 5 minutes to fail stuck downloads automatically.
|
||||
|
||||
**Auto-recovery:** The `recover-stuck-downloads` scheduler detects jobs stuck in `downloading_audio` for >10 minutes and fails them. Use the admin retry button to re-attempt.
|
||||
|
||||
**Manual recovery:**
|
||||
|
||||
```bash
|
||||
# 1. Check for stuck downloads
|
||||
curl -s "https://api.nomadkaraoke.com/api/health/job-consistency" \
|
||||
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
|
||||
| python3 -m json.tool | grep -A3 "downloading_audio_stuck"
|
||||
|
||||
# 2. Trigger recovery manually (if scheduler hasn't run yet)
|
||||
curl -X POST "https://api.nomadkaraoke.com/api/internal/recover-stuck-jobs" \
|
||||
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)"
|
||||
|
||||
# 3. Retry the failed job via admin dashboard or API
|
||||
curl -X POST "https://api.nomadkaraoke.com/api/jobs/YOUR_JOB_ID/retry" \
|
||||
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Job stuck at `encoding` status
|
||||
|
||||
**Cause:** A Cloud Run deployment killed the poller mid-encoding. The GCE worker finished but nobody received the result. The health service will flag this as `encoding_stuck` after 50 minutes.
|
||||
@@ -73,6 +98,23 @@ gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
|
||||
---
|
||||
|
||||
## GDrive validator reports sequence gap
|
||||
|
||||
**Symptoms:** Email from "Nomad Karaoke GDrive Validator" reporting `SEQUENCE GAPS: MP4: missing XXXX`.
|
||||
|
||||
**Key principle: Never add to `KNOWN_GAPS`.** All known gaps are historical (pre-generator, 2024). Every new gap is a real bug.
|
||||
|
||||
**Full investigation and fix procedure:** See [docs/GDRIVE-VALIDATOR.md § Sequence Gap Detected](GDRIVE-VALIDATOR.md#sequence-gap-detected).
|
||||
|
||||
**Quick reference:**
|
||||
1. Query Firestore for the missing brand code (`state_data.brand_code == 'NOMAD-XXXX'`)
|
||||
2. If no job found, check Cloud Run logs for `"Allocated brand code: NOMAD-XXXX"` to find when/how it was consumed
|
||||
3. Determine root cause from logs (job re-trigger, failed distribution, etc.)
|
||||
4. Recycle the brand code number into `brand_code_counters/NOMAD.recycled` — the next public job will fill the gap
|
||||
5. Report any orphan GDrive files to the user for manual cleanup
|
||||
|
||||
---
|
||||
|
||||
## Google Drive uploads missing (gdrive_files empty)
|
||||
|
||||
**Symptoms:** Jobs complete successfully but `state_data.gdrive_files` is empty `{}`. Cloud Run logs show `BrokenPipeError` or `SSL: UNEXPECTED_EOF_WHILE_READING`.
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
# Tenant Portal UI Rework
|
||||
|
||||
**Date**: 2026-03-04
|
||||
**Branch**: `feat/sess-20260304-0007-tenant-ui-rework`
|
||||
**Worktree**: `karaoke-gen-tenant-ui-rework`
|
||||
**Status**: Implementation + Config Complete — Ready for PR
|
||||
|
||||
## Context
|
||||
|
||||
The tenant portal at `vocalstar.nomadkaraoke.com` shows the same 3-step consumer wizard (song search -> audio source -> customize) designed for end users. B2B white-label customers like Vocal Star always provide their own mixed audio AND instrumental files. They don't need audio search, YouTube URL input, theme selection, privacy toggles, or customization options.
|
||||
|
||||
**Goal**: Replace the multi-step wizard with a streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) for tenant portals. All tracks are automatically private, delivered to tenant-specific Dropbox/Google Drive folders, with tenant brand codes and styling.
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Phase 1: Backend — Tenant Distribution Defaults
|
||||
|
||||
| Step | File | Change | Status |
|
||||
|------|------|--------|--------|
|
||||
| 1.1 | `backend/models/tenant.py` | Add `dropbox_path`, `gdrive_folder_id` to TenantDefaults | Done |
|
||||
| 1.2 | `backend/api/routes/file_upload.py` | Create `_apply_tenant_overrides()`, call in 2 endpoints | Done |
|
||||
| 1.3 | `backend/services/job_defaults_service.py` | Tenant-aware private job handling (skip NonPublished override) | Done |
|
||||
| 1.4 | `frontend/lib/api.ts` | Add `existing_instrumental` flag to createJobWithUploadUrls | Done |
|
||||
| 1.5 | `backend/tests/test_tenant_job_defaults.py` | 9 unit tests for tenant override logic | Done |
|
||||
|
||||
**1.1 Details**: Two new Optional fields on TenantDefaults:
|
||||
- `dropbox_path: Optional[str]` — e.g., `/Karaoke/Vocal-Star`
|
||||
- `gdrive_folder_id: Optional[str]` — tenant GDrive folder ID
|
||||
|
||||
Already excluded from TenantPublicConfig (line 194 only copies theme_id, locked_theme, distribution_mode).
|
||||
|
||||
**1.2 Details**: `_apply_tenant_overrides(dist, tenant_config, body)` helper that:
|
||||
1. Overlays tenant `brand_prefix`, `dropbox_path`, `gdrive_folder_id` onto EffectiveDistributionSettings
|
||||
2. Forces `is_private = True` for all tenant jobs
|
||||
3. Applies `locked_theme` as effective theme
|
||||
4. Disables YouTube upload
|
||||
|
||||
Called in: `create_job_with_upload_urls` (line 971) and `upload_and_create_job` (line 324).
|
||||
|
||||
**1.3 Details**: In `get_effective_distribution_for_job` (line 64), if `job.tenant_id` is set AND `is_private=True`, skip the NonPublished path override. Use job's own distribution fields (which contain tenant defaults from creation). Still disable YouTube.
|
||||
|
||||
**1.4 Details**: The backend `CreateJobWithUploadUrlsRequest` already has `existing_instrumental: bool` (line 170). Frontend `api.ts` `createJobWithUploadUrls()` just needs to pass it through in the request body.
|
||||
|
||||
**1.5 Tests**:
|
||||
- `test_tenant_defaults_applied_to_distribution` — brand_prefix, dropbox_path, gdrive_folder_id applied
|
||||
- `test_tenant_job_forced_private` — is_private always True for tenant jobs
|
||||
- `test_tenant_locked_theme_applied` — locked_theme overrides user theme
|
||||
- `test_private_tenant_job_uses_tenant_paths` — uses tenant Dropbox/GDrive, NOT NonPublished
|
||||
- `test_non_tenant_private_job_still_uses_nonpublished` — existing behavior preserved
|
||||
|
||||
### Phase 2: Frontend — TenantJobFlow Component
|
||||
|
||||
| Step | File | Change | Status |
|
||||
|------|------|--------|--------|
|
||||
| 2.1 | `frontend/components/job/TenantJobFlow.tsx` | **Create** single-page 4-field form | Done |
|
||||
| 2.2 | `frontend/app/app/page.tsx` | TenantLogo in header, conditional form rendering | Done |
|
||||
| 2.3 | `frontend/__tests__/tenant-job-flow.test.tsx` | Component tests (4 tests) | Done |
|
||||
|
||||
**2.1 Details**: Single-page form (~250 lines) with:
|
||||
- Artist text input, Title text input
|
||||
- Mixed Audio file upload (drag-and-drop, accepts .mp3,.wav,.flac,.m4a,.ogg,.aac)
|
||||
- Instrumental Audio file upload (same types)
|
||||
- Submit button (disabled until all 4 fields filled)
|
||||
- Submission: `createJobWithUploadUrls` -> `uploadToSignedUrl` x2 -> `completeJobUpload`
|
||||
- Success view: simplified timeline (review lyrics -> video delivered), "Create Another" button
|
||||
- Omits "audio processing" step since instrumental is provided
|
||||
|
||||
**2.2 Details**:
|
||||
- Replace hardcoded `<img src="/nomad-karaoke-logo.svg">` (line 196) with `<TenantLogo size="sm" />`
|
||||
- Tenant-aware title using `branding.site_title`
|
||||
- Conditional: `<TenantJobFlow>` when `!isDefault`, else `<GuidedJobFlow>`
|
||||
- Card text: "Submit Track" / "Upload your mixed audio and instrumental" for tenants
|
||||
- Hide feedback banner for non-default users
|
||||
|
||||
### Phase 3: Config & Deployment
|
||||
|
||||
| Step | Change | Status |
|
||||
|------|--------|--------|
|
||||
| 3.1 | Update Vocalstar tenant config in GCS | Done |
|
||||
| 3.2 | Post-deploy setup tasks | Done — all verified |
|
||||
|
||||
Config additions needed:
|
||||
```json
|
||||
{
|
||||
"defaults": {
|
||||
"locked_theme": "vocalstar",
|
||||
"distribution_mode": "cloud_only",
|
||||
"brand_prefix": "VSTAR",
|
||||
"dropbox_path": "<user-to-provide>",
|
||||
"gdrive_folder_id": "<user-to-provide>"
|
||||
},
|
||||
"features": {
|
||||
"audio_search": false,
|
||||
"file_upload": true,
|
||||
"youtube_url": false,
|
||||
"youtube_upload": false,
|
||||
"theme_selection": false,
|
||||
"color_overrides": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 4: Production Verification
|
||||
|
||||
| Step | File | Change | Status |
|
||||
|------|------|--------|--------|
|
||||
| 4.1 | `frontend/e2e/production/tenant-job-submission.spec.ts` | **Create** Playwright E2E test (3 tests) | Done |
|
||||
|
||||
Full lifecycle: navigate tenant portal -> verify branding -> submit track -> wait for processing -> approve reviews -> verify outputs delivered to tenant paths.
|
||||
|
||||
## Key Files
|
||||
|
||||
| File | Action |
|
||||
|------|--------|
|
||||
| `backend/models/tenant.py` | Modify — add 2 fields to TenantDefaults |
|
||||
| `backend/api/routes/file_upload.py` | Modify — add `_apply_tenant_overrides()`, call in 2 endpoints |
|
||||
| `backend/services/job_defaults_service.py` | Modify — tenant-aware private job handling |
|
||||
| `frontend/components/job/TenantJobFlow.tsx` | **Create** — new simplified 4-field form |
|
||||
| `frontend/app/app/page.tsx` | Modify — TenantLogo in header, conditional form |
|
||||
| `frontend/lib/api.ts` | Modify — add `existing_instrumental` flag |
|
||||
| `backend/tests/test_tenant_job_defaults.py` | **Create** — backend tests |
|
||||
| `frontend/__tests__/components/job/TenantJobFlow.test.tsx` | **Create** — component tests |
|
||||
| `frontend/e2e/production/tenant-job-submission.spec.ts` | **Create** — E2E prod test |
|
||||
|
||||
## Implementation Log
|
||||
|
||||
### Phase 1 — Backend (Complete)
|
||||
- Added `dropbox_path` and `gdrive_folder_id` to `TenantDefaults` model
|
||||
- Created `_apply_tenant_overrides()` helper in `file_upload.py` — overlays tenant config, forces private, applies locked_theme, disables YouTube
|
||||
- Wired into both `upload_and_create_job` and `create_job_with_upload_urls` endpoints
|
||||
- Fixed `get_effective_distribution_for_job` to respect tenant paths for private jobs (skips NonPublished override when `tenant_id` is set)
|
||||
- Added `existing_instrumental` option to frontend `api.createJobWithUploadUrls()`
|
||||
- 9 unit tests in `test_tenant_job_defaults.py` — all pass
|
||||
|
||||
### Phase 2 — Frontend (Complete)
|
||||
- Created `TenantJobFlow.tsx` (~300 lines) — 4-field form with drag-and-drop, progress tracking, success timeline
|
||||
- Updated `app/page.tsx`:
|
||||
- `TenantLogo` component in header (replaces hardcoded Nomad logo for tenants)
|
||||
- Tenant-aware title using `branding.site_title`
|
||||
- Conditional rendering: `TenantJobFlow` for tenants, `GuidedJobFlow` for consumers
|
||||
- Card titles/descriptions adapted per mode
|
||||
- Feedback banner hidden for tenants
|
||||
- 4 component tests in `tenant-job-flow.test.tsx` — all pass (520/520 total)
|
||||
|
||||
### Phase 3 — Config (Complete)
|
||||
- Updated `gs://karaoke-gen-storage-nomadkaraoke/tenants/vocalstar/config.json`:
|
||||
- `distribution_mode`: "download_only" → "cloud_only"
|
||||
- `dropbox_upload`/`gdrive_upload`: false → true
|
||||
- Added `dropbox_path`: "/MediaUnsynced/Karaoke/Tracks-VocalStar"
|
||||
- Added `gdrive_folder_id`: "15pKDJSh9uQSAJFbKlHsiiRLmFCUkYZPc"
|
||||
- Verified: `vocalstar` theme exists with style_params.json + 6 assets (font, backgrounds)
|
||||
- Verified: logo.jpg accessible via API asset endpoint (85KB, 200 OK)
|
||||
|
||||
### Phase 4 — E2E (Complete)
|
||||
- Created `tenant-job-submission.spec.ts` with 3 tests:
|
||||
1. Tenant portal shows simplified form (not consumer wizard)
|
||||
2. Full track submission flow
|
||||
3. Consumer portal still works normally
|
||||
@@ -0,0 +1,70 @@
|
||||
# Visibility Step & Customize Rework
|
||||
|
||||
**Date:** 2026-03-04
|
||||
**Branch:** feat/sess-20260304-1700-visibility-step-customize
|
||||
|
||||
## Overview
|
||||
|
||||
Rework the guided job creation flow to add a separate "Visibility" step before "Customize & Create", dedicated to deciding whether the created video should be published or private. Then rework the "Customize & Create" step based on the chosen visibility.
|
||||
|
||||
## New "Visibility" Step
|
||||
|
||||
On this step, we simply let the user choose between public or private, but we use it as an opportunity to ensure the user definitely understands what will happen.
|
||||
|
||||
### Published (Public)
|
||||
|
||||
Explain that "published" means:
|
||||
|
||||
- The resulting karaoke video will be automatically uploaded to the Nomad Karaoke YouTube channel (with a link to https://www.youtube.com/@nomadkaraoke/videos for them to check that out)
|
||||
- It will also be uploaded to a Google Drive which is shared with various karaoke venues, meaning the song will be available to sing at a variety of karaoke bars/venues around the world
|
||||
- The user will get all the source files and highest quality output formats via a Dropbox folder link too, which they can download for their safekeeping
|
||||
- We should encourage the user to choose this option as it's the most convenient way to make their song available to sing (via YouTube) and they'll be helping out other fans of the same song, bringing joy to people all over the world who love that song
|
||||
|
||||
### Private
|
||||
|
||||
Explain that "private" means:
|
||||
|
||||
- The resulting karaoke video will NOT be uploaded to YouTube or Google Drive, and will only be provided via a Dropbox folder / via this site, for the user to download and use however they see fit
|
||||
- If the user wants to perform the track at a venue, they'll be responsible for providing the files to the host at that venue
|
||||
- If the user wants to upload the video to their own YouTube channel they can do so, but they likely won't be able to monetise it (the song licenses/copyrights are still owned by record labels in most cases)
|
||||
- If the user wants to customise the video styles (e.g. background image, colors), they can do this if they choose private delivery
|
||||
|
||||
## Reworked "Customize & Create" Step
|
||||
|
||||
Once we have the new "Visibility" step in the flow, we also need to rework the "Customize & Create" flow:
|
||||
|
||||
### Remove Private Checkbox
|
||||
|
||||
The "private" checkbox on the current Customize & Create step is replaced by the new Visibility step.
|
||||
|
||||
### Conditional Options Based on Visibility
|
||||
|
||||
Since we'll now know already whether the video is private or public, we can show only the options which are allowed:
|
||||
|
||||
- **For public videos**: Only the title card artist/title should be customisable
|
||||
- **For private videos**: Allow customising almost anything
|
||||
|
||||
### Side-by-Side Preview Canvases
|
||||
|
||||
Show the two preview canvases (title screen, main karaoke) side by side in this part of the flow, not below each other, so the user doesn't need to scroll down.
|
||||
|
||||
### Remove Redundant Thumbnails
|
||||
|
||||
Uploaded images for custom backgrounds don't need thumbnails - that's redundant since they're shown on the preview canvas(es).
|
||||
|
||||
### Improved Karaoke Preview Canvas
|
||||
|
||||
The text in the karaoke preview canvas needs to be centered in the thumbnail and show 4 lines so it's more similar to how the actual karaoke videos get rendered (see reference screenshot of actual video output).
|
||||
|
||||
### New Style Customisation Options
|
||||
|
||||
There should be a way to change more aspects of the styles:
|
||||
|
||||
- Change the text color and/or highlight color of the karaoke lyrics
|
||||
- Use a solid color background (rather than an image) for either the title screen or karaoke video (or both with different colors)
|
||||
- Add a few preset color buttons for both of these, including one which is the "green screen" color
|
||||
|
||||
## Reference Screenshots
|
||||
|
||||
- Current "Customize & Create" UI: see attached screenshot showing the existing layout with private checkbox, stacked canvases, and current style options
|
||||
- Actual karaoke video output: see attached screenshot showing how lyrics appear in real videos (4 centered lines with highlight color)
|
||||
@@ -0,0 +1,120 @@
|
||||
# Plan: Admin Lyrics Review Dashboard
|
||||
|
||||
**Created:** 2026-03-05
|
||||
**Branch:** feat/sess-20260305-0002-admin-lyrics-review
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Add an "Edit Reviews" section to the admin dashboard for reviewing completed lyrics reviews. Three goals:
|
||||
|
||||
1. **View what users saw** - Jump into a read-only lyrics review UI showing original vs corrected lyrics
|
||||
2. **Replay user edits** - Step through edit log entries to see exactly what each user changed
|
||||
3. **Review raw data** - View human edits data to evaluate quality for AudioShake data sharing
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] New admin sidebar item "Edit Reviews" linking to `/admin/edit-reviews`
|
||||
- [ ] Backend endpoint to list recent jobs that have completed lyrics review (with edit logs)
|
||||
- [ ] Backend endpoint to serve immutable correction data for a job (read-only, cannot modify job)
|
||||
- [ ] Admin page showing list of recently reviewed jobs with key metrics
|
||||
- [ ] Ability to open the existing LyricsAnalyzer in read-only mode with snapshot data
|
||||
- [ ] Edit log replay/stepper UI to walk through user changes one by one
|
||||
- [ ] Raw data viewer for edit logs, annotations, and correction diffs
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Backend: 2 new admin endpoints
|
||||
|
||||
1. **`GET /api/admin/edit-reviews`** - List jobs with completed reviews
|
||||
- Query Firestore for jobs with `state_data.last_edit_log_path` set (indicating review was performed)
|
||||
- Filter by status (completed jobs, or optionally all post-review statuses)
|
||||
- Return summary: job_id, artist, title, user_email, review_completed_at, edit_count, feedback_count
|
||||
- Support pagination, search, exclude_test filtering
|
||||
|
||||
2. **`GET /api/admin/edit-reviews/{job_id}`** - Get full review snapshot
|
||||
- Returns immutable copy of:
|
||||
- Original corrections (`corrections.json` from GCS)
|
||||
- Updated corrections (`corrections_updated.json` from GCS)
|
||||
- Edit log (`edit_log_{session_id}.json` from GCS)
|
||||
- Annotations (`annotations.json` from GCS)
|
||||
- Job metadata (artist, title, user_email, timestamps)
|
||||
- Audio URL (signed, for playback in review UI)
|
||||
- This is a **read-only** endpoint - no job state mutations
|
||||
- Uses `require_admin` dependency (not `require_review_auth`)
|
||||
- Does NOT transition job status or modify any state
|
||||
|
||||
### Frontend: New admin page + Read-only review mode
|
||||
|
||||
1. **`/admin/edit-reviews/page.tsx`** - List page
|
||||
- Table of recently reviewed jobs
|
||||
- Columns: Artist/Title, User, Review Date, Edits Made, Feedback Given, Actions
|
||||
- "View Review" button → opens read-only lyrics review
|
||||
- "View Edit Log" button → opens edit replay view
|
||||
- "View Raw Data" button → shows raw JSON
|
||||
|
||||
2. **Read-only review viewer** - Reuse LyricsAnalyzer
|
||||
- Load data from the new admin endpoint (not the regular review endpoint)
|
||||
- Pass `isReadOnly={true}` and `apiClient={null}` to LyricsAnalyzer
|
||||
- Header shows "Admin Review - Read Only" indicator
|
||||
- No submit/save buttons, no state transitions
|
||||
- Audio playback still works (via signed URL)
|
||||
|
||||
3. **Edit log replay** - New component
|
||||
- Timeline/stepper showing each edit entry
|
||||
- For each entry: operation type, text before → text after, timestamp
|
||||
- Step forward/backward through edits
|
||||
- Show feedback reason if user provided one
|
||||
- Summary stats: total edits, edits with feedback, correction types breakdown
|
||||
|
||||
4. **Raw data viewer** - JSON viewer tabs
|
||||
- Tab 1: Edit Log (formatted JSON with syntax highlighting)
|
||||
- Tab 2: Annotations
|
||||
- Tab 3: Corrections diff (original vs updated)
|
||||
|
||||
### Key safety guarantee
|
||||
|
||||
The admin review endpoint serves a **snapshot** of the data. It reads from GCS files that were already written. The LyricsAnalyzer receives `apiClient={null}` so it physically cannot call any mutation endpoints. Even if code changes in the future, the admin endpoint itself never writes to Firestore or GCS.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] **Backend: Add `GET /api/admin/edit-reviews` endpoint** - List reviewed jobs with edit log metadata
|
||||
2. [ ] **Backend: Add `GET /api/admin/edit-reviews/{job_id}` endpoint** - Serve full immutable review snapshot
|
||||
3. [ ] **Frontend: Add admin API client methods** - `adminApi.listEditReviews()`, `adminApi.getEditReview(jobId)`
|
||||
4. [ ] **Frontend: Create `/admin/edit-reviews/page.tsx`** - List page with table
|
||||
5. [ ] **Frontend: Add sidebar nav item** - "Edit Reviews" with BookOpen icon
|
||||
6. [ ] **Frontend: Create read-only review viewer** - Load snapshot data into LyricsAnalyzer with isReadOnly
|
||||
7. [ ] **Frontend: Create edit log replay component** - Step-through UI for edit entries
|
||||
8. [ ] **Frontend: Create raw data viewer** - JSON viewer with tabs
|
||||
9. [ ] **Tests: Backend unit tests** for new admin endpoints
|
||||
10. [ ] **Tests: Frontend component tests** for new page
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/admin.py` | Modify | Add edit-reviews endpoints |
|
||||
| `frontend/lib/api.ts` | Modify | Add adminApi methods for edit reviews |
|
||||
| `frontend/app/admin/edit-reviews/page.tsx` | Create | Main edit reviews list page |
|
||||
| `frontend/components/admin/edit-review-viewer.tsx` | Create | Read-only review wrapper using LyricsAnalyzer |
|
||||
| `frontend/components/admin/edit-log-replay.tsx` | Create | Edit log stepper/replay component |
|
||||
| `frontend/components/admin/raw-data-viewer.tsx` | Create | JSON viewer with tabs |
|
||||
| `frontend/components/admin/admin-sidebar.tsx` | Modify | Add Edit Reviews nav item |
|
||||
| `backend/tests/test_admin_edit_reviews.py` | Create | Backend tests |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- Unit tests for backend endpoints (mock Firestore + GCS)
|
||||
- Verify admin auth is required on all new endpoints
|
||||
- Verify no write operations occur on read-only endpoints
|
||||
- Frontend component tests for key interactions
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should we show ALL jobs that went through review, or only ones with edit logs? (Recommendation: only those with edit logs, since those are the interesting ones)
|
||||
- [ ] Do we need audio playback in the admin review viewer? (Recommendation: yes, it helps understand what the user heard)
|
||||
- [ ] Should the raw data be downloadable? (Nice-to-have, can add later)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
All changes are additive (new endpoints, new pages). Removing the sidebar link effectively hides the feature. No existing behavior is modified.
|
||||
@@ -0,0 +1,165 @@
|
||||
# Plan: Reliable Audio Downloads
|
||||
|
||||
**Date:** 2026-03-05
|
||||
**Branch:** feat/sess-20260305-0125-investigate-stuck-downloads
|
||||
**Status:** Implemented
|
||||
|
||||
## Problem Statement
|
||||
|
||||
Jobs that download audio via the "guided flow" (create-from-search, select audio source) use FastAPI `BackgroundTasks` to run the download + worker trigger logic. When Cloud Run scales down the instance before the background task completes, the task is silently killed. The job stays stuck at `downloading_audio` forever — no error is recorded, no workers are triggered, and there's no automatic recovery.
|
||||
|
||||
This affected jobs `51b8231d` and `89e497b1` on 2026-03-05. Cloud Run instances were shut down ~1-2 minutes after job creation.
|
||||
|
||||
### Why This Happens
|
||||
|
||||
The download flow is:
|
||||
1. HTTP endpoint returns 200 immediately (job created)
|
||||
2. `background_tasks.add_task(_download_audio_and_trigger_workers, ...)` schedules the download
|
||||
3. BackgroundTask calls flacfetch API, polls for completion (can take 30s-5min for Spotify)
|
||||
4. On success: updates Firestore, transitions to DOWNLOADING, triggers audio+lyrics workers
|
||||
5. On failure: calls `fail_job()` to mark as failed
|
||||
|
||||
Cloud Run terminates "idle" instances (no active HTTP requests). Since the endpoint already returned, the instance appears idle despite the background task running. When terminated, step 3/4/5 never completes.
|
||||
|
||||
### Existing Pattern That Works
|
||||
|
||||
Audio separation and lyrics transcription workers already solved this exact problem by using **Cloud Run Jobs** (`trigger_audio_worker`, `trigger_lyrics_worker` in `worker_service.py`). Cloud Run Jobs run to completion without HTTP request lifecycle concerns.
|
||||
|
||||
## Plan
|
||||
|
||||
### Part 1: Move Audio Download to Cloud Run Job
|
||||
|
||||
**Goal:** Make audio downloads survive Cloud Run instance shutdowns.
|
||||
|
||||
#### 1a. Create `backend/workers/audio_download_worker.py`
|
||||
|
||||
New standalone worker module (like `audio_worker.py` and `lyrics_worker.py`) that:
|
||||
- Accepts `--job-id` CLI argument
|
||||
- Reads job from Firestore to get download params (source_name, source_id, selection_index, etc.)
|
||||
- Downloads audio via flacfetch client or YouTube download service
|
||||
- Uploads to GCS at `uploads/{job_id}/audio/`
|
||||
- Updates Firestore with `input_media_gcs_path` and `filename`
|
||||
- Transitions job from `DOWNLOADING_AUDIO` to `DOWNLOADING`
|
||||
- Triggers audio+lyrics workers (via Cloud Run Jobs, same as today)
|
||||
- On failure: calls `fail_job()` with error details
|
||||
|
||||
This is essentially extracting `_download_audio_and_trigger_workers()` from `audio_search.py` into a standalone entrypoint.
|
||||
|
||||
#### 1b. Create Cloud Run Job infrastructure
|
||||
|
||||
Add to `infrastructure/modules/cloud_run.py`:
|
||||
- `create_audio_download_job()` — new Cloud Run Job resource `audio-download-job`
|
||||
- Same pattern as `create_audio_separation_job()` and `create_lyrics_transcription_job()`
|
||||
- Timeout: 10 minutes (Spotify downloads typically < 5 min, YouTube < 30s)
|
||||
- Max retries: 2
|
||||
|
||||
Add to `infrastructure/__main__.py`:
|
||||
- Wire up the new job resource
|
||||
|
||||
#### 1c. Add `trigger_audio_download_worker()` to WorkerService
|
||||
|
||||
Add method to `backend/services/worker_service.py`:
|
||||
```python
|
||||
async def trigger_audio_download_worker(self, job_id: str) -> bool:
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="audio-download-job",
|
||||
worker_module="audio_download_worker",
|
||||
)
|
||||
```
|
||||
|
||||
#### 1d. Replace BackgroundTasks calls with Cloud Run Job triggers
|
||||
|
||||
In these 3 call sites, replace `background_tasks.add_task(_download_audio_and_trigger_workers, ...)` with `await worker_service.trigger_audio_download_worker(job_id)`:
|
||||
|
||||
1. `backend/api/routes/audio_search.py` — `select_audio_source()` (line ~1160)
|
||||
2. `backend/api/routes/audio_search.py` — `search_with_auto_download()` (line ~838)
|
||||
3. `backend/api/routes/jobs.py` — `create_from_search()` (line ~2067)
|
||||
|
||||
The endpoints still return immediately — Cloud Run Job creation is fast (~100ms). The actual download runs in the separate Cloud Run Job instance.
|
||||
|
||||
#### 1e. Update admin retry endpoint
|
||||
|
||||
In `backend/api/routes/jobs.py`, the retry endpoint's audio download path (line ~1470-1605):
|
||||
- Currently runs the download synchronously in the HTTP handler (problematic for long downloads)
|
||||
- Refactor to trigger the same `audio_download_worker` Cloud Run Job
|
||||
- Fix the state transition bug: add `DOWNLOADING_AUDIO` to valid transitions from `FAILED`
|
||||
|
||||
### Part 2: Stuck Job Detection & Auto-Recovery (Defense in Depth)
|
||||
|
||||
**Goal:** Automatically detect and recover jobs stuck in transient states.
|
||||
|
||||
#### 2a. Add `downloading_audio_stuck` check to JobHealthService
|
||||
|
||||
In `backend/services/job_health_service.py`, add a consistency check:
|
||||
- Jobs in `DOWNLOADING_AUDIO` status for >10 minutes are stuck
|
||||
- Check `updated_at` age, similar to existing `encoding_stuck` check
|
||||
|
||||
#### 2b. Create stuck job recovery endpoint
|
||||
|
||||
New internal endpoint `POST /api/internal/recover-stuck-jobs`:
|
||||
- Queries Firestore for jobs in `DOWNLOADING_AUDIO` status with `updated_at` > 10 minutes ago
|
||||
- For each stuck job:
|
||||
- If `input_media_gcs_path` is set (file exists): transition to DOWNLOADING, trigger workers
|
||||
- If `input_media_gcs_path` is null: re-trigger audio download worker
|
||||
- If retry_count > 3: fail the job with timeout error
|
||||
- Increment `retry_count` on each recovery attempt
|
||||
- Log all recovery actions for observability
|
||||
|
||||
#### 2c. Create Cloud Scheduler job
|
||||
|
||||
Add to infrastructure:
|
||||
- Cloud Scheduler job `recover-stuck-downloads` that runs every 5 minutes
|
||||
- Calls `POST /api/internal/recover-stuck-jobs`
|
||||
- Uses the existing service account OIDC auth pattern
|
||||
|
||||
This catches any future edge cases where jobs get stuck, regardless of the cause.
|
||||
|
||||
### Part 3: Fix State Machine Gap
|
||||
|
||||
**Goal:** Allow retry from `FAILED` to `DOWNLOADING_AUDIO`.
|
||||
|
||||
In `backend/models/job.py`, add `JobStatus.DOWNLOADING_AUDIO` to the `FAILED` transitions:
|
||||
```python
|
||||
JobStatus.FAILED: [
|
||||
JobStatus.DOWNLOADING,
|
||||
JobStatus.DOWNLOADING_AUDIO, # <-- ADD THIS
|
||||
JobStatus.INSTRUMENTAL_SELECTED,
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
JobStatus.LYRICS_COMPLETE,
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
]
|
||||
```
|
||||
|
||||
This allows the admin retry endpoint to re-download audio for failed jobs that came from the audio search flow.
|
||||
|
||||
## Scope & Complexity
|
||||
|
||||
| Part | Files Changed | Complexity | Risk |
|
||||
|------|--------------|------------|------|
|
||||
| 1a | 1 new file | Medium | Low — extracts existing logic |
|
||||
| 1b | 2 infra files | Low | Low — follows existing pattern |
|
||||
| 1c | 1 file | Low | Low — one new method |
|
||||
| 1d | 2 files | Low | Low — replace 3 call sites |
|
||||
| 1e | 1 file | Medium | Medium — refactor retry logic |
|
||||
| 2a | 1 file | Low | Low — add one check |
|
||||
| 2b | 1 file | Medium | Low — new endpoint |
|
||||
| 2c | 2 infra files | Low | Low — follows existing pattern |
|
||||
| 3 | 1 file | Low | Low — add one enum value |
|
||||
|
||||
**Total: ~6 files changed, 2 new files, 1 new infra resource**
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests:** Test `audio_download_worker.py` with mocked flacfetch/YouTube services
|
||||
- **Integration tests:** Test the full flow from `create_from_search` through Cloud Run Job trigger
|
||||
- **Existing tests:** Update mocks in `test_audio_search.py` and `test_standalone_search.py` to verify Cloud Run Job is triggered instead of BackgroundTasks
|
||||
- **Manual verification:** Deploy to prod and create a test job via guided flow; verify it completes even if Cloud Run scales down
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. Part 3 (state machine fix) — smallest, unblocks retry
|
||||
2. Part 1a-1c (new worker + infra) — core fix
|
||||
3. Part 1d (replace call sites) — activate the fix
|
||||
4. Part 1e (retry endpoint) — improve admin tooling
|
||||
5. Part 2 (stuck job detection) — defense in depth
|
||||
@@ -0,0 +1,339 @@
|
||||
# Change Visibility Plan
|
||||
|
||||
> **Date**: 2026-03-06
|
||||
> **Branch**: `feat/sess-20260306-1750-change-visibility`
|
||||
> **Status**: Draft
|
||||
|
||||
## Problem
|
||||
|
||||
Users who accidentally select the wrong visibility (public/private) during job creation have no way to change it after the job completes. Currently, only admins can toggle `is_private` via the PATCH endpoint, and when toggling to private it only auto-deletes outputs -- it doesn't re-distribute to the correct destination.
|
||||
|
||||
Example: Job `fdcc82a6` was accidentally created as private but should be public.
|
||||
|
||||
## Requirements
|
||||
|
||||
1. Any user who can see a job (creator or admin) can change visibility on completed jobs
|
||||
2. A confirmation modal explains exactly what will happen before proceeding
|
||||
3. Modal wording varies based on direction (public->private vs private->public)
|
||||
4. Tenant jobs (Vocal Star, Singa) are excluded -- this is consumer gen only
|
||||
5. No cooldown/rate limiting needed
|
||||
|
||||
## Two Distinct Flows
|
||||
|
||||
### Flow A: Public -> Private (simpler, faster)
|
||||
|
||||
The video content doesn't change -- same nomad theme, same screens. We just need to move outputs from public destinations to private ones.
|
||||
|
||||
**Steps:**
|
||||
1. Delete distributed outputs (YouTube, Dropbox `/Tracks-Organized/`, GDrive) but **keep GCS finals**
|
||||
2. Recycle the NOMAD brand code
|
||||
3. Set `is_private = true` on the job
|
||||
4. Re-run distribution only: allocate NOMADNP brand code, upload finals to Dropbox `/Tracks-NonPublished/`
|
||||
5. Update job state_data with new brand_code and dropbox_link
|
||||
6. Clear `outputs_deleted_at` flag
|
||||
7. Mark job as complete
|
||||
|
||||
**Expected duration:** ~1-2 minutes (just file uploads)
|
||||
|
||||
### Flow B: Private -> Public (complex, slower)
|
||||
|
||||
Private jobs may have custom styles (backgrounds, colors) that don't conform to the public Nomad branding. We must reset to defaults and re-process from screens onward.
|
||||
|
||||
**Steps:**
|
||||
1. Delete distributed outputs (Dropbox `/Tracks-NonPublished/`) + delete GCS finals + delete screens + delete `with_vocals.mkv`
|
||||
2. Recycle the NOMADNP brand code
|
||||
3. **Permanently clear custom style data:**
|
||||
- Reset `theme_id` to `"nomad"` (or whatever the default is)
|
||||
- Clear `color_overrides` to `{}`
|
||||
- Clear `style_assets` to `{}`
|
||||
- Delete any custom style files from GCS (`jobs/{job_id}/style/`)
|
||||
4. Set `is_private = false` on the job
|
||||
5. Set job status to `LYRICS_COMPLETE` (entry point for screens worker)
|
||||
6. Clear relevant progress keys: `screens_progress`, `render_progress`, `video_progress`, `encoding_progress`
|
||||
7. Trigger screens worker, which cascades through: screens -> awaiting_review (auto-skip, since review is already done) -> render -> encode -> distribute publicly
|
||||
8. Job returns to `COMPLETE` with public outputs (YouTube, Dropbox `/Tracks-Organized/`, GDrive)
|
||||
|
||||
**Expected duration:** ~15-30 minutes (re-render + re-encode + distribute)
|
||||
|
||||
**Key gotcha:** After regenerating screens, the pipeline normally transitions to `AWAITING_REVIEW`. But we've already completed review -- we need to auto-skip review and proceed to rendering. We'll use a `regen_restore_status` mechanism (already exists for the `regenerate-screens` endpoint) to signal the screens worker to restore to `REVIEW_COMPLETE` instead of `AWAITING_REVIEW`, which triggers the render worker.
|
||||
|
||||
## Architecture
|
||||
|
||||
### New Backend Endpoint
|
||||
|
||||
```
|
||||
POST /api/jobs/{job_id}/change-visibility
|
||||
```
|
||||
|
||||
**Auth:** Requires authenticated user who is the job creator OR an admin.
|
||||
|
||||
**Request body:**
|
||||
```json
|
||||
{
|
||||
"target_visibility": "public" | "private"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"status": "success" | "processing" | "error",
|
||||
"job_id": "...",
|
||||
"message": "...",
|
||||
"previous_visibility": "public" | "private",
|
||||
"new_visibility": "public" | "private",
|
||||
"reprocessing_required": true | false
|
||||
}
|
||||
```
|
||||
|
||||
**Why a new endpoint instead of extending admin PATCH?**
|
||||
- The PATCH endpoint is admin-only; this needs to work for regular users
|
||||
- The logic is complex enough to warrant its own endpoint with clear semantics
|
||||
- We need to orchestrate multiple steps atomically (delete outputs, update fields, trigger workers)
|
||||
- The existing PATCH toggle-to-private behavior is kept as-is for admin convenience (backwards compat)
|
||||
|
||||
**Validation:**
|
||||
- Job must be in `COMPLETE` status (not `FAILED`, `PREP_COMPLETE`, or in-progress)
|
||||
- Job must not be a tenant job (`tenant_id` must be null)
|
||||
- Target visibility must differ from current visibility
|
||||
- Job must not already be undergoing a visibility change (guard against double-clicks)
|
||||
|
||||
### Backend Implementation Details
|
||||
|
||||
#### Public -> Private (distribution-only re-run)
|
||||
|
||||
This flow is novel -- we don't have an existing mechanism to re-run just distribution. Options:
|
||||
|
||||
**Option 1: Dedicated `_redistribute` function** (recommended)
|
||||
Create a lightweight function that:
|
||||
1. Downloads finals from GCS to a temp dir
|
||||
2. Creates an OrchestratorConfig with private distribution settings
|
||||
3. Runs only `_run_organization()` + `_run_distribution()` + `_run_notifications()` stages
|
||||
4. Updates job state_data
|
||||
|
||||
This avoids re-encoding entirely. We'd extract the distribution stages into a callable unit.
|
||||
|
||||
**Option 2: Re-run full video worker with cached encoding**
|
||||
The GCE encoding worker has a cache -- if the job was recently encoded, it returns cached results. But this is fragile (cache might be cleared) and still downloads/re-uploads files unnecessarily.
|
||||
|
||||
Going with Option 1.
|
||||
|
||||
**Implementation:**
|
||||
- New function in `video_worker.py`: `async def redistribute_video(job_id: str) -> bool`
|
||||
- Modeled after `generate_video_orchestrated()` but skips encoding
|
||||
- Downloads existing finals from GCS `jobs/{job_id}/finals/`
|
||||
- Creates orchestrator with appropriate distribution config
|
||||
- Runs organization + distribution stages only
|
||||
|
||||
#### Private -> Public (full re-process)
|
||||
|
||||
This reuses existing infrastructure more directly:
|
||||
1. Call modified `delete_job_outputs()` that also cleans up screens and rendered video
|
||||
2. Reset style fields on the job document
|
||||
3. Set status to `LYRICS_COMPLETE` with `regen_restore_status = "review_complete"`
|
||||
4. Trigger screens worker via `worker_service.trigger_screens_worker(job_id)`
|
||||
5. The screens worker generates screens, then sees `regen_restore_status` and restores to `REVIEW_COMPLETE`
|
||||
6. `REVIEW_COMPLETE` triggers render worker -> video worker -> `COMPLETE`
|
||||
|
||||
**Issue: Screens worker `regen_restore_status` behavior**
|
||||
|
||||
Looking at the existing `regenerate-screens` endpoint (admin.py:2003), it sets `regen_restore_status` to the original status. The screens worker checks this and restores to that status instead of going to `AWAITING_REVIEW`.
|
||||
|
||||
For our case, we want to restore to `REVIEW_COMPLETE` (not back to `COMPLETE`), so the pipeline continues through render + encode. This fits the existing mechanism perfectly -- we just set `regen_restore_status = "review_complete"`.
|
||||
|
||||
**Issue: Screens worker does NOT auto-trigger the render worker**
|
||||
|
||||
Verified: The screens worker's `regen_restore_status` handling (screens_worker.py:197-204) just does a raw Firestore update to set the status -- it does **not** trigger any downstream worker. The render worker is only triggered from the `complete-review` API endpoint (jobs.py:992).
|
||||
|
||||
**Solution:** Modify the screens worker's `regen_restore_status` handling to also trigger the render worker when the restore status is `review_complete`. This is the cleanest approach because:
|
||||
- The trigger logic stays in the worker pipeline (not in a separate polling mechanism)
|
||||
- It's a small, focused change to `screens_worker.py`
|
||||
- It reuses `worker_service.trigger_render_video_worker(job_id)`
|
||||
|
||||
```python
|
||||
# In screens_worker.py, after restoring status:
|
||||
if regen_restore_status == "review_complete":
|
||||
# Visibility change flow: trigger render worker to continue pipeline
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
```
|
||||
|
||||
#### Modified `delete_job_outputs` for Public -> Private
|
||||
|
||||
The current `delete_job_outputs()` always deletes GCS finals. For public->private, we need to keep them. Two approaches:
|
||||
|
||||
**Option A: Add `keep_gcs_finals` parameter** (recommended)
|
||||
Add an optional parameter to `delete_job_outputs()`: `keep_gcs_finals: bool = False`. When True, skip the GCS finals deletion step. The endpoint still deletes YouTube/Dropbox/GDrive and recycles the brand code.
|
||||
|
||||
**Option B: Create separate helper function**
|
||||
Extract the YouTube/Dropbox/GDrive deletion into a helper. More code duplication.
|
||||
|
||||
Going with Option A -- minimal change, backwards compatible.
|
||||
|
||||
### Frontend Implementation
|
||||
|
||||
#### Button Location
|
||||
|
||||
Add a "Change Visibility" button to the `OutputLinks` component (`frontend/components/job/OutputLinks.tsx`), visible when:
|
||||
- Job status is `complete`
|
||||
- Job is not a tenant job
|
||||
- Job is not currently being re-processed (guard state)
|
||||
|
||||
The button shows the current visibility and what it would change to:
|
||||
- For public jobs: "Make Private" with a Lock icon
|
||||
- For private jobs: "Make Public" with a Globe icon
|
||||
|
||||
#### Confirmation Modal
|
||||
|
||||
Uses the existing `AlertDialog` component from `@radix-ui/react-alert-dialog`.
|
||||
|
||||
**Public -> Private modal:**
|
||||
```
|
||||
Title: Make This Track Private?
|
||||
|
||||
This will:
|
||||
- Remove the video from YouTube
|
||||
- Remove files from Google Drive
|
||||
- Move Dropbox files from public to private folder
|
||||
- Assign a new private brand code (NOMADNP)
|
||||
|
||||
The video content won't change. This usually takes about 1-2 minutes.
|
||||
|
||||
You can change it back to public later, but that will require
|
||||
re-rendering the video (~15-30 minutes).
|
||||
|
||||
[Cancel] [Make Private]
|
||||
```
|
||||
|
||||
**Private -> Public modal:**
|
||||
```
|
||||
Title: Make This Track Public?
|
||||
|
||||
This will:
|
||||
- Remove any custom styling (backgrounds, colors) and
|
||||
reset to the standard Nomad Karaoke theme
|
||||
- Regenerate title and end screens
|
||||
- Re-render the karaoke video with default branding
|
||||
- Publish to YouTube, Google Drive, and Dropbox
|
||||
|
||||
This process takes approximately 15-30 minutes. You'll receive
|
||||
an email when it's complete.
|
||||
|
||||
Any custom styling you applied will be permanently removed.
|
||||
|
||||
[Cancel] [Make Public]
|
||||
```
|
||||
|
||||
#### During Re-processing (Private -> Public)
|
||||
|
||||
While the job is being re-processed:
|
||||
- The button is disabled and shows a spinner: "Changing to Public..."
|
||||
- Job status will cycle through intermediate states (`LYRICS_COMPLETE` -> `GENERATING_SCREENS` -> etc.)
|
||||
- The job card should show these intermediate statuses normally
|
||||
- When it reaches `COMPLETE` again, the button returns to normal
|
||||
|
||||
For public->private, the change is fast enough (~1-2 min) that we can show a loading spinner on the button and poll for completion.
|
||||
|
||||
#### API Integration
|
||||
|
||||
New method in `frontend/lib/api.ts`:
|
||||
|
||||
```typescript
|
||||
// In the public api object (not adminApi, since regular users can use this)
|
||||
async changeVisibility(jobId: string, targetVisibility: 'public' | 'private'): Promise<ChangeVisibilityResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/jobs/${jobId}/change-visibility`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify({ target_visibility: targetVisibility }),
|
||||
}
|
||||
);
|
||||
return handleResponse(response);
|
||||
}
|
||||
```
|
||||
|
||||
## State Machine Considerations
|
||||
|
||||
New state transitions needed:
|
||||
- `COMPLETE` -> `LYRICS_COMPLETE` (for private->public re-processing)
|
||||
|
||||
This transition doesn't currently exist in `STATE_TRANSITIONS`. We need to add it. The `COMPLETE` -> `LYRICS_COMPLETE` transition is safe because:
|
||||
- We've already validated the job has completed audio+lyrics processing
|
||||
- We're resetting screens/render/video progress markers
|
||||
- The screens worker will pick up from `LYRICS_COMPLETE` as normal
|
||||
|
||||
Also need: `COMPLETE` -> `GENERATING_VIDEO` (for public->private redistribution, if we transition through video worker states during redistribution). Actually, for the redistribution-only path, we might want a simpler approach -- keep the job in `COMPLETE` status during redistribution since it's a fast operation, or use a new transient state.
|
||||
|
||||
**Decision:** For public->private (fast redistribution), we'll:
|
||||
1. Set a flag `state_data.visibility_change_in_progress = true` to prevent concurrent changes
|
||||
2. Keep status as `COMPLETE` (since the operation is fast and the job is still "complete")
|
||||
3. Run redistribution in a background task
|
||||
4. Clear the flag when done
|
||||
|
||||
For private->public (full re-process), we'll:
|
||||
1. Set `visibility_change_in_progress = true`
|
||||
2. Transition to `LYRICS_COMPLETE` (triggering the normal pipeline)
|
||||
3. The flag gets cleared when the job reaches `COMPLETE` again
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Phase 1: Backend - Change Visibility Endpoint
|
||||
|
||||
**Files to modify:**
|
||||
- `backend/api/routes/jobs.py` -- Add `POST /jobs/{job_id}/change-visibility` endpoint
|
||||
- `backend/api/routes/admin.py` -- Add `keep_gcs_finals` param to `delete_job_outputs()`
|
||||
- `backend/models/job.py` -- Add `COMPLETE -> LYRICS_COMPLETE` state transition
|
||||
- `backend/models/requests.py` -- Add request/response models
|
||||
|
||||
**Files to create:**
|
||||
- `backend/services/visibility_change_service.py` -- Core logic for both flows
|
||||
|
||||
### Phase 2: Backend - Redistribution Function
|
||||
|
||||
**Files to modify:**
|
||||
- `backend/workers/video_worker.py` -- Add `redistribute_video()` function
|
||||
- `backend/workers/video_worker_orchestrator.py` -- Possibly extract distribution stages
|
||||
|
||||
### Phase 3: Frontend - Button + Modal
|
||||
|
||||
**Files to modify:**
|
||||
- `frontend/components/job/OutputLinks.tsx` -- Add Change Visibility button + modal
|
||||
- `frontend/lib/api.ts` -- Add `changeVisibility()` method + response types
|
||||
|
||||
### Phase 4: Testing
|
||||
|
||||
**Files to create:**
|
||||
- `backend/tests/test_change_visibility.py` -- Unit tests for the visibility change service
|
||||
- `backend/tests/test_redistribute.py` -- Unit tests for the redistribution function
|
||||
- `frontend/e2e/production/change-visibility.spec.ts` -- E2E test (if feasible)
|
||||
|
||||
**Test cases:**
|
||||
1. Public -> Private: outputs deleted, finals preserved, redistributed to private destination
|
||||
2. Private -> Public: styles reset, screens regenerated, full pipeline completes
|
||||
3. Validation: rejects non-complete jobs, tenant jobs, same-visibility changes, concurrent changes
|
||||
4. Auth: job creator can change, admin can change, other users cannot
|
||||
5. Edge cases: job with no YouTube URL, job with no brand code, job with outputs already deleted
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Risk | Impact | Mitigation |
|
||||
|------|--------|------------|
|
||||
| Pipeline fails mid-visibility-change (private->public) | Job stuck in intermediate state | Use existing `FAILED` state handling; admin can restart |
|
||||
| GCS finals deleted before redistribution completes (public->private) | Need to re-encode | Use `keep_gcs_finals=True` to preserve them |
|
||||
| Race condition: user clicks button twice | Double processing | `visibility_change_in_progress` guard flag |
|
||||
| Screens worker doesn't auto-trigger render after regen | Pipeline stalls | **Resolved**: Modify screens worker to trigger render worker when `regen_restore_status == "review_complete"` |
|
||||
| Custom style files left as orphans in GCS | Storage waste | Clean up `jobs/{job_id}/style/` during private->public |
|
||||
|
||||
## Open Questions (Resolved)
|
||||
|
||||
1. **Who can trigger?** Anyone who can see the job (creator or admin). -> New user-facing endpoint.
|
||||
2. **Skip re-encoding for public->private?** Yes, keep GCS finals and redistribute only.
|
||||
3. **How far back for private->public?** From `LYRICS_COMPLETE` (screens -> render -> encode -> distribute).
|
||||
4. **Tenant jobs?** Excluded. Consumer gen only.
|
||||
5. **Custom style data?** Permanently cleared on private->public. Explained in modal.
|
||||
6. **Rate limiting?** None needed.
|
||||
@@ -0,0 +1,262 @@
|
||||
# Edit Completed Tracks — Implementation Plan
|
||||
|
||||
> Created: 2026-03-06
|
||||
> Branch: feat/sess-20260306-1705-edit-completed-tracks
|
||||
|
||||
## Overview
|
||||
|
||||
Allow users to edit completed karaoke tracks — correcting lyrics, changing instrumental selection, or updating artist/title metadata — without consuming additional credits. The existing outputs are cleaned up (YouTube, Dropbox, GDrive, GCS) before re-opening the review screens, and a fresh brand code is allocated when the edited track is re-distributed.
|
||||
|
||||
## Design Decisions
|
||||
|
||||
| Decision | Answer |
|
||||
|----------|--------|
|
||||
| Brand code on edit | New code allocated (old one recycled) |
|
||||
| Credit cost | Free (credit already consumed at job creation) |
|
||||
| Edit limit | None |
|
||||
| Metadata edits (artist/title) | Supported via confirmation modal |
|
||||
| UX approach | Reopen review on same job (approach A) |
|
||||
|
||||
## User Flow
|
||||
|
||||
```
|
||||
Completed job detail page
|
||||
→ User clicks "Edit Track"
|
||||
→ Confirmation modal appears:
|
||||
- Explains: existing outputs will be deleted, track re-rendered after review
|
||||
- Asks: "Do you need to update the artist or title?"
|
||||
- If yes: shows editable artist/title input fields (pre-filled)
|
||||
- If no: fields hidden
|
||||
- [Cancel] [Confirm & Edit]
|
||||
→ On confirm:
|
||||
- Frontend calls POST /api/jobs/{job_id}/edit
|
||||
- Backend: cleanup outputs → reset state → issue review token
|
||||
- Frontend redirects to review screen (/app/jobs#/{jobId}/review)
|
||||
→ User edits lyrics / instrumental as usual
|
||||
→ User submits review
|
||||
→ Standard pipeline: render → encode → distribute (new brand code)
|
||||
→ Job returns to COMPLETE with fresh outputs
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
### Phase 1: Backend — Edit Endpoint
|
||||
|
||||
**New endpoint: `POST /api/jobs/{job_id}/edit`**
|
||||
|
||||
File: `backend/api/routes/jobs.py` (or new `backend/api/routes/edit.py`)
|
||||
|
||||
Request body:
|
||||
```json
|
||||
{
|
||||
"artist": "Updated Artist", // optional, only if user wants to change
|
||||
"title": "Updated Title" // optional, only if user wants to change
|
||||
}
|
||||
```
|
||||
|
||||
Auth: Job owner (via session token) OR admin.
|
||||
|
||||
Logic:
|
||||
1. **Validate** job is in `COMPLETE` state and user owns it
|
||||
2. **Validate** `outputs_deleted_at` is not set (prevent editing already-in-progress edits)
|
||||
3. **Cleanup distributed outputs** (reuse logic from admin `delete-outputs`):
|
||||
a. Delete YouTube video (if exists)
|
||||
b. Delete Dropbox folder (if exists)
|
||||
c. Delete Google Drive files (if exists)
|
||||
d. Delete GCS `finals/` folder
|
||||
e. Recycle brand code (if Dropbox + GDrive both succeeded)
|
||||
f. Clear state_data keys: `youtube_url`, `youtube_video_id`, `brand_code`, `dropbox_link`, `gdrive_files`
|
||||
g. Set `outputs_deleted_at` + `outputs_deleted_by`
|
||||
4. **Update metadata** (if provided):
|
||||
a. Update `artist` and/or `title` fields on the job
|
||||
b. If metadata changed: delete existing screen files from GCS (`screens/` folder)
|
||||
c. Clear `screens_progress` from state_data so screens worker re-runs
|
||||
5. **Reset processing state**:
|
||||
a. Clear state_data keys: `render_progress`, `video_progress`, `encoding_progress`, `review_complete`
|
||||
b. Keep: `audio_complete`, `lyrics_complete`, `corrected_lyrics`, `instrumental_selection`, `instrumental_options`
|
||||
c. Keep all stems and lyrics files in GCS
|
||||
6. **Transition state**: `COMPLETE` → `AWAITING_REVIEW`
|
||||
7. **Issue review token**: Generate new `review_token` with expiration
|
||||
8. **Increment edit counter**: `edit_count += 1` (new field)
|
||||
9. **Log timeline event**: `"Track edit initiated by {user_email} (edit #{edit_count})"`
|
||||
10. **Return** review URL + token
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"review_url": "/app/jobs#/{jobId}/review",
|
||||
"review_token": "abc123..."
|
||||
}
|
||||
```
|
||||
|
||||
**Error cases:**
|
||||
- Job not in COMPLETE state → 400
|
||||
- User doesn't own job → 403
|
||||
- Cleanup fails critically (Dropbox folder still exists) → 500, don't reset state
|
||||
- Job already being edited (status != COMPLETE) → 400
|
||||
|
||||
### Phase 2: Backend — State Machine Updates
|
||||
|
||||
File: `backend/models/job.py`
|
||||
|
||||
1. Add `COMPLETE → AWAITING_REVIEW` to `STATE_TRANSITIONS` dict (conditional on edit endpoint)
|
||||
2. Add new field to Job model:
|
||||
```python
|
||||
edit_count: int = 0
|
||||
```
|
||||
|
||||
### Phase 3: Backend — Post-Review Pipeline Adjustments
|
||||
|
||||
File: `backend/workers/screens_worker.py`
|
||||
|
||||
- When triggered after an edit with metadata changes, screens worker already handles regeneration
|
||||
- The edit endpoint clears `screens_progress` and deletes screen files, so screens worker will re-run naturally
|
||||
- No changes needed if screens worker already checks for missing screen files
|
||||
|
||||
File: `backend/workers/render_video_worker.py`
|
||||
|
||||
- No changes needed — render worker reads current `corrected_lyrics` and `instrumental_selection` from state_data
|
||||
- Will pick up whatever the user selected during re-review
|
||||
|
||||
File: `backend/workers/video_worker_orchestrator.py`
|
||||
|
||||
- Already clears `outputs_deleted_at` after successful distribution (lines 564-578)
|
||||
- Already allocates new brand code via `allocate_brand_code()` during distribution
|
||||
- No changes needed
|
||||
|
||||
### Phase 4: Frontend — Edit Button + Confirmation Modal
|
||||
|
||||
**Edit button on completed job view**
|
||||
|
||||
File: `frontend/app/app/jobs/[[...slug]]/client.tsx` (or wherever job detail is rendered)
|
||||
|
||||
- Show "Edit Track" button only when job status is `complete`
|
||||
- Button opens the confirmation modal
|
||||
|
||||
**Confirmation modal component**
|
||||
|
||||
New file: `frontend/components/job/EditTrackModal.tsx`
|
||||
|
||||
Content:
|
||||
- Warning text: "This will remove your current video from YouTube, Dropbox, and Google Drive. After you complete the review again, a new version will be rendered and re-distributed."
|
||||
- Toggle/checkbox: "I need to update the artist or title"
|
||||
- When checked, show:
|
||||
- Artist input (pre-filled with current `job.artist`)
|
||||
- Title input (pre-filled with current `job.title`)
|
||||
- [Cancel] button
|
||||
- [Confirm & Edit] button → calls API, shows loading state, redirects to review on success
|
||||
|
||||
**API call**
|
||||
|
||||
File: `frontend/lib/api.ts`
|
||||
|
||||
Add:
|
||||
```typescript
|
||||
editCompletedTrack(jobId: string, updates?: { artist?: string; title?: string }): Promise<{ review_url: string; review_token: string }>
|
||||
```
|
||||
|
||||
### Phase 5: Frontend — Review Screen Adjustments
|
||||
|
||||
File: `frontend/app/app/jobs/[[...slug]]/client.tsx` (JobRouterClient)
|
||||
|
||||
- Currently only renders review screens for `AWAITING_REVIEW` / `IN_REVIEW` states — this already works
|
||||
- The edit endpoint transitions the job to `AWAITING_REVIEW`, so existing routing handles it
|
||||
|
||||
**One adjustment needed:** If the user edited metadata (artist/title), the screens worker needs to run before or after review. Two options:
|
||||
|
||||
- **Option A (simpler):** Edit endpoint triggers screens worker immediately after resetting state. Screens regenerate in background while user reviews lyrics. By the time review is submitted, screens should be ready. The existing coordination logic (screens_progress check) handles this.
|
||||
|
||||
- **Option B:** Defer screen regeneration to after review submission, same as initial flow. Slightly slower end-to-end but no parallel coordination concerns.
|
||||
|
||||
**Recommendation:** Option A — trigger screens worker during edit if metadata changed. The 30-second screen generation will finish well before the user completes their review edits.
|
||||
|
||||
### Phase 6: Testing
|
||||
|
||||
**Backend unit tests:**
|
||||
- `test_edit_completed_track.py`:
|
||||
- Happy path: COMPLETE job → edit → state becomes AWAITING_REVIEW
|
||||
- With metadata: artist/title updated, screens cleared
|
||||
- Without metadata: artist/title unchanged, screens preserved
|
||||
- Auth: owner can edit, non-owner gets 403
|
||||
- State guard: non-COMPLETE jobs rejected
|
||||
- Cleanup: verify YouTube/Dropbox/GDrive/GCS deletion called
|
||||
- Brand code: verify recycled during cleanup
|
||||
- Edit count: incremented correctly
|
||||
- Timeline: event logged
|
||||
|
||||
**Frontend tests:**
|
||||
- EditTrackModal renders correctly
|
||||
- Toggle shows/hides metadata fields
|
||||
- Confirm calls API with correct payload
|
||||
- Loading state during API call
|
||||
- Redirect to review on success
|
||||
- Error display on failure
|
||||
|
||||
**E2E production test:**
|
||||
- Create job → complete → edit → re-review → verify new outputs
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
### New Files
|
||||
- `frontend/components/job/EditTrackModal.tsx` — Confirmation modal
|
||||
- `backend/tests/test_edit_completed_track.py` — Backend tests
|
||||
|
||||
### Modified Files
|
||||
- `backend/api/routes/jobs.py` — Add edit endpoint (or create `edit.py`)
|
||||
- `backend/models/job.py` — Add `edit_count` field, update STATE_TRANSITIONS
|
||||
- `frontend/lib/api.ts` — Add `editCompletedTrack()` method
|
||||
- `frontend/app/app/jobs/[[...slug]]/client.tsx` — Add Edit button to completed job view
|
||||
|
||||
### No Changes Needed
|
||||
- `backend/workers/render_video_worker.py` — Already reads current state_data
|
||||
- `backend/workers/video_worker_orchestrator.py` — Already allocates new brand code, clears outputs_deleted_at
|
||||
- `backend/workers/screens_worker.py` — Already handles missing screens
|
||||
- `backend/services/brand_code_service.py` — Allocation/recycling already works
|
||||
- `frontend/components/lyrics-review/LyricsAnalyzer.tsx` — Reused as-is
|
||||
- `frontend/components/instrumental-review/InstrumentalSelector.tsx` — Reused as-is
|
||||
|
||||
## Sequence Diagram
|
||||
|
||||
```
|
||||
User Frontend Backend Workers
|
||||
| | | |
|
||||
|-- Click "Edit" ----->| | |
|
||||
| |-- Show modal ------->| |
|
||||
|-- Confirm edit ----->| | |
|
||||
| |-- POST /edit ------->| |
|
||||
| | |-- Delete YouTube --->|
|
||||
| | |-- Delete Dropbox --->|
|
||||
| | |-- Delete GDrive ---->|
|
||||
| | |-- Delete GCS ------->|
|
||||
| | |-- Recycle brand code |
|
||||
| | |-- Reset state ------>|
|
||||
| | |-- Issue review token |
|
||||
| | |-- (if metadata changed:
|
||||
| | | trigger screens worker)
|
||||
| |<-- review_url -------| |
|
||||
|<-- Redirect to review| | |
|
||||
| | | |
|
||||
|-- Edit lyrics ------>| | |
|
||||
|-- Select instrumental| | |
|
||||
|-- Submit review ---->| | |
|
||||
| |-- POST /complete --->| |
|
||||
| | |-- Trigger render --->|
|
||||
| | | |-- Render video
|
||||
| | | |-- Encode formats
|
||||
| | | |-- Allocate brand code
|
||||
| | | |-- Upload YouTube
|
||||
| | | |-- Upload Dropbox
|
||||
| | | |-- Upload GDrive
|
||||
| | | |-- Clear outputs_deleted_at
|
||||
| | |<-- COMPLETE ---------|
|
||||
|<-- Job complete -----| | |
|
||||
```
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Cleanup fails mid-way (e.g., YouTube deleted but Dropbox fails) | Don't reset job state on critical failure. User sees error, job stays COMPLETE with partial cleanup. Admin can investigate. |
|
||||
| User abandons review after edit (outputs deleted, never re-submitted) | Job sits in AWAITING_REVIEW. Same as any unreviewed job. Could add reminder email after 24h. |
|
||||
| Race condition: two edit requests simultaneously | Use Firestore transaction for state transition. Second request fails validation (job no longer COMPLETE). |
|
||||
| Screens not ready when user submits review quickly | Existing coordination logic in pipeline handles this — render worker waits for screens_complete flag. |
|
||||
@@ -0,0 +1,464 @@
|
||||
# Lyrics Review Session Backup & Restore
|
||||
|
||||
**Date:** 2026-03-07
|
||||
**Branch:** `feat/sess-20260307-2332-lyrics-review-sessions`
|
||||
**Status:** Planning
|
||||
|
||||
## Problem
|
||||
|
||||
The lyrics review process can take 1+ hours for difficult songs. Currently, progress is saved to browser localStorage using a fragile key based on a hash of the first segment's text. This has several issues:
|
||||
|
||||
1. **Fragile matching** — hash of first segment text can collide or mismatch across jobs
|
||||
2. **Browser-local only** — lost on browser clear, different device, or incognito
|
||||
3. **No history** — only stores the latest state, no way to browse previous sessions
|
||||
4. **Confusing restore UX** — bare `window.confirm()` dialog with no context about what's being restored
|
||||
5. **No cross-job restore** — can't apply edits from a previous job to a new one (needed for style-change redeliveries)
|
||||
|
||||
## Solution Overview
|
||||
|
||||
Server-side review session storage with automatic periodic backup, rich restore UI, and cross-job session search.
|
||||
|
||||
### Phases
|
||||
|
||||
| Phase | Scope | Description |
|
||||
|-------|-------|-------------|
|
||||
| 1 | Backend API + storage | Firestore subcollection, save/list/get endpoints |
|
||||
| 2 | Auto-save from frontend | Periodic backup (60s interval, on preview, on dirty changes) |
|
||||
| 3 | Restore UI | Session browser with edit preview, auto-prompt on load |
|
||||
| 4 | Cross-job restore | Search sessions across jobs, duration mismatch warning |
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Backend API + Storage
|
||||
|
||||
### Data Model
|
||||
|
||||
Store sessions in a Firestore **subcollection**: `jobs/{jobId}/review_sessions/{sessionId}`
|
||||
|
||||
This follows the existing pattern used for worker logs (`jobs/{jobId}/logs/{logId}`).
|
||||
|
||||
#### `ReviewSession` document schema
|
||||
|
||||
```python
|
||||
{
|
||||
"session_id": str, # Auto-generated document ID
|
||||
"job_id": str, # Parent job ID (denormalized for cross-job queries)
|
||||
"user_email": str, # Who created this session
|
||||
"created_at": datetime, # First save timestamp
|
||||
"updated_at": datetime, # Last save timestamp
|
||||
"edit_count": int, # Number of edits in this session
|
||||
"is_auto_save": bool, # True for periodic auto-saves, False for manual saves
|
||||
"trigger": str, # "auto" | "preview" | "manual"
|
||||
"audio_duration_seconds": float | None, # Input audio duration (for cross-job matching)
|
||||
"artist": str | None, # From correction_data.metadata
|
||||
"title": str | None, # From correction_data.metadata
|
||||
|
||||
# Summary for list view (avoid loading full correction_data)
|
||||
"summary": {
|
||||
"total_segments": int,
|
||||
"total_words": int,
|
||||
"corrections_made": int,
|
||||
"changed_words": [ # First N changed words for preview
|
||||
{"original": str, "corrected": str, "segment_index": int}
|
||||
],
|
||||
},
|
||||
|
||||
# Full correction data (stored in GCS, NOT in Firestore doc)
|
||||
"correction_data_gcs_path": str, # "jobs/{jobId}/review_sessions/{sessionId}.json"
|
||||
}
|
||||
```
|
||||
|
||||
**Why GCS for correction_data?** CorrectionData can be large (100KB+). Firestore has a 1MB document limit, and storing large blobs in Firestore is inefficient for reads/writes. The summary field provides enough info for list views without loading full data.
|
||||
|
||||
#### Store audio duration on Job
|
||||
|
||||
Add `input_audio_duration_seconds: Optional[float]` to the `Job` model. Populate it during job creation (audio worker already has access to ffprobe). This enables cross-job duration comparison without re-computing.
|
||||
|
||||
### API Endpoints
|
||||
|
||||
All under the existing review router (`/api/review/{job_id}/...`), using the existing `require_review_auth` dependency.
|
||||
|
||||
#### `POST /api/review/{job_id}/sessions`
|
||||
|
||||
Save a review session snapshot.
|
||||
|
||||
**Request body:**
|
||||
```json
|
||||
{
|
||||
"correction_data": { ... },
|
||||
"edit_count": 42,
|
||||
"trigger": "auto",
|
||||
"summary": {
|
||||
"total_segments": 15,
|
||||
"total_words": 230,
|
||||
"corrections_made": 12,
|
||||
"changed_words": [
|
||||
{"original": "world", "corrected": "word", "segment_index": 3}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Response:** `{ "session_id": "abc123", "created_at": "..." }`
|
||||
|
||||
**Logic:**
|
||||
1. Upload `correction_data` to GCS at `jobs/{jobId}/review_sessions/{sessionId}.json`
|
||||
2. Create Firestore subcollection document with metadata + summary
|
||||
3. Denormalize `job_id`, `artist`, `title`, `audio_duration_seconds` from parent job
|
||||
|
||||
#### `GET /api/review/{job_id}/sessions`
|
||||
|
||||
List all sessions for a job (metadata only, no correction_data).
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"sessions": [
|
||||
{
|
||||
"session_id": "abc123",
|
||||
"created_at": "2026-03-07T12:00:00Z",
|
||||
"updated_at": "2026-03-07T12:15:00Z",
|
||||
"edit_count": 42,
|
||||
"trigger": "auto",
|
||||
"summary": { ... },
|
||||
"user_email": "andrew@..."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Ordered by `updated_at` descending. No pagination needed initially (unlikely to exceed 50 sessions per job).
|
||||
|
||||
#### `GET /api/review/{job_id}/sessions/{session_id}`
|
||||
|
||||
Get full session data (loads correction_data from GCS).
|
||||
|
||||
**Response:** Full session document + `correction_data` from GCS.
|
||||
|
||||
#### `DELETE /api/review/{job_id}/sessions/{session_id}`
|
||||
|
||||
Delete a session (admin only). Removes both Firestore doc and GCS file.
|
||||
|
||||
#### `GET /api/review/sessions/search` (Phase 4)
|
||||
|
||||
Cross-job session search. Requires admin auth.
|
||||
|
||||
**Query params:** `?q=<search>&limit=20`
|
||||
|
||||
Search by artist, title, or job_id across all jobs. Uses Firestore collection group query on `review_sessions`.
|
||||
|
||||
**Response:** Same as list endpoint but includes `job_id`, `artist`, `title` per session.
|
||||
|
||||
### Backend Implementation Files
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `backend/models/review_session.py` | New: `ReviewSession` dataclass |
|
||||
| `backend/models/job.py` | Add `input_audio_duration_seconds` field |
|
||||
| `backend/services/firestore_service.py` | Add session CRUD methods using subcollection pattern |
|
||||
| `backend/api/routes/review.py` | Add session endpoints |
|
||||
| `backend/workers/audio_worker.py` | Store audio duration on job after ffprobe |
|
||||
|
||||
### Cleanup / Retention
|
||||
|
||||
- Auto-save sessions older than 90 days: eligible for cleanup (can add TTL field like worker logs)
|
||||
- Manual/preview-triggered sessions: kept indefinitely
|
||||
- When a job is deleted, cascade delete its review_sessions subcollection
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Auto-Save from Frontend
|
||||
|
||||
### Save Strategy
|
||||
|
||||
Replace the current localStorage-on-every-edit approach with a smarter dual strategy:
|
||||
|
||||
1. **localStorage** — continues to save on every edit (instant, for crash recovery within same browser)
|
||||
2. **Server backup** — periodic saves to the backend API
|
||||
|
||||
### Server Backup Triggers
|
||||
|
||||
| Trigger | Condition | `trigger` field |
|
||||
|---------|-----------|-----------------|
|
||||
| Periodic timer | Every 60 seconds, IF at least 1 edit since last backup | `"auto"` |
|
||||
| Preview video | When user generates a preview video | `"preview"` |
|
||||
| Page unload | `beforeunload` event, IF dirty since last backup | `"auto"` |
|
||||
| Manual save | User clicks explicit "Save Progress" button | `"manual"` |
|
||||
|
||||
### Dirty Tracking
|
||||
|
||||
Track a `lastBackupEditCount` ref. Compare against current `history.length` to determine if there are new edits since last backup.
|
||||
|
||||
### Implementation
|
||||
|
||||
New custom hook: `useReviewSessionAutoSave()`
|
||||
|
||||
```typescript
|
||||
// frontend/hooks/use-review-session-autosave.ts
|
||||
|
||||
function useReviewSessionAutoSave({
|
||||
jobId: string,
|
||||
data: CorrectionData,
|
||||
initialData: CorrectionData,
|
||||
historyLength: number,
|
||||
isReadOnly: boolean,
|
||||
apiClient: ReviewApiClient,
|
||||
}) {
|
||||
// Track last backup state
|
||||
const lastBackupEditCount = useRef(0)
|
||||
|
||||
// Compute summary from data diff (changed words, counts)
|
||||
const computeSummary = useCallback(...)
|
||||
|
||||
// Save function (called by timer, preview trigger, etc.)
|
||||
const saveSession = useCallback(async (trigger: string) => {
|
||||
if (historyLength <= 1) return // No edits yet
|
||||
if (historyLength === lastBackupEditCount.current) return // No new edits
|
||||
|
||||
await apiClient.saveReviewSession(jobId, {
|
||||
correction_data: data,
|
||||
edit_count: historyLength - 1,
|
||||
trigger,
|
||||
summary: computeSummary(initialData, data),
|
||||
})
|
||||
|
||||
lastBackupEditCount.current = historyLength
|
||||
}, [data, historyLength, ...])
|
||||
|
||||
// 60-second interval
|
||||
useEffect(() => {
|
||||
if (isReadOnly) return
|
||||
const timer = setInterval(() => saveSession("auto"), 60_000)
|
||||
return () => clearInterval(timer)
|
||||
}, [saveSession, isReadOnly])
|
||||
|
||||
// beforeunload
|
||||
useEffect(() => {
|
||||
const handler = () => saveSession("auto")
|
||||
window.addEventListener("beforeunload", handler)
|
||||
return () => window.removeEventListener("beforeunload", handler)
|
||||
}, [saveSession])
|
||||
|
||||
return { saveSession } // Expose for preview trigger
|
||||
}
|
||||
```
|
||||
|
||||
### Frontend API Client Additions
|
||||
|
||||
```typescript
|
||||
// In frontend/lib/api.ts - lyricsReviewApi
|
||||
|
||||
async saveReviewSession(jobId, data): Promise<{ session_id: string }>
|
||||
async listReviewSessions(jobId): Promise<{ sessions: ReviewSession[] }>
|
||||
async getReviewSession(jobId, sessionId): Promise<ReviewSessionFull>
|
||||
async deleteReviewSession(jobId, sessionId): Promise<void>
|
||||
async searchReviewSessions(query): Promise<{ sessions: ReviewSession[] }> // Phase 4
|
||||
```
|
||||
|
||||
### Frontend Files
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `frontend/hooks/use-review-session-autosave.ts` | New: auto-save hook |
|
||||
| `frontend/lib/api.ts` | Add session API methods |
|
||||
| `frontend/lib/lyrics-review/types.ts` | Add `ReviewSession`, `ReviewSessionSummary` types |
|
||||
| `frontend/components/lyrics-review/LyricsAnalyzer.tsx` | Wire up auto-save hook, add "Save Progress" button |
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Restore UI
|
||||
|
||||
### Behavior on Load
|
||||
|
||||
When `LyricsAnalyzer` mounts:
|
||||
|
||||
1. Call `GET /api/review/{job_id}/sessions` to check for saved sessions
|
||||
2. **If sessions exist**: show the Session Restore dialog (replaces the old `window.confirm`)
|
||||
3. **If no sessions**: proceed normally (also check localStorage as fallback for backward compat)
|
||||
|
||||
### Session Restore Dialog
|
||||
|
||||
A modal dialog with a split-pane layout:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Saved Review Sessions [×] │
|
||||
├───────────────────────┬─────────────────────────────────┤
|
||||
│ Session List │ Edit Preview │
|
||||
│ │ │
|
||||
│ ▸ Mar 7, 2:15 PM │ Segment 3: │
|
||||
│ 42 edits · preview │ "hello world" → "hello word" │
|
||||
│ [Most recent] │ │
|
||||
│ │ Segment 7: │
|
||||
│ ▸ Mar 7, 1:30 PM │ "singing loud" → "singing out"│
|
||||
│ 38 edits · auto │ │
|
||||
│ │ Segment 12: │
|
||||
│ ▸ Mar 6, 11:00 PM │ (deleted word "um") │
|
||||
│ 15 edits · auto │ │
|
||||
│ │ ... +39 more changes │
|
||||
│ │ │
|
||||
├───────────────────────┴─────────────────────────────────┤
|
||||
│ [Start Fresh] [Restore Selected] │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
#### Session List (left pane)
|
||||
|
||||
Each session shows:
|
||||
- Date/time (relative: "2 hours ago", absolute on hover)
|
||||
- Edit count
|
||||
- Trigger badge: `auto` / `preview` / `manual`
|
||||
- Selected state (highlight)
|
||||
|
||||
#### Edit Preview (right pane)
|
||||
|
||||
When a session is selected, show a compact diff view:
|
||||
- List of changed words grouped by segment
|
||||
- Show original → corrected text
|
||||
- Color-coded: green for additions, red for deletions, yellow for changes
|
||||
- Scroll if many edits, with a summary count at bottom
|
||||
|
||||
#### Actions
|
||||
|
||||
- **Start Fresh** — dismiss dialog, use initial data (no restore)
|
||||
- **Restore Selected** — load the selected session's full `correction_data`, replace current state
|
||||
|
||||
### "Save Progress" Button & Session Browser
|
||||
|
||||
Add to the LyricsAnalyzer toolbar:
|
||||
- **Save Progress** button (triggers manual save)
|
||||
- **Session History** button — opens the same Session Restore dialog at any time (not just on load)
|
||||
|
||||
### Frontend Files
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `frontend/components/lyrics-review/SessionRestoreDialog.tsx` | New: the restore modal |
|
||||
| `frontend/components/lyrics-review/SessionListItem.tsx` | New: session list item component |
|
||||
| `frontend/components/lyrics-review/SessionEditPreview.tsx` | New: edit diff preview |
|
||||
| `frontend/components/lyrics-review/LyricsAnalyzer.tsx` | Mount dialog on load, add toolbar buttons |
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Cross-Job Session Restore
|
||||
|
||||
### Power User Feature
|
||||
|
||||
Add a tab/toggle in the Session Restore dialog: **"This Job"** | **"All Jobs"**
|
||||
|
||||
When "All Jobs" is selected:
|
||||
- Show a search box (search by artist, title, or job ID)
|
||||
- Query `GET /api/review/sessions/search?q=...`
|
||||
- Results show sessions from other jobs with job context (artist - title, job ID)
|
||||
|
||||
### Duration Mismatch Warning
|
||||
|
||||
When restoring from a different job:
|
||||
|
||||
1. Compare `session.audio_duration_seconds` with current job's `audio_duration_seconds`
|
||||
2. If durations differ by more than 2 seconds, show a warning:
|
||||
|
||||
```
|
||||
⚠️ Duration Mismatch
|
||||
|
||||
The selected session is from a track with a different duration:
|
||||
This job: 3:42 (222s)
|
||||
Source session: 4:01 (241s)
|
||||
|
||||
Timing alignment may not match. Word timestamps from the
|
||||
source session will be preserved as-is.
|
||||
|
||||
[Cancel] [Restore Anyway]
|
||||
```
|
||||
|
||||
3. If durations match (within 2s), restore silently
|
||||
|
||||
### Collection Group Index
|
||||
|
||||
Firestore collection group queries require a **composite index** on `review_sessions`:
|
||||
- Fields: `artist` (ASC), `title` (ASC), `updated_at` (DESC)
|
||||
- Add via `firestore.indexes.json` or Pulumi
|
||||
|
||||
### Backend: Search Implementation
|
||||
|
||||
The search endpoint uses Firestore collection group query:
|
||||
|
||||
```python
|
||||
@router.get("/sessions/search")
|
||||
async def search_sessions(q: str, limit: int = 20, auth=Depends(require_admin)):
|
||||
# Collection group query across all jobs' review_sessions
|
||||
sessions_ref = db.collection_group("review_sessions")
|
||||
|
||||
# Search by artist OR title containing query (case-insensitive prefix)
|
||||
# Firestore doesn't support LIKE queries, so we use range queries
|
||||
# for prefix matching, or store lowercase variants for matching
|
||||
results = sessions_ref.where("artist_lower", ">=", q.lower())
|
||||
.where("artist_lower", "<=", q.lower() + "\uf8ff")
|
||||
.limit(limit)
|
||||
.get()
|
||||
|
||||
# Also search by title and job_id, merge results
|
||||
...
|
||||
```
|
||||
|
||||
**Note:** Firestore's text search is limited. For the MVP, searching by exact job_id + prefix matching on artist/title should be sufficient. If full-text search is needed later, consider Algolia or a simple in-memory filter on the client after fetching recent sessions.
|
||||
|
||||
### Frontend Files
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `frontend/components/lyrics-review/SessionRestoreDialog.tsx` | Add "All Jobs" tab, search input |
|
||||
| `frontend/components/lyrics-review/DurationWarning.tsx` | New: duration mismatch warning |
|
||||
| `frontend/lib/api.ts` | Add `searchReviewSessions()` |
|
||||
|
||||
---
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Backend Tests
|
||||
|
||||
| Test | Type | What |
|
||||
|------|------|------|
|
||||
| `test_review_session_crud.py` | Unit | Create, list, get, delete sessions via Firestore service |
|
||||
| `test_review_session_endpoints.py` | Integration | API endpoint tests with auth |
|
||||
| `test_review_session_gcs.py` | Unit | GCS upload/download of correction data |
|
||||
| `test_audio_duration_storage.py` | Unit | Duration stored on job creation |
|
||||
|
||||
### Frontend Tests
|
||||
|
||||
| Test | Type | What |
|
||||
|------|------|------|
|
||||
| `SessionRestoreDialog.test.tsx` | Unit | Renders session list, selection, restore action |
|
||||
| `SessionEditPreview.test.tsx` | Unit | Diff computation and display |
|
||||
| `use-review-session-autosave.test.ts` | Unit | Timer behavior, dirty tracking, save triggers |
|
||||
| `lyrics-review-sessions.spec.ts` | E2E | Full flow: edit → auto-save → reload → restore |
|
||||
|
||||
---
|
||||
|
||||
## Migration / Backward Compatibility
|
||||
|
||||
1. **localStorage fallback** — keep the existing localStorage load/save as a fallback. If no server sessions exist, check localStorage. Gradually phase out once server sessions are proven reliable.
|
||||
2. **No schema migration needed** — new Firestore subcollection, new GCS paths. No existing data affected.
|
||||
3. **Feature flag** — not needed; server session save is additive. The restore dialog replaces `window.confirm()` which is strictly better.
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **Session limit per job?** — Should we cap at e.g. 50 sessions per job and auto-prune oldest auto-saves? Probably yes to avoid unbounded growth.
|
||||
2. **Session deduplication** — If user makes 0 additional edits between auto-save intervals, we skip the save (dirty tracking handles this). But should we also deduplicate if the correction_data hasn't actually changed (e.g. undo then redo)?
|
||||
3. **Compression** — CorrectionData JSON can be large. Should we gzip before storing in GCS? Probably not for MVP; GCS handles compression at the storage layer.
|
||||
|
||||
---
|
||||
|
||||
## Estimated Scope
|
||||
|
||||
| Phase | Backend | Frontend | Total |
|
||||
|-------|---------|----------|-------|
|
||||
| 1 | ~300 lines | 0 | Medium |
|
||||
| 2 | 0 | ~150 lines | Small |
|
||||
| 3 | 0 | ~400 lines | Medium |
|
||||
| 4 | ~100 lines | ~200 lines | Medium |
|
||||
| Tests | ~300 lines | ~300 lines | Medium |
|
||||
|
||||
Phases 1-3 form the core feature. Phase 4 (cross-job) can be deferred to a follow-up PR if needed.
|
||||
@@ -19,6 +19,8 @@ jest.mock('@/lib/api', () => ({
|
||||
searchStandalone: jest.fn(),
|
||||
searchAudio: jest.fn(),
|
||||
createJobFromSearch: jest.fn(),
|
||||
createJobFromUrl: jest.fn(),
|
||||
uploadJobSmart: jest.fn(),
|
||||
createJob: jest.fn(),
|
||||
deleteJob: jest.fn(),
|
||||
uploadFile: jest.fn(),
|
||||
@@ -350,3 +352,496 @@ describe('api module — style upload methods', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Private/Published visibility — all audio source paths
|
||||
// ---------------------------------------------------------------------------
|
||||
// This tests the core fix: URL and upload fallback paths must respect the
|
||||
// user's visibility choice (is_private), just like the search path does.
|
||||
// Previously, URL/upload created the job in Step 2 before the user reached
|
||||
// the Visibility step (Step 3), so is_private was always false.
|
||||
|
||||
describe('Visibility (is_private) — respected across all audio source paths', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
// -- Search path --
|
||||
|
||||
it('search path: is_private=true is passed to createJobFromSearch', async () => {
|
||||
mockApi.createJobFromSearch.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'search-private-job',
|
||||
message: 'Created',
|
||||
})
|
||||
|
||||
await api.createJobFromSearch({
|
||||
search_session_id: 'sess-123',
|
||||
selection_index: 0,
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
is_private: true,
|
||||
})
|
||||
|
||||
expect(mockApi.createJobFromSearch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ is_private: true })
|
||||
)
|
||||
})
|
||||
|
||||
it('search path: is_private=false is passed to createJobFromSearch', async () => {
|
||||
mockApi.createJobFromSearch.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'search-public-job',
|
||||
message: 'Created',
|
||||
})
|
||||
|
||||
await api.createJobFromSearch({
|
||||
search_session_id: 'sess-456',
|
||||
selection_index: 0,
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
is_private: false,
|
||||
})
|
||||
|
||||
expect(mockApi.createJobFromSearch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ is_private: false })
|
||||
)
|
||||
})
|
||||
|
||||
// -- URL fallback path --
|
||||
|
||||
it('URL path: is_private=true is passed to createJobFromUrl', async () => {
|
||||
mockApi.createJobFromUrl.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'url-private-job',
|
||||
message: 'Created',
|
||||
})
|
||||
|
||||
// Simulate what GuidedJobFlow.handleConfirm() does for URL path
|
||||
await api.createJobFromUrl(
|
||||
'https://youtube.com/watch?v=abc',
|
||||
'Test Artist',
|
||||
'Test Song',
|
||||
{ is_private: true }
|
||||
)
|
||||
|
||||
expect(mockApi.createJobFromUrl).toHaveBeenCalledWith(
|
||||
'https://youtube.com/watch?v=abc',
|
||||
'Test Artist',
|
||||
'Test Song',
|
||||
expect.objectContaining({ is_private: true })
|
||||
)
|
||||
})
|
||||
|
||||
it('URL path: is_private=false is passed to createJobFromUrl', async () => {
|
||||
mockApi.createJobFromUrl.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'url-public-job',
|
||||
message: 'Created',
|
||||
})
|
||||
|
||||
await api.createJobFromUrl(
|
||||
'https://youtube.com/watch?v=abc',
|
||||
'Test Artist',
|
||||
'Test Song',
|
||||
{ is_private: false }
|
||||
)
|
||||
|
||||
expect(mockApi.createJobFromUrl).toHaveBeenCalledWith(
|
||||
'https://youtube.com/watch?v=abc',
|
||||
'Test Artist',
|
||||
'Test Song',
|
||||
expect.objectContaining({ is_private: false })
|
||||
)
|
||||
})
|
||||
|
||||
// -- Upload fallback path --
|
||||
|
||||
it('upload path: is_private=true is passed to uploadJobSmart', async () => {
|
||||
mockApi.uploadJobSmart.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'upload-private-job',
|
||||
message: 'Created',
|
||||
})
|
||||
|
||||
const mockFile = new File(['audio'], 'song.mp3', { type: 'audio/mpeg' })
|
||||
|
||||
// Simulate what GuidedJobFlow.handleConfirm() does for upload path
|
||||
await api.uploadJobSmart(mockFile, 'Test Artist', 'Test Song', {
|
||||
is_private: true,
|
||||
})
|
||||
|
||||
expect(mockApi.uploadJobSmart).toHaveBeenCalledWith(
|
||||
mockFile,
|
||||
'Test Artist',
|
||||
'Test Song',
|
||||
expect.objectContaining({ is_private: true })
|
||||
)
|
||||
})
|
||||
|
||||
it('upload path: is_private=false is passed to uploadJobSmart', async () => {
|
||||
mockApi.uploadJobSmart.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'upload-public-job',
|
||||
message: 'Created',
|
||||
})
|
||||
|
||||
const mockFile = new File(['audio'], 'song.flac', { type: 'audio/flac' })
|
||||
|
||||
await api.uploadJobSmart(mockFile, 'Test Artist', 'Test Song', {
|
||||
is_private: false,
|
||||
})
|
||||
|
||||
expect(mockApi.uploadJobSmart).toHaveBeenCalledWith(
|
||||
mockFile,
|
||||
'Test Artist',
|
||||
'Test Song',
|
||||
expect.objectContaining({ is_private: false })
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// handleConfirm logic — simulates the three code paths in GuidedJobFlow
|
||||
// ---------------------------------------------------------------------------
|
||||
// These tests replicate the exact branching logic inside handleConfirm()
|
||||
// to verify all three audio source paths produce correct API calls.
|
||||
|
||||
describe('GuidedJobFlow handleConfirm — all three audio source paths', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
/**
|
||||
* Helper that mirrors GuidedJobFlow.handleConfirm() logic.
|
||||
* This lets us unit-test the branching without rendering the full component.
|
||||
*/
|
||||
async function simulateHandleConfirm(params: {
|
||||
audioSource: 'search' | 'url' | 'upload'
|
||||
isPrivate: boolean
|
||||
artist: string
|
||||
title: string
|
||||
displayArtist: string
|
||||
displayTitle: string
|
||||
// search-specific
|
||||
searchSessionId?: string | null
|
||||
selectedResultIndex?: number | null
|
||||
// url-specific
|
||||
pendingUrl?: string | null
|
||||
// upload-specific
|
||||
pendingFile?: File | null
|
||||
}): Promise<string> {
|
||||
const effectiveArtist = params.displayArtist.trim() || params.artist.trim()
|
||||
const effectiveTitle = params.displayTitle.trim() || params.title.trim()
|
||||
|
||||
if (params.audioSource === 'url' && params.pendingUrl) {
|
||||
const response = await api.createJobFromUrl(
|
||||
params.pendingUrl, effectiveArtist, effectiveTitle,
|
||||
{ is_private: params.isPrivate }
|
||||
)
|
||||
return response.job_id
|
||||
} else if (params.audioSource === 'upload' && params.pendingFile) {
|
||||
const response = await api.uploadJobSmart(
|
||||
params.pendingFile, effectiveArtist, effectiveTitle,
|
||||
{ is_private: params.isPrivate }
|
||||
)
|
||||
return response.job_id
|
||||
} else if (params.searchSessionId && params.selectedResultIndex !== null) {
|
||||
const response = await api.createJobFromSearch({
|
||||
search_session_id: params.searchSessionId,
|
||||
selection_index: params.selectedResultIndex!,
|
||||
artist: params.artist,
|
||||
title: params.title,
|
||||
display_artist: params.displayArtist.trim() || undefined,
|
||||
display_title: params.displayTitle.trim() || undefined,
|
||||
is_private: params.isPrivate,
|
||||
})
|
||||
return response.job_id
|
||||
}
|
||||
throw new Error('Missing audio source')
|
||||
}
|
||||
|
||||
// -- Search path --
|
||||
|
||||
it('search + private: creates job via createJobFromSearch with is_private=true', async () => {
|
||||
mockApi.createJobFromSearch.mockResolvedValue({
|
||||
status: 'success', job_id: 'sp-001', message: 'Created',
|
||||
})
|
||||
|
||||
const jobId = await simulateHandleConfirm({
|
||||
audioSource: 'search',
|
||||
isPrivate: true,
|
||||
artist: 'ABBA',
|
||||
title: 'Waterloo',
|
||||
displayArtist: '',
|
||||
displayTitle: '',
|
||||
searchSessionId: 'sess-abc',
|
||||
selectedResultIndex: 0,
|
||||
})
|
||||
|
||||
expect(jobId).toBe('sp-001')
|
||||
expect(mockApi.createJobFromSearch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ is_private: true })
|
||||
)
|
||||
expect(mockApi.createJobFromUrl).not.toHaveBeenCalled()
|
||||
expect(mockApi.uploadJobSmart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('search + published: creates job via createJobFromSearch with is_private=false', async () => {
|
||||
mockApi.createJobFromSearch.mockResolvedValue({
|
||||
status: 'success', job_id: 'sp-002', message: 'Created',
|
||||
})
|
||||
|
||||
const jobId = await simulateHandleConfirm({
|
||||
audioSource: 'search',
|
||||
isPrivate: false,
|
||||
artist: 'ABBA',
|
||||
title: 'Waterloo',
|
||||
displayArtist: '',
|
||||
displayTitle: '',
|
||||
searchSessionId: 'sess-def',
|
||||
selectedResultIndex: 2,
|
||||
})
|
||||
|
||||
expect(jobId).toBe('sp-002')
|
||||
expect(mockApi.createJobFromSearch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ is_private: false })
|
||||
)
|
||||
})
|
||||
|
||||
it('search + display overrides: display values passed correctly', async () => {
|
||||
mockApi.createJobFromSearch.mockResolvedValue({
|
||||
status: 'success', job_id: 'sp-003', message: 'Created',
|
||||
})
|
||||
|
||||
await simulateHandleConfirm({
|
||||
audioSource: 'search',
|
||||
isPrivate: true,
|
||||
artist: 'ABBA',
|
||||
title: 'Waterloo',
|
||||
displayArtist: 'Abba (Karaoke)',
|
||||
displayTitle: 'Waterloo (Live)',
|
||||
searchSessionId: 'sess-ghi',
|
||||
selectedResultIndex: 0,
|
||||
})
|
||||
|
||||
expect(mockApi.createJobFromSearch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
display_artist: 'Abba (Karaoke)',
|
||||
display_title: 'Waterloo (Live)',
|
||||
is_private: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
// -- URL fallback path --
|
||||
|
||||
it('URL + private: creates job via createJobFromUrl with is_private=true', async () => {
|
||||
mockApi.createJobFromUrl.mockResolvedValue({
|
||||
status: 'success', job_id: 'url-001', message: 'Created',
|
||||
})
|
||||
|
||||
const jobId = await simulateHandleConfirm({
|
||||
audioSource: 'url',
|
||||
isPrivate: true,
|
||||
artist: 'Dion Anthony Ruben',
|
||||
title: 'Whatever Rock',
|
||||
displayArtist: '',
|
||||
displayTitle: '',
|
||||
pendingUrl: 'https://www.youtube.com/watch?v=b8m91qLtWZM',
|
||||
})
|
||||
|
||||
expect(jobId).toBe('url-001')
|
||||
expect(mockApi.createJobFromUrl).toHaveBeenCalledWith(
|
||||
'https://www.youtube.com/watch?v=b8m91qLtWZM',
|
||||
'Dion Anthony Ruben',
|
||||
'Whatever Rock',
|
||||
{ is_private: true }
|
||||
)
|
||||
expect(mockApi.createJobFromSearch).not.toHaveBeenCalled()
|
||||
expect(mockApi.uploadJobSmart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('URL + published: creates job via createJobFromUrl with is_private=false', async () => {
|
||||
mockApi.createJobFromUrl.mockResolvedValue({
|
||||
status: 'success', job_id: 'url-002', message: 'Created',
|
||||
})
|
||||
|
||||
const jobId = await simulateHandleConfirm({
|
||||
audioSource: 'url',
|
||||
isPrivate: false,
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
displayArtist: '',
|
||||
displayTitle: '',
|
||||
pendingUrl: 'https://youtube.com/watch?v=xyz',
|
||||
})
|
||||
|
||||
expect(jobId).toBe('url-002')
|
||||
expect(mockApi.createJobFromUrl).toHaveBeenCalledWith(
|
||||
'https://youtube.com/watch?v=xyz',
|
||||
'Test Artist',
|
||||
'Test Song',
|
||||
{ is_private: false }
|
||||
)
|
||||
})
|
||||
|
||||
it('URL + display overrides: effective artist/title used (not search values)', async () => {
|
||||
mockApi.createJobFromUrl.mockResolvedValue({
|
||||
status: 'success', job_id: 'url-003', message: 'Created',
|
||||
})
|
||||
|
||||
await simulateHandleConfirm({
|
||||
audioSource: 'url',
|
||||
isPrivate: false,
|
||||
artist: 'Original Search Artist',
|
||||
title: 'Original Search Title',
|
||||
displayArtist: 'Display Artist Override',
|
||||
displayTitle: 'Display Title Override',
|
||||
pendingUrl: 'https://youtube.com/watch?v=test',
|
||||
})
|
||||
|
||||
// URL/upload paths use effective artist/title (display overrides or search values)
|
||||
expect(mockApi.createJobFromUrl).toHaveBeenCalledWith(
|
||||
'https://youtube.com/watch?v=test',
|
||||
'Display Artist Override', // display override used, not search value
|
||||
'Display Title Override', // display override used, not search value
|
||||
{ is_private: false }
|
||||
)
|
||||
})
|
||||
|
||||
// -- Upload fallback path --
|
||||
|
||||
it('upload + private: creates job via uploadJobSmart with is_private=true', async () => {
|
||||
mockApi.uploadJobSmart.mockResolvedValue({
|
||||
status: 'success', job_id: 'upl-001', message: 'Created',
|
||||
})
|
||||
|
||||
const mockFile = new File(['audio-data'], 'my-song.flac', { type: 'audio/flac' })
|
||||
|
||||
const jobId = await simulateHandleConfirm({
|
||||
audioSource: 'upload',
|
||||
isPrivate: true,
|
||||
artist: 'My Band',
|
||||
title: 'Our Song',
|
||||
displayArtist: '',
|
||||
displayTitle: '',
|
||||
pendingFile: mockFile,
|
||||
})
|
||||
|
||||
expect(jobId).toBe('upl-001')
|
||||
expect(mockApi.uploadJobSmart).toHaveBeenCalledWith(
|
||||
mockFile,
|
||||
'My Band',
|
||||
'Our Song',
|
||||
{ is_private: true }
|
||||
)
|
||||
expect(mockApi.createJobFromSearch).not.toHaveBeenCalled()
|
||||
expect(mockApi.createJobFromUrl).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('upload + published: creates job via uploadJobSmart with is_private=false', async () => {
|
||||
mockApi.uploadJobSmart.mockResolvedValue({
|
||||
status: 'success', job_id: 'upl-002', message: 'Created',
|
||||
})
|
||||
|
||||
const mockFile = new File(['audio-data'], 'track.mp3', { type: 'audio/mpeg' })
|
||||
|
||||
const jobId = await simulateHandleConfirm({
|
||||
audioSource: 'upload',
|
||||
isPrivate: false,
|
||||
artist: 'Another Band',
|
||||
title: 'Public Song',
|
||||
displayArtist: '',
|
||||
displayTitle: '',
|
||||
pendingFile: mockFile,
|
||||
})
|
||||
|
||||
expect(jobId).toBe('upl-002')
|
||||
expect(mockApi.uploadJobSmart).toHaveBeenCalledWith(
|
||||
mockFile,
|
||||
'Another Band',
|
||||
'Public Song',
|
||||
{ is_private: false }
|
||||
)
|
||||
})
|
||||
|
||||
it('upload + display overrides: effective artist/title used', async () => {
|
||||
mockApi.uploadJobSmart.mockResolvedValue({
|
||||
status: 'success', job_id: 'upl-003', message: 'Created',
|
||||
})
|
||||
|
||||
const mockFile = new File(['audio'], 'song.wav', { type: 'audio/wav' })
|
||||
|
||||
await simulateHandleConfirm({
|
||||
audioSource: 'upload',
|
||||
isPrivate: true,
|
||||
artist: 'Search Artist',
|
||||
title: 'Search Title',
|
||||
displayArtist: 'Custom Display Artist',
|
||||
displayTitle: 'Custom Display Title',
|
||||
pendingFile: mockFile,
|
||||
})
|
||||
|
||||
expect(mockApi.uploadJobSmart).toHaveBeenCalledWith(
|
||||
mockFile,
|
||||
'Custom Display Artist', // display override used
|
||||
'Custom Display Title', // display override used
|
||||
{ is_private: true }
|
||||
)
|
||||
})
|
||||
|
||||
// -- Error case: missing audio source --
|
||||
|
||||
it('throws when no audio source data is available', async () => {
|
||||
await expect(simulateHandleConfirm({
|
||||
audioSource: 'search',
|
||||
isPrivate: true,
|
||||
artist: 'Test',
|
||||
title: 'Test',
|
||||
displayArtist: '',
|
||||
displayTitle: '',
|
||||
searchSessionId: null,
|
||||
selectedResultIndex: null,
|
||||
})).rejects.toThrow('Missing audio source')
|
||||
})
|
||||
|
||||
// -- Mutual exclusivity: only one API is called per path --
|
||||
|
||||
it('URL path never calls search or upload APIs', async () => {
|
||||
mockApi.createJobFromUrl.mockResolvedValue({
|
||||
status: 'success', job_id: 'excl-url', message: 'Created',
|
||||
})
|
||||
|
||||
await simulateHandleConfirm({
|
||||
audioSource: 'url',
|
||||
isPrivate: true,
|
||||
artist: 'A', title: 'B',
|
||||
displayArtist: '', displayTitle: '',
|
||||
pendingUrl: 'https://youtube.com/watch?v=123',
|
||||
})
|
||||
|
||||
expect(mockApi.createJobFromUrl).toHaveBeenCalledTimes(1)
|
||||
expect(mockApi.createJobFromSearch).not.toHaveBeenCalled()
|
||||
expect(mockApi.uploadJobSmart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('upload path never calls search or URL APIs', async () => {
|
||||
mockApi.uploadJobSmart.mockResolvedValue({
|
||||
status: 'success', job_id: 'excl-upl', message: 'Created',
|
||||
})
|
||||
|
||||
const mockFile = new File(['x'], 'x.mp3', { type: 'audio/mpeg' })
|
||||
await simulateHandleConfirm({
|
||||
audioSource: 'upload',
|
||||
isPrivate: false,
|
||||
artist: 'A', title: 'B',
|
||||
displayArtist: '', displayTitle: '',
|
||||
pendingFile: mockFile,
|
||||
})
|
||||
|
||||
expect(mockApi.uploadJobSmart).toHaveBeenCalledTimes(1)
|
||||
expect(mockApi.createJobFromSearch).not.toHaveBeenCalled()
|
||||
expect(mockApi.createJobFromUrl).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Tests for the TenantJobFlow component.
|
||||
*
|
||||
* Key invariants verified:
|
||||
* - api.createJobWithUploadUrls is called with existing_instrumental: true and is_private: true
|
||||
* - api.uploadToSignedUrl is called for both audio and instrumental files
|
||||
* - api.completeJobUpload is called with correct file types
|
||||
* - Submit button is disabled until all 4 fields are filled
|
||||
* - Success and error states render correctly
|
||||
*/
|
||||
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// Mock api module
|
||||
jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
createJobWithUploadUrls: jest.fn(),
|
||||
uploadToSignedUrl: jest.fn(),
|
||||
completeJobUpload: jest.fn(),
|
||||
},
|
||||
ApiError: class ApiError extends Error {
|
||||
status: number
|
||||
constructor(message: string, status: number) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/tenant', () => ({
|
||||
useTenant: jest.fn(() => ({
|
||||
branding: {
|
||||
site_title: 'Test Tenant',
|
||||
primary_color: '#ff0000',
|
||||
secondary_color: '#0000ff',
|
||||
},
|
||||
features: {},
|
||||
isDefault: false,
|
||||
tenant: { id: 'test-tenant' },
|
||||
})),
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/auth', () => ({
|
||||
useAuth: jest.fn(() => ({ user: null })),
|
||||
}))
|
||||
|
||||
const mockApi = api as jest.Mocked<typeof api>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API contract tests — verifies correct API calls for tenant upload flow
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('TenantJobFlow — API contract', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('createJobWithUploadUrls is called with existing_instrumental and is_private flags', async () => {
|
||||
mockApi.createJobWithUploadUrls.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'tenant-job-123',
|
||||
message: 'Created',
|
||||
upload_urls: [
|
||||
{ file_type: 'audio', gcs_path: 'path/audio.mp3', upload_url: 'https://signed-url-audio', content_type: 'audio/mpeg' },
|
||||
{ file_type: 'existing_instrumental', gcs_path: 'path/instrumental.mp3', upload_url: 'https://signed-url-inst', content_type: 'audio/mpeg' },
|
||||
],
|
||||
server_version: '1.0',
|
||||
})
|
||||
|
||||
// Simulate what TenantJobFlow.handleSubmit() does
|
||||
const files = [
|
||||
{ filename: 'song.mp3', content_type: 'audio/mpeg', file_type: 'audio' },
|
||||
{ filename: 'inst.mp3', content_type: 'audio/mpeg', file_type: 'existing_instrumental' },
|
||||
]
|
||||
|
||||
await api.createJobWithUploadUrls('Test Artist', 'Test Title', files, {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
|
||||
expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledWith(
|
||||
'Test Artist',
|
||||
'Test Title',
|
||||
files,
|
||||
{ is_private: true, existing_instrumental: true },
|
||||
)
|
||||
})
|
||||
|
||||
it('uploadToSignedUrl is called for both audio and instrumental', async () => {
|
||||
mockApi.uploadToSignedUrl.mockResolvedValue(undefined)
|
||||
|
||||
const audioFile = new File(['audio'], 'song.mp3', { type: 'audio/mpeg' })
|
||||
const instFile = new File(['inst'], 'inst.mp3', { type: 'audio/mpeg' })
|
||||
|
||||
// Upload audio
|
||||
await api.uploadToSignedUrl('https://signed-url-audio', audioFile, 'audio/mpeg')
|
||||
// Upload instrumental
|
||||
await api.uploadToSignedUrl('https://signed-url-inst', instFile, 'audio/mpeg')
|
||||
|
||||
expect(mockApi.uploadToSignedUrl).toHaveBeenCalledTimes(2)
|
||||
expect(mockApi.uploadToSignedUrl).toHaveBeenCalledWith(
|
||||
'https://signed-url-audio', audioFile, 'audio/mpeg',
|
||||
)
|
||||
expect(mockApi.uploadToSignedUrl).toHaveBeenCalledWith(
|
||||
'https://signed-url-inst', instFile, 'audio/mpeg',
|
||||
)
|
||||
})
|
||||
|
||||
it('completeJobUpload is called with both audio and existing_instrumental types', async () => {
|
||||
mockApi.completeJobUpload.mockResolvedValue({
|
||||
status: 'success',
|
||||
message: 'Processing started',
|
||||
})
|
||||
|
||||
await api.completeJobUpload('tenant-job-123', ['audio', 'existing_instrumental'])
|
||||
|
||||
expect(mockApi.completeJobUpload).toHaveBeenCalledWith(
|
||||
'tenant-job-123',
|
||||
['audio', 'existing_instrumental'],
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error handling tests — verifies error paths in handleSubmit
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('TenantJobFlow — error handling', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('ApiError message is surfaced when createJobWithUploadUrls fails', async () => {
|
||||
const { ApiError } = require('@/lib/api')
|
||||
mockApi.createJobWithUploadUrls.mockRejectedValue(
|
||||
new ApiError('Tenant file upload is not enabled', 403),
|
||||
)
|
||||
|
||||
// Simulate handleSubmit error path
|
||||
let errorMessage = ''
|
||||
try {
|
||||
await api.createJobWithUploadUrls('Artist', 'Title', [], {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
} catch (err: any) {
|
||||
errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'
|
||||
}
|
||||
|
||||
expect(errorMessage).toBe('Tenant file upload is not enabled')
|
||||
})
|
||||
|
||||
it('generic errors get fallback message', async () => {
|
||||
mockApi.createJobWithUploadUrls.mockRejectedValue(new TypeError('Network error'))
|
||||
|
||||
const { ApiError } = require('@/lib/api')
|
||||
let errorMessage = ''
|
||||
try {
|
||||
await api.createJobWithUploadUrls('Artist', 'Title', [], {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
} catch (err: any) {
|
||||
errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'
|
||||
}
|
||||
|
||||
expect(errorMessage).toBe('Something went wrong. Please try again.')
|
||||
})
|
||||
|
||||
it('missing upload URL throws ApiError', async () => {
|
||||
mockApi.createJobWithUploadUrls.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'job-123',
|
||||
message: 'Created',
|
||||
upload_urls: [
|
||||
// Missing 'audio' file type — only has instrumental
|
||||
{ file_type: 'existing_instrumental', gcs_path: 'p', upload_url: 'https://inst', content_type: 'audio/mpeg' },
|
||||
],
|
||||
server_version: '1.0',
|
||||
})
|
||||
|
||||
const response = await api.createJobWithUploadUrls('Artist', 'Title', [], {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
|
||||
// The component checks: find(u => u.file_type === "audio")
|
||||
const audioUrl = response.upload_urls.find((u: any) => u.file_type === 'audio')
|
||||
expect(audioUrl).toBeUndefined()
|
||||
})
|
||||
|
||||
it('upload failure on instrumental after successful mixed upload is catchable', async () => {
|
||||
mockApi.uploadToSignedUrl
|
||||
.mockResolvedValueOnce(undefined) // mixed succeeds
|
||||
.mockRejectedValueOnce(new Error('Upload timeout')) // instrumental fails
|
||||
|
||||
const audioFile = new File(['audio'], 'song.mp3', { type: 'audio/mpeg' })
|
||||
const instFile = new File(['inst'], 'inst.mp3', { type: 'audio/mpeg' })
|
||||
|
||||
// First upload succeeds
|
||||
await api.uploadToSignedUrl('https://url-audio', audioFile, 'audio/mpeg')
|
||||
|
||||
// Second upload fails
|
||||
await expect(
|
||||
api.uploadToSignedUrl('https://url-inst', instFile, 'audio/mpeg'),
|
||||
).rejects.toThrow('Upload timeout')
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Form validation logic tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('TenantJobFlow — form validation', () => {
|
||||
it('canSubmit requires all 4 fields and idle phase', () => {
|
||||
// Replicate the canSubmit logic from TenantJobFlow
|
||||
const canSubmit = (artist: string, title: string, mixed: File | null, inst: File | null, phase: string) =>
|
||||
!!(artist.trim() && title.trim() && mixed && inst && phase === 'idle')
|
||||
|
||||
const file = new File(['data'], 'song.mp3', { type: 'audio/mpeg' })
|
||||
|
||||
// All fields filled + idle → true
|
||||
expect(canSubmit('Artist', 'Title', file, file, 'idle')).toBe(true)
|
||||
|
||||
// Missing artist → false
|
||||
expect(canSubmit('', 'Title', file, file, 'idle')).toBe(false)
|
||||
|
||||
// Whitespace-only artist → false
|
||||
expect(canSubmit(' ', 'Title', file, file, 'idle')).toBe(false)
|
||||
|
||||
// Missing title → false
|
||||
expect(canSubmit('Artist', '', file, file, 'idle')).toBe(false)
|
||||
|
||||
// Missing mixed file → false
|
||||
expect(canSubmit('Artist', 'Title', null, file, 'idle')).toBe(false)
|
||||
|
||||
// Missing instrumental file → false
|
||||
expect(canSubmit('Artist', 'Title', file, null, 'idle')).toBe(false)
|
||||
|
||||
// Submitting phase → false
|
||||
expect(canSubmit('Artist', 'Title', file, file, 'creating')).toBe(false)
|
||||
expect(canSubmit('Artist', 'Title', file, file, 'uploading-mixed')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Component interface tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('TenantJobFlow — component interface', () => {
|
||||
it('exports TenantJobFlow as a named export', async () => {
|
||||
const mod = await import('@/components/job/TenantJobFlow')
|
||||
expect(typeof mod.TenantJobFlow).toBe('function')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,690 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import {
|
||||
adminApi,
|
||||
EditReviewSummary,
|
||||
EditReviewListResponse,
|
||||
EditReviewDetail,
|
||||
AdminEditLogEntry,
|
||||
} from "@/lib/api"
|
||||
import { CorrectionData } from "@/lib/lyrics-review/types"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Search,
|
||||
Loader2,
|
||||
Eye,
|
||||
FileText,
|
||||
Code,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
Check,
|
||||
MessageSquare,
|
||||
ArrowRight,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import dynamic from "next/dynamic"
|
||||
|
||||
const LyricsAnalyzer = dynamic(
|
||||
() => import("@/components/lyrics-review/LyricsAnalyzer"),
|
||||
{ ssr: false }
|
||||
)
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
// ─── Edit Log Replay Panel ───────────────────────────────────────────────────
|
||||
|
||||
function EditLogReplayPanel({
|
||||
entries,
|
||||
}: {
|
||||
entries: AdminEditLogEntry[]
|
||||
}) {
|
||||
const [currentIndex, setCurrentIndex] = useState(0)
|
||||
|
||||
if (entries.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-48 text-muted-foreground">
|
||||
No edit log entries found.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const operationCounts: Record<string, number> = {}
|
||||
let feedbackCount = 0
|
||||
for (const entry of entries) {
|
||||
operationCounts[entry.operation] = (operationCounts[entry.operation] || 0) + 1
|
||||
if (entry.feedback) feedbackCount++
|
||||
}
|
||||
|
||||
const current = entries[currentIndex]
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Summary Stats */}
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<Card>
|
||||
<CardHeader className="py-2 px-3">
|
||||
<CardTitle className="text-xs font-medium text-muted-foreground">Total Edits</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="py-1 px-3">
|
||||
<div className="text-2xl font-bold">{entries.length}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="py-2 px-3">
|
||||
<CardTitle className="text-xs font-medium text-muted-foreground">With Feedback</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="py-1 px-3">
|
||||
<div className="text-2xl font-bold">{feedbackCount}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="py-2 px-3">
|
||||
<CardTitle className="text-xs font-medium text-muted-foreground">Operation Types</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="py-1 px-3">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{Object.entries(operationCounts).map(([op, count]) => (
|
||||
<Badge key={op} variant="secondary" className="text-xs">
|
||||
{op}: {count}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<div className="flex items-center justify-between border rounded-md p-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={currentIndex === 0}
|
||||
onClick={() => setCurrentIndex((i) => i - 1)}
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4 mr-1" /> Previous
|
||||
</Button>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{currentIndex + 1} / {entries.length}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={currentIndex === entries.length - 1}
|
||||
onClick={() => setCurrentIndex((i) => i + 1)}
|
||||
>
|
||||
Next <ChevronRight className="w-4 h-4 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Entry List */}
|
||||
<ScrollArea className="h-[400px]">
|
||||
<div className="space-y-2">
|
||||
{entries.map((entry, idx) => {
|
||||
const isActive = idx === currentIndex
|
||||
return (
|
||||
<div
|
||||
key={entry.id}
|
||||
className={`border rounded-md p-3 cursor-pointer transition-colors ${
|
||||
isActive ? "border-primary bg-primary/5" : "hover:bg-muted/50"
|
||||
}`}
|
||||
onClick={() => setCurrentIndex(idx)}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Badge variant={isActive ? "default" : "outline"} className="text-xs">
|
||||
{entry.operation}
|
||||
</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(entry.timestamp).toLocaleString()}
|
||||
</span>
|
||||
{entry.segment_index !== undefined && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Segment {entry.segment_index}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{entry.text_before && (
|
||||
<span className="line-through text-red-500/80 bg-red-50 dark:bg-red-950/30 px-1 rounded text-xs">
|
||||
{entry.text_before}
|
||||
</span>
|
||||
)}
|
||||
{entry.text_before && entry.text_after && (
|
||||
<ArrowRight className="w-3 h-3 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
{entry.text_after && (
|
||||
<span className="text-green-600 bg-green-50 dark:bg-green-950/30 px-1 rounded text-xs">
|
||||
{entry.text_after}
|
||||
</span>
|
||||
)}
|
||||
{!entry.text_before && !entry.text_after && (
|
||||
<span className="text-xs text-muted-foreground italic">
|
||||
(no text change)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{entry.feedback && (
|
||||
<div className="mt-2 flex items-start gap-1.5 text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-950/30 rounded p-1.5">
|
||||
<MessageSquare className="w-3 h-3 mt-0.5 shrink-0" />
|
||||
<span>{entry.feedback.reason}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Raw Data Viewer ─────────────────────────────────────────────────────────
|
||||
|
||||
function RawDataViewer({
|
||||
editLog,
|
||||
annotations,
|
||||
originalCorrections,
|
||||
updatedCorrections,
|
||||
}: {
|
||||
editLog: unknown
|
||||
annotations: unknown
|
||||
originalCorrections: Record<string, unknown> | null
|
||||
updatedCorrections: Record<string, unknown> | null
|
||||
}) {
|
||||
const [copiedTab, setCopiedTab] = useState<string | null>(null)
|
||||
|
||||
const handleCopy = useCallback((data: unknown, tabName: string) => {
|
||||
navigator.clipboard.writeText(JSON.stringify(data, null, 2))
|
||||
setCopiedTab(tabName)
|
||||
toast.success("Copied to clipboard")
|
||||
setTimeout(() => setCopiedTab(null), 2000)
|
||||
}, [])
|
||||
|
||||
// Compute corrections diff
|
||||
const correctionsDiff = (() => {
|
||||
if (!originalCorrections || !updatedCorrections) return null
|
||||
const allKeys = new Set([
|
||||
...Object.keys(originalCorrections),
|
||||
...Object.keys(updatedCorrections),
|
||||
])
|
||||
const diff: Record<string, { original: unknown; updated: unknown }> = {}
|
||||
for (const key of allKeys) {
|
||||
const origVal = JSON.stringify(originalCorrections[key])
|
||||
const updVal = JSON.stringify(updatedCorrections[key])
|
||||
if (origVal !== updVal) {
|
||||
diff[key] = {
|
||||
original: originalCorrections[key],
|
||||
updated: updatedCorrections[key],
|
||||
}
|
||||
}
|
||||
}
|
||||
return diff
|
||||
})()
|
||||
|
||||
return (
|
||||
<Tabs defaultValue="edit-log" className="w-full">
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger value="edit-log" className="flex-1">Edit Log</TabsTrigger>
|
||||
<TabsTrigger value="annotations" className="flex-1">Annotations</TabsTrigger>
|
||||
<TabsTrigger value="corrections-diff" className="flex-1">Corrections Diff</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="edit-log">
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleCopy(editLog, "edit-log")}
|
||||
>
|
||||
{copiedTab === "edit-log" ? (
|
||||
<Check className="w-3 h-3 mr-1" />
|
||||
) : (
|
||||
<Copy className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-[500px]">
|
||||
<pre className="text-xs bg-muted/50 p-3 rounded-md overflow-x-auto">
|
||||
{JSON.stringify(editLog, null, 2) ?? "null"}
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="annotations">
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleCopy(annotations, "annotations")}
|
||||
>
|
||||
{copiedTab === "annotations" ? (
|
||||
<Check className="w-3 h-3 mr-1" />
|
||||
) : (
|
||||
<Copy className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-[500px]">
|
||||
<pre className="text-xs bg-muted/50 p-3 rounded-md overflow-x-auto">
|
||||
{JSON.stringify(annotations, null, 2) ?? "null"}
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="corrections-diff">
|
||||
<div className="flex justify-end mb-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleCopy(correctionsDiff, "corrections-diff")}
|
||||
>
|
||||
{copiedTab === "corrections-diff" ? (
|
||||
<Check className="w-3 h-3 mr-1" />
|
||||
) : (
|
||||
<Copy className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
Copy
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-[500px]">
|
||||
{correctionsDiff && Object.keys(correctionsDiff).length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{Object.entries(correctionsDiff).map(([key, { original, updated }]) => (
|
||||
<div key={key} className="border rounded-md p-3">
|
||||
<div className="font-mono text-sm font-semibold mb-2">{key}</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div>
|
||||
<div className="text-xs font-medium text-muted-foreground mb-1">Original</div>
|
||||
<pre className="text-xs bg-red-50 dark:bg-red-950/30 p-2 rounded overflow-x-auto">
|
||||
{JSON.stringify(original, null, 2) ?? "undefined"}
|
||||
</pre>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs font-medium text-muted-foreground mb-1">Updated</div>
|
||||
<pre className="text-xs bg-green-50 dark:bg-green-950/30 p-2 rounded overflow-x-auto">
|
||||
{JSON.stringify(updated, null, 2) ?? "undefined"}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-48 text-muted-foreground">
|
||||
{!originalCorrections || !updatedCorrections
|
||||
? "Original or updated corrections not available."
|
||||
: "No differences found between original and updated corrections."}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Main Page ───────────────────────────────────────────────────────────────
|
||||
|
||||
export default function EditReviewsPage() {
|
||||
const { showTestData } = useAdminSettings()
|
||||
|
||||
// List state
|
||||
const [reviews, setReviews] = useState<EditReviewSummary[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [hasMore, setHasMore] = useState(false)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
// Dialog state
|
||||
const [reviewDialogOpen, setReviewDialogOpen] = useState(false)
|
||||
const [editLogDialogOpen, setEditLogDialogOpen] = useState(false)
|
||||
const [rawDataDialogOpen, setRawDataDialogOpen] = useState(false)
|
||||
const [selectedReview, setSelectedReview] = useState<EditReviewDetail | null>(null)
|
||||
const [detailLoading, setDetailLoading] = useState(false)
|
||||
|
||||
const fetchReviews = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data: EditReviewListResponse = await adminApi.listEditReviews({
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
exclude_test: !showTestData,
|
||||
search: searchQuery || undefined,
|
||||
})
|
||||
setReviews(data.reviews)
|
||||
setTotal(data.total)
|
||||
setHasMore(data.has_more)
|
||||
} catch (err) {
|
||||
toast.error("Failed to load edit reviews: " + (err instanceof Error ? err.message : String(err)))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [offset, searchQuery, showTestData])
|
||||
|
||||
useEffect(() => {
|
||||
fetchReviews()
|
||||
}, [fetchReviews])
|
||||
|
||||
const loadDetail = useCallback(async (jobId: string) => {
|
||||
setDetailLoading(true)
|
||||
try {
|
||||
const detail = await adminApi.getEditReview(jobId)
|
||||
setSelectedReview(detail)
|
||||
return detail
|
||||
} catch (err) {
|
||||
toast.error("Failed to load review detail: " + (err instanceof Error ? err.message : String(err)))
|
||||
return null
|
||||
} finally {
|
||||
setDetailLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleViewReview = useCallback(async (jobId: string) => {
|
||||
const detail = await loadDetail(jobId)
|
||||
if (detail) {
|
||||
setReviewDialogOpen(true)
|
||||
}
|
||||
}, [loadDetail])
|
||||
|
||||
const handleViewEditLog = useCallback(async (jobId: string) => {
|
||||
const detail = await loadDetail(jobId)
|
||||
if (detail) {
|
||||
setEditLogDialogOpen(true)
|
||||
}
|
||||
}, [loadDetail])
|
||||
|
||||
const handleViewRawData = useCallback(async (jobId: string) => {
|
||||
const detail = await loadDetail(jobId)
|
||||
if (detail) {
|
||||
setRawDataDialogOpen(true)
|
||||
}
|
||||
}, [loadDetail])
|
||||
|
||||
const handleSearch = useCallback(() => {
|
||||
setOffset(0)
|
||||
setSearchQuery(searchInput)
|
||||
}, [searchInput])
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter") handleSearch()
|
||||
},
|
||||
[handleSearch]
|
||||
)
|
||||
|
||||
const correctionData: CorrectionData | null =
|
||||
selectedReview?.updated_corrections
|
||||
? (selectedReview.updated_corrections as unknown as CorrectionData)
|
||||
: selectedReview?.original_corrections
|
||||
? (selectedReview.original_corrections as unknown as CorrectionData)
|
||||
: null
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Edit Reviews</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Review user lyrics edits and corrections
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search by artist, title, or email..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={handleSearch} variant="secondary">
|
||||
Search
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
<Card>
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-base">
|
||||
{loading ? "Loading..." : `${total} review${total !== 1 ? "s" : ""} found`}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
{loading ? (
|
||||
<div className="p-4 space-y-3">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-12 w-full" />
|
||||
))}
|
||||
</div>
|
||||
) : reviews.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-48 text-muted-foreground">
|
||||
No edit reviews found.
|
||||
</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Artist / Title</TableHead>
|
||||
<TableHead>User Email</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Updated</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{reviews.map((review) => (
|
||||
<TableRow key={review.job_id}>
|
||||
<TableCell>
|
||||
<div className="font-medium">{review.artist}</div>
|
||||
<div className="text-sm text-muted-foreground">{review.title}</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">{review.user_email}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={review.status === "completed" ? "default" : "secondary"}>
|
||||
{review.status}
|
||||
</Badge>
|
||||
{review.has_corrections_updated && (
|
||||
<Badge variant="outline" className="ml-1 text-xs">
|
||||
edited
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">
|
||||
{review.updated_at
|
||||
? new Date(review.updated_at).toLocaleDateString()
|
||||
: "-"}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleViewReview(review.job_id)}
|
||||
disabled={detailLoading}
|
||||
title="View Review"
|
||||
>
|
||||
<Eye className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleViewEditLog(review.job_id)}
|
||||
disabled={detailLoading}
|
||||
title="View Edit Log"
|
||||
>
|
||||
<FileText className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleViewRawData(review.job_id)}
|
||||
disabled={detailLoading}
|
||||
title="View Raw Data"
|
||||
>
|
||||
<Code className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{!loading && total > PAGE_SIZE && (
|
||||
<div className="flex items-center justify-between p-4 border-t">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={offset === 0}
|
||||
onClick={() => setOffset((o) => Math.max(0, o - PAGE_SIZE))}
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4 mr-1" /> Previous
|
||||
</Button>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Showing {offset + 1}-{Math.min(offset + PAGE_SIZE, total)} of {total}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!hasMore}
|
||||
onClick={() => setOffset((o) => o + PAGE_SIZE)}
|
||||
>
|
||||
Next <ChevronRight className="w-4 h-4 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Review Viewer Dialog */}
|
||||
<Dialog open={reviewDialogOpen} onOpenChange={setReviewDialogOpen}>
|
||||
<DialogContent className="max-w-[95vw] w-[95vw] h-[90vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{selectedReview
|
||||
? `${selectedReview.job.artist} - ${selectedReview.job.title}`
|
||||
: "Loading..."}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex-1 overflow-auto">
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : correctionData ? (
|
||||
<LyricsAnalyzer
|
||||
data={correctionData}
|
||||
isReadOnly={true}
|
||||
apiClient={null}
|
||||
audioHash={selectedReview?.edit_log?.audio_hash ?? ""}
|
||||
onFileLoad={() => {}}
|
||||
onShowMetadata={() => {}}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||
No correction data available for this review.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Edit Log Dialog */}
|
||||
<Dialog open={editLogDialogOpen} onOpenChange={setEditLogDialogOpen}>
|
||||
<DialogContent className="max-w-2xl w-full max-h-[85vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Edit Log
|
||||
{selectedReview && (
|
||||
<span className="text-sm font-normal text-muted-foreground ml-2">
|
||||
{selectedReview.job.artist} - {selectedReview.job.title}
|
||||
</span>
|
||||
)}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex-1 overflow-auto">
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center justify-center h-48">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : selectedReview?.edit_log?.entries ? (
|
||||
<EditLogReplayPanel entries={selectedReview.edit_log.entries} />
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-48 text-muted-foreground">
|
||||
No edit log available for this review.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Raw Data Dialog */}
|
||||
<Dialog open={rawDataDialogOpen} onOpenChange={setRawDataDialogOpen}>
|
||||
<DialogContent className="max-w-4xl w-full max-h-[85vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Raw Data
|
||||
{selectedReview && (
|
||||
<span className="text-sm font-normal text-muted-foreground ml-2">
|
||||
{selectedReview.job.artist} - {selectedReview.job.title}
|
||||
</span>
|
||||
)}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex-1 overflow-auto">
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center justify-center h-48">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : selectedReview ? (
|
||||
<RawDataViewer
|
||||
editLog={selectedReview.edit_log}
|
||||
annotations={selectedReview.annotations}
|
||||
originalCorrections={selectedReview.original_corrections}
|
||||
updatedCorrections={selectedReview.updated_corrections}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-48 text-muted-foreground">
|
||||
No data available.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -46,14 +46,18 @@ import {
|
||||
Clock,
|
||||
Trash2,
|
||||
DollarSign,
|
||||
LogIn,
|
||||
} from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
|
||||
export default function AdminUserDetailPage() {
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { user: currentUser, startImpersonation } = useAuth()
|
||||
const email = searchParams.get("email") || ""
|
||||
const [impersonating, setImpersonating] = useState(false)
|
||||
|
||||
const [user, setUser] = useState<AdminUserDetail | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
@@ -173,6 +177,32 @@ export default function AdminUserDetailPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleImpersonate = async () => {
|
||||
if (!email || email === currentUser?.email) return
|
||||
try {
|
||||
setImpersonating(true)
|
||||
const success = await startImpersonation(email)
|
||||
if (success) {
|
||||
router.push("/dashboard")
|
||||
} else {
|
||||
const authError = useAuth.getState().error
|
||||
toast({
|
||||
title: "Impersonation Failed",
|
||||
description: authError || "Unable to impersonate user",
|
||||
variant: "destructive",
|
||||
})
|
||||
}
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: err.message || "Failed to impersonate user",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setImpersonating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteUser = async () => {
|
||||
if (!user) return
|
||||
|
||||
@@ -261,6 +291,21 @@ export default function AdminUserDetailPage() {
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{email !== currentUser?.email && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleImpersonate}
|
||||
disabled={impersonating || actionLoading}
|
||||
title="View the app as this user"
|
||||
>
|
||||
{impersonating ? (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<LogIn className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
Impersonate User
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => setCreditDialogOpen(true)} disabled={actionLoading} title="Grant credits to this user">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Add Credits
|
||||
|
||||
@@ -421,6 +421,7 @@ function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMo
|
||||
audioHash={correctionData.metadata?.audio_hash || job.audio_hash || job.job_id}
|
||||
isLocalMode={isLocalMode}
|
||||
jobId={job.job_id}
|
||||
hasExistingInstrumental={!!job.existing_instrumental_gcs_path}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -20,12 +20,15 @@ import { sortJobsByDate, getDisplayJobs } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
import { TenantJobFlow } from "@/components/job/TenantJobFlow"
|
||||
import { TenantLogo } from "@/components/tenant-logo"
|
||||
import { AuthStatus } from "@/components/auth"
|
||||
import { AutoProcessor } from "@/components/AutoProcessor"
|
||||
import { VersionFooter } from "@/components/version-footer"
|
||||
import { PushNotificationPrompt } from "@/components/push-notification-prompt"
|
||||
import { FeedbackDialog } from "@/components/feedback/FeedbackDialog"
|
||||
import { useTheme } from "@/lib/theme"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
@@ -52,6 +55,7 @@ function AppPageContent() {
|
||||
const adminTokenHandled = useRef(false) // Track if admin_token was already processed
|
||||
const { isDarkMode, toggleTheme, mounted } = useTheme()
|
||||
const { user, fetchUser, verifyMagicLink } = useAuth()
|
||||
const { isDefault: isDefaultTenant, branding } = useTenant()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [jobLimit, setJobLimit] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 10
|
||||
@@ -66,7 +70,10 @@ function AppPageContent() {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-karaoke-admin-controls") === "true"
|
||||
})
|
||||
const [feedbackBannerDismissed, setFeedbackBannerDismissed] = useState(false)
|
||||
const [feedbackBannerDismissed, setFeedbackBannerDismissed] = useState(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-feedback-banner-dismissed") === "true"
|
||||
})
|
||||
const [showFeedbackDialog, setShowFeedbackDialog] = useState(false)
|
||||
|
||||
// Check if user is admin (for exclude_test parameter)
|
||||
@@ -201,9 +208,15 @@ function AppPageContent() {
|
||||
<header className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
|
||||
<div className="px-3 sm:px-4 py-2 sm:py-3 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 sm:gap-3 min-w-0">
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 sm:h-10 shrink-0" />
|
||||
{isDefaultTenant ? (
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 sm:h-10 shrink-0" />
|
||||
) : (
|
||||
<TenantLogo size="sm" />
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-base sm:text-xl font-bold truncate" style={{ color: 'var(--text)' }}>Karaoke Generator</h1>
|
||||
<h1 className="text-base sm:text-xl font-bold truncate" style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? "Karaoke Generator" : branding.site_title}
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
|
||||
@@ -311,8 +324,8 @@ function AppPageContent() {
|
||||
{/* Push notification prompt - shows once when appropriate */}
|
||||
<PushNotificationPrompt />
|
||||
|
||||
{/* Feedback-for-credits banner */}
|
||||
{user?.feedback_eligible && !feedbackBannerDismissed && (
|
||||
{/* Feedback-for-credits banner (consumer portal only) */}
|
||||
{isDefaultTenant && user?.feedback_eligible && !feedbackBannerDismissed && (
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border px-4 py-3"
|
||||
style={{
|
||||
borderColor: 'var(--accent)',
|
||||
@@ -338,7 +351,10 @@ function AppPageContent() {
|
||||
Give Feedback
|
||||
</Button>
|
||||
<button
|
||||
onClick={() => setFeedbackBannerDismissed(true)}
|
||||
onClick={() => {
|
||||
localStorage.setItem("nomad-feedback-banner-dismissed", "true")
|
||||
setFeedbackBannerDismissed(true)
|
||||
}}
|
||||
className="p-1 rounded hover:bg-secondary transition-colors"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
@@ -352,13 +368,21 @@ function AppPageContent() {
|
||||
{/* Submit Job Card */}
|
||||
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
|
||||
<CardHeader>
|
||||
<CardTitle style={{ color: 'var(--text)' }}>Create Karaoke Video</CardTitle>
|
||||
<CardTitle style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? "Create Karaoke Video" : "Submit Track"}
|
||||
</CardTitle>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
Turn any song into a karaoke video with synced lyrics
|
||||
{isDefaultTenant
|
||||
? "Turn any song into a karaoke video with synced lyrics"
|
||||
: "Upload your mixed audio and instrumental"}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
{isDefaultTenant ? (
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
) : (
|
||||
<TenantJobFlow onJobCreated={loadJobs} />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -78,8 +78,8 @@
|
||||
--text: #1e293b;
|
||||
--text-muted: #64748b;
|
||||
--text-subtle: #94a3b8;
|
||||
--primary: var(--brand-pink);
|
||||
--primary-hover: var(--brand-pink-hover);
|
||||
--primary: var(--tenant-primary);
|
||||
--primary-hover: color-mix(in srgb, var(--tenant-primary) 80%, black 20%);
|
||||
--secondary: #f1f5f9;
|
||||
--secondary-hover: #e2e8f0;
|
||||
--success: #22c55e;
|
||||
|
||||
@@ -71,7 +71,7 @@ export function TenantLandingPage() {
|
||||
className="px-8 py-3 rounded-lg text-lg font-semibold transition-all hover:opacity-90 cursor-pointer"
|
||||
style={{
|
||||
backgroundColor: primaryColor,
|
||||
color: branding.background_color || '#000000',
|
||||
color: 'var(--primary-foreground)',
|
||||
}}
|
||||
>
|
||||
Sign In
|
||||
|
||||
@@ -134,6 +134,72 @@ describe('OutputLinks', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('visibility change button', () => {
|
||||
it('shows "Make Public" for private complete jobs', () => {
|
||||
const privateJob: Job = {
|
||||
...baseJob,
|
||||
is_private: true,
|
||||
}
|
||||
|
||||
render(<OutputLinks job={privateJob} />)
|
||||
|
||||
expect(screen.getByText('Make Public')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Private')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows "Make Private" for public complete jobs', () => {
|
||||
const publicJob: Job = {
|
||||
...baseJob,
|
||||
is_private: false,
|
||||
}
|
||||
|
||||
render(<OutputLinks job={publicJob} />)
|
||||
|
||||
expect(screen.getByText('Make Private')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Public')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides button when visibility change is in progress', () => {
|
||||
const inProgressJob: Job = {
|
||||
...baseJob,
|
||||
state_data: {
|
||||
...baseJob.state_data,
|
||||
visibility_change_in_progress: true,
|
||||
},
|
||||
}
|
||||
|
||||
render(<OutputLinks job={inProgressJob} />)
|
||||
|
||||
expect(screen.queryByText('Make Public')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Private')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides button for non-complete jobs', () => {
|
||||
const pendingJob: Job = {
|
||||
...baseJob,
|
||||
status: 'generating_video',
|
||||
}
|
||||
|
||||
render(<OutputLinks job={pendingJob} />)
|
||||
|
||||
expect(screen.queryByText('Make Public')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Private')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides button for tenant jobs', () => {
|
||||
const { useTenant } = require('@/lib/tenant')
|
||||
useTenant.mockReturnValue({
|
||||
tenantId: 'vocalstar',
|
||||
features: { youtube_upload: true, dropbox_upload: true },
|
||||
})
|
||||
|
||||
render(<OutputLinks job={baseJob} />)
|
||||
|
||||
expect(screen.queryByText('Make Public')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Make Private')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('shows nothing when job has no file_urls and no state_data (non-admin)', () => {
|
||||
// Reset to non-admin user
|
||||
@@ -142,16 +208,47 @@ describe('OutputLinks', () => {
|
||||
|
||||
const emptyJob: Job = {
|
||||
...baseJob,
|
||||
status: 'generating_video',
|
||||
file_urls: undefined,
|
||||
state_data: undefined,
|
||||
}
|
||||
|
||||
render(<OutputLinks job={emptyJob} />)
|
||||
|
||||
// Should show "No outputs available yet" for non-admin
|
||||
// Should show "No outputs available yet" for non-admin, non-complete job
|
||||
expect(screen.getByText('No outputs available yet')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Edit button for completed jobs with outputs', () => {
|
||||
render(<OutputLinks job={baseJob} />)
|
||||
|
||||
expect(screen.getByText('Edit')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides Edit button when outputs are deleted', () => {
|
||||
const deletedJob: Job = {
|
||||
...baseJob,
|
||||
outputs_deleted_at: '2026-01-15T10:00:00Z',
|
||||
}
|
||||
|
||||
render(<OutputLinks job={deletedJob} />)
|
||||
|
||||
expect(screen.queryByText('Edit')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides Edit button for non-complete jobs', () => {
|
||||
const pendingJob: Job = {
|
||||
...baseJob,
|
||||
status: 'pending',
|
||||
}
|
||||
|
||||
render(<OutputLinks job={pendingJob} />)
|
||||
|
||||
expect(screen.queryByText('Edit')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('handles partial file_urls gracefully', () => {
|
||||
// Reset to non-admin user
|
||||
const { useAuth } = require('@/lib/auth')
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
Settings,
|
||||
Search,
|
||||
ShieldAlert,
|
||||
BookOpenCheck,
|
||||
} from "lucide-react"
|
||||
|
||||
import {
|
||||
@@ -58,6 +59,11 @@ const navItems = [
|
||||
href: "/admin/rate-limits",
|
||||
icon: ShieldAlert,
|
||||
},
|
||||
{
|
||||
title: "Edit Reviews",
|
||||
href: "/admin/edit-reviews",
|
||||
icon: BookOpenCheck,
|
||||
},
|
||||
]
|
||||
|
||||
export function AdminSidebar() {
|
||||
|
||||
@@ -12,11 +12,11 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "./ui/dropdown-menu"
|
||||
import { User, LogOut, Settings, Shield, Mail, Phone, HelpCircle } from "lucide-react"
|
||||
import { User, LogOut, Settings, Shield, Mail, Phone, HelpCircle, Eye } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
|
||||
export function AppHeader() {
|
||||
const { user, logout } = useAuth()
|
||||
const { user, logout, isImpersonating, impersonatedUserEmail, endImpersonation } = useAuth()
|
||||
const router = useRouter()
|
||||
|
||||
const handleLogout = () => {
|
||||
@@ -24,6 +24,11 @@ export function AppHeader() {
|
||||
router.push("/")
|
||||
}
|
||||
|
||||
const handleBackToAdmin = () => {
|
||||
endImpersonation()
|
||||
router.push("/admin")
|
||||
}
|
||||
|
||||
if (!user) return null
|
||||
|
||||
return (
|
||||
@@ -48,6 +53,18 @@ export function AppHeader() {
|
||||
</nav>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
{isImpersonating && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleBackToAdmin}
|
||||
className="h-8 gap-1.5 border-purple-500/40 text-purple-300 hover:text-white hover:bg-purple-800/40"
|
||||
>
|
||||
<Shield className="w-3.5 h-3.5" />
|
||||
Back to Admin
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="hidden lg:flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors">
|
||||
|
||||
@@ -1,36 +1,43 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { X, Eye } from "lucide-react"
|
||||
import { Eye, Shield } from "lucide-react"
|
||||
|
||||
/**
|
||||
* Banner shown when admin is impersonating another user.
|
||||
* Displays prominently at the top of the page with option to stop impersonating.
|
||||
* Compact strip at the top of the page with clear identity and quick exit.
|
||||
*/
|
||||
export function ImpersonationBanner() {
|
||||
const { isImpersonating, impersonatedUserEmail, endImpersonation } = useAuth()
|
||||
const router = useRouter()
|
||||
|
||||
if (!isImpersonating) {
|
||||
return null
|
||||
}
|
||||
|
||||
const handleBackToAdmin = () => {
|
||||
endImpersonation()
|
||||
router.push("/admin")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-amber-500 text-amber-950 px-4 py-2 flex items-center justify-between gap-4 text-sm font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
<Eye className="w-4 h-4" />
|
||||
<div className="border-b border-purple-500/30 bg-purple-950/60 px-4 py-1.5 flex items-center justify-between gap-4 text-xs">
|
||||
<div className="flex items-center gap-2 text-purple-300">
|
||||
<Eye className="w-3.5 h-3.5 shrink-0" />
|
||||
<span>
|
||||
Viewing as <strong>{impersonatedUserEmail}</strong>
|
||||
Viewing as <strong className="text-purple-100">{impersonatedUserEmail}</strong>
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={endImpersonation}
|
||||
className="bg-amber-100 hover:bg-amber-200 text-amber-950 border-amber-600 h-7 px-3"
|
||||
onClick={handleBackToAdmin}
|
||||
className="h-6 px-2.5 text-xs gap-1.5 text-purple-200 hover:text-white hover:bg-purple-800/50"
|
||||
>
|
||||
<X className="w-3 h-3 mr-1" />
|
||||
Stop Impersonating
|
||||
<Shield className="w-3 h-3" />
|
||||
Back to Admin
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { api, Job } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Loader2 } from "lucide-react"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
interface EditTrackModalProps {
|
||||
job: Job
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onEditStarted?: () => void
|
||||
}
|
||||
|
||||
export function EditTrackModal({ job, open, onOpenChange, onEditStarted }: EditTrackModalProps) {
|
||||
const [updateMetadata, setUpdateMetadata] = useState(false)
|
||||
const [artist, setArtist] = useState(job.artist || "")
|
||||
const [title, setTitle] = useState(job.title || "")
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleConfirm = async () => {
|
||||
setIsSubmitting(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const updates: { artist?: string; title?: string } = {}
|
||||
if (updateMetadata) {
|
||||
const trimmedArtist = artist?.trim()
|
||||
const trimmedTitle = title?.trim()
|
||||
if (trimmedArtist && trimmedArtist !== job.artist) updates.artist = trimmedArtist
|
||||
if (trimmedTitle && trimmedTitle !== job.title) updates.title = trimmedTitle
|
||||
}
|
||||
|
||||
const result = await api.editCompletedTrack(job.job_id, updates)
|
||||
|
||||
onOpenChange(false)
|
||||
|
||||
// Navigate to review screen using server-provided URL
|
||||
if (result.review_url) {
|
||||
window.location.hash = result.review_url.replace(/^\/app\/jobs#/, '')
|
||||
} else {
|
||||
window.location.hash = `/${job.job_id}/review`
|
||||
}
|
||||
|
||||
onEditStarted?.()
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Failed to start edit. Please try again.")
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (!isSubmitting) {
|
||||
onOpenChange(newOpen)
|
||||
if (!newOpen) {
|
||||
setError(null)
|
||||
setUpdateMetadata(false)
|
||||
setArtist(job.artist || "")
|
||||
setTitle(job.title || "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[480px]" onClick={(e) => e.stopPropagation()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Completed Track</DialogTitle>
|
||||
<DialogDescription>
|
||||
This will remove the current video from YouTube, Dropbox, and Google Drive.
|
||||
After you complete the review again, a new version will be rendered and re-distributed.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="update-metadata"
|
||||
checked={updateMetadata}
|
||||
onChange={(e) => setUpdateMetadata(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
<Label htmlFor="update-metadata" className="cursor-pointer">
|
||||
I need to update the artist or title
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{updateMetadata && (
|
||||
<div className="grid gap-3 pl-6">
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="edit-artist" className="text-right">
|
||||
Artist
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-artist"
|
||||
value={artist}
|
||||
onChange={(e) => setArtist(e.target.value)}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="edit-title" className="text-right">
|
||||
Title
|
||||
</Label>
|
||||
<Input
|
||||
id="edit-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleConfirm}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Cleaning up...
|
||||
</>
|
||||
) : (
|
||||
"Confirm & Edit"
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button"
|
||||
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
|
||||
import { SongInfoStep } from "./steps/SongInfoStep"
|
||||
import { AudioSourceStep } from "./steps/AudioSourceStep"
|
||||
import { VisibilityStep } from "./steps/VisibilityStep"
|
||||
import { CustomizeStep } from "./steps/CustomizeStep"
|
||||
import type { ColorOverrides } from "./steps/CustomizeStep"
|
||||
|
||||
@@ -16,9 +17,9 @@ interface GuidedJobFlowProps {
|
||||
onJobCreated: () => void
|
||||
}
|
||||
|
||||
type Step = 1 | 2 | 3
|
||||
type Step = 1 | 2 | 3 | 4
|
||||
|
||||
const STEP_LABELS = ["Song Info", "Choose Audio", "Customize & Create"]
|
||||
const STEP_LABELS = ["Song Info", "Choose Audio", "Visibility", "Customize & Create"]
|
||||
|
||||
/**
|
||||
* Upload custom style assets to an already-created job.
|
||||
@@ -75,7 +76,8 @@ async function uploadStyleAssets(
|
||||
|
||||
// Step 3: Finalize with uploaded file types + color overrides
|
||||
const uploadedFileTypes = filesToUpload.map((f) => f.file_type)
|
||||
const hasColorOverrides = colorOverrides.artist_color || colorOverrides.title_color
|
||||
const hasColorOverrides = colorOverrides.artist_color || colorOverrides.title_color ||
|
||||
colorOverrides.sung_lyrics_color || colorOverrides.unsung_lyrics_color
|
||||
await api.completeStyleUploads(
|
||||
jobId,
|
||||
uploadedFileTypes,
|
||||
@@ -115,6 +117,10 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
const [selectedResultIndex, setSelectedResultIndex] = useState<number | null>(null)
|
||||
const [searchSessionId, setSearchSessionId] = useState<string | null>(null)
|
||||
|
||||
// Pending fallback data (URL/upload stored until after Steps 3-4)
|
||||
const [pendingUrl, setPendingUrl] = useState<string | null>(null)
|
||||
const [pendingFile, setPendingFile] = useState<File | null>(null)
|
||||
|
||||
// Submission state
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [submitError, setSubmitError] = useState("")
|
||||
@@ -124,9 +130,16 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
setAudioSource("search")
|
||||
}
|
||||
|
||||
function handleJobCreated(id: string, source: "upload" | "url") {
|
||||
setJobId(id)
|
||||
setAudioSource(source)
|
||||
function handleUrlReady(url: string) {
|
||||
setPendingUrl(url)
|
||||
setAudioSource("url")
|
||||
setStep(3)
|
||||
}
|
||||
|
||||
function handleFileReady(file: File) {
|
||||
setPendingFile(file)
|
||||
setAudioSource("upload")
|
||||
setStep(3)
|
||||
}
|
||||
|
||||
function handleSearchResultChosen(resultIndex: number) {
|
||||
@@ -135,37 +148,55 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
setStep(3)
|
||||
}
|
||||
|
||||
function handleFallbackComplete() {
|
||||
// Upload/URL jobs are already processing — show success directly
|
||||
onJobCreated()
|
||||
setShowSuccess(true)
|
||||
}
|
||||
|
||||
async function handleConfirm() {
|
||||
if (!searchSessionId || selectedResultIndex === null) return
|
||||
|
||||
setIsSubmitting(true)
|
||||
setSubmitError("")
|
||||
try {
|
||||
// Create the job now with all final values from Steps 1+3
|
||||
const response = await api.createJobFromSearch({
|
||||
search_session_id: searchSessionId,
|
||||
selection_index: selectedResultIndex,
|
||||
artist: artist,
|
||||
title: title,
|
||||
display_artist: displayArtist.trim() || undefined,
|
||||
display_title: displayTitle.trim() || undefined,
|
||||
is_private: isPrivate,
|
||||
})
|
||||
setJobId(response.job_id)
|
||||
let createdJobId: string
|
||||
// For URL/upload, the artist/title params ARE the display values
|
||||
const effectiveArtist = displayArtist.trim() || artist.trim()
|
||||
const effectiveTitle = displayTitle.trim() || title.trim()
|
||||
|
||||
if (audioSource === "url" && pendingUrl) {
|
||||
// URL fallback path — create job now with visibility from Step 3
|
||||
const response = await api.createJobFromUrl(pendingUrl, effectiveArtist, effectiveTitle, {
|
||||
is_private: isPrivate,
|
||||
})
|
||||
createdJobId = response.job_id
|
||||
} else if (audioSource === "upload" && pendingFile) {
|
||||
// Upload fallback path — upload and create job now with visibility from Step 3
|
||||
const response = await api.uploadJobSmart(
|
||||
pendingFile, effectiveArtist, effectiveTitle,
|
||||
{ is_private: isPrivate },
|
||||
)
|
||||
createdJobId = response.job_id
|
||||
} else if (searchSessionId && selectedResultIndex !== null) {
|
||||
// Search path — create job from search session
|
||||
const response = await api.createJobFromSearch({
|
||||
search_session_id: searchSessionId,
|
||||
selection_index: selectedResultIndex,
|
||||
artist: artist,
|
||||
title: title,
|
||||
display_artist: displayArtist.trim() || undefined,
|
||||
display_title: displayTitle.trim() || undefined,
|
||||
is_private: isPrivate,
|
||||
})
|
||||
createdJobId = response.job_id
|
||||
} else {
|
||||
setSubmitError("Missing audio source. Please go back and try again.")
|
||||
return
|
||||
}
|
||||
|
||||
setJobId(createdJobId)
|
||||
onJobCreated()
|
||||
setShowSuccess(true)
|
||||
|
||||
// Upload style assets in the background (non-blocking)
|
||||
const hasStyleCustomizations = karaokeBackground || introBackground ||
|
||||
colorOverrides.artist_color || colorOverrides.title_color
|
||||
colorOverrides.artist_color || colorOverrides.title_color ||
|
||||
colorOverrides.sung_lyrics_color || colorOverrides.unsung_lyrics_color
|
||||
if (isPrivate && hasStyleCustomizations) {
|
||||
uploadStyleAssets(response.job_id, karaokeBackground, introBackground, colorOverrides)
|
||||
uploadStyleAssets(createdJobId, karaokeBackground, introBackground, colorOverrides)
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
@@ -183,6 +214,8 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
setSearchSessionId(null)
|
||||
setAudioSource("search")
|
||||
setSelectedResultIndex(null)
|
||||
setPendingUrl(null)
|
||||
setPendingFile(null)
|
||||
setStep(1)
|
||||
}
|
||||
|
||||
@@ -201,6 +234,8 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
setAudioSource("search")
|
||||
setSelectedResultIndex(null)
|
||||
setSearchSessionId(null)
|
||||
setPendingUrl(null)
|
||||
setPendingFile(null)
|
||||
setSubmitError("")
|
||||
}
|
||||
|
||||
@@ -422,19 +457,25 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
<AudioSourceStep
|
||||
artist={artist}
|
||||
title={title}
|
||||
displayArtist={displayArtist}
|
||||
displayTitle={displayTitle}
|
||||
isPrivate={isPrivate}
|
||||
onSearchCompleted={handleSearchCompleted}
|
||||
onJobCreated={handleJobCreated}
|
||||
onSearchResultChosen={handleSearchResultChosen}
|
||||
onFallbackComplete={handleFallbackComplete}
|
||||
onUrlReady={handleUrlReady}
|
||||
onFileReady={handleFileReady}
|
||||
onBack={handleBackFromAudio}
|
||||
noCredits={noCredits}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<VisibilityStep
|
||||
isPrivate={isPrivate}
|
||||
onPrivateChange={setIsPrivate}
|
||||
onNext={() => setStep(4)}
|
||||
onBack={() => setStep(2)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 4 && (
|
||||
<CustomizeStep
|
||||
artist={artist}
|
||||
title={title}
|
||||
@@ -443,7 +484,6 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
onDisplayArtistChange={setDisplayArtist}
|
||||
onDisplayTitleChange={setDisplayTitle}
|
||||
isPrivate={isPrivate}
|
||||
onPrivateChange={setIsPrivate}
|
||||
karaokeBackground={karaokeBackground}
|
||||
onKaraokeBackgroundChange={setKaraokeBackground}
|
||||
introBackground={introBackground}
|
||||
@@ -451,7 +491,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
colorOverrides={colorOverrides}
|
||||
onColorOverridesChange={setColorOverrides}
|
||||
onConfirm={handleConfirm}
|
||||
onBack={() => setStep(2)}
|
||||
onBack={() => setStep(3)}
|
||||
isSubmitting={isSubmitting}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -10,6 +10,7 @@ interface ImageUploadFieldProps {
|
||||
file: File | null
|
||||
onChange: (file: File | null) => void
|
||||
disabled?: boolean
|
||||
hidePreview?: boolean // Hide the image thumbnail (when a canvas preview is shown instead)
|
||||
}
|
||||
|
||||
const MAX_SIZE_BYTES = 10 * 1024 * 1024 // 10MB
|
||||
@@ -21,7 +22,7 @@ function formatFileSize(bytes: number): string {
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
export function ImageUploadField({ label, description, file, onChange, disabled }: ImageUploadFieldProps) {
|
||||
export function ImageUploadField({ label, description, file, onChange, disabled, hidePreview }: ImageUploadFieldProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const [dragOver, setDragOver] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -74,8 +75,8 @@ export function ImageUploadField({ label, description, file, onChange, disabled
|
||||
|
||||
{file ? (
|
||||
<div className="relative rounded-lg overflow-hidden border" style={{ borderColor: 'var(--card-border)' }}>
|
||||
{/* 16:9 preview thumbnail */}
|
||||
{previewUrl && (
|
||||
{/* 16:9 preview thumbnail (hidden when canvas preview is used instead) */}
|
||||
{!hidePreview && previewUrl && (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={previewUrl}
|
||||
|
||||
@@ -187,7 +187,7 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
{/* Output links for completed jobs, or admin link for admins on any job */}
|
||||
{(isComplete || isAdmin) && (
|
||||
<div className="mt-2">
|
||||
<OutputLinks job={job} />
|
||||
<OutputLinks job={job} onJobUpdated={onRefresh} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -3,44 +3,65 @@
|
||||
import { useRef, useEffect, useCallback } from "react"
|
||||
|
||||
interface KaraokeBackgroundPreviewProps {
|
||||
backgroundUrl: string // Object URL from File
|
||||
backgroundUrl?: string // Object URL from File, or undefined for solid color
|
||||
backgroundColor?: string // Solid color hex (used when no backgroundUrl)
|
||||
sungColor?: string // Highlight color for sung lyrics
|
||||
unsungColor?: string // Color for unsung lyrics
|
||||
}
|
||||
|
||||
const CANVAS_W = 3840
|
||||
const CANVAS_H = 2160
|
||||
|
||||
// Sample lyrics to show how text looks over the background
|
||||
const SAMPLE_LINE_1 = "This is how your lyrics will look"
|
||||
const SAMPLE_LINE_2 = "over the background image"
|
||||
// 4 sample lines to match real karaoke video rendering
|
||||
const SAMPLE_LINES = [
|
||||
"Don't say that you don't understand",
|
||||
"This is California Babylon my man",
|
||||
"Don't say that you don't understand",
|
||||
"Don't say that you can't comprehend",
|
||||
]
|
||||
|
||||
// Default karaoke colors (matching Nomad theme)
|
||||
const SUNG_COLOR = "#7070F7"
|
||||
const UNSUNG_COLOR = "#ffffff"
|
||||
const DEFAULT_SUNG_COLOR = "#7070F7"
|
||||
const DEFAULT_UNSUNG_COLOR = "#ffffff"
|
||||
|
||||
export function KaraokeBackgroundPreview({ backgroundUrl }: KaraokeBackgroundPreviewProps) {
|
||||
export function KaraokeBackgroundPreview({
|
||||
backgroundUrl,
|
||||
backgroundColor,
|
||||
sungColor,
|
||||
unsungColor,
|
||||
}: KaraokeBackgroundPreviewProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
|
||||
const effectiveSungColor = sungColor || DEFAULT_SUNG_COLOR
|
||||
const effectiveUnsungColor = unsungColor || DEFAULT_UNSUNG_COLOR
|
||||
|
||||
const draw = useCallback(async () => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
|
||||
// Draw background
|
||||
try {
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const el = new Image()
|
||||
el.onload = () => resolve(el)
|
||||
el.onerror = reject
|
||||
el.src = backgroundUrl
|
||||
})
|
||||
ctx.drawImage(img, 0, 0, CANVAS_W, CANVAS_H)
|
||||
} catch {
|
||||
ctx.fillStyle = "#000000"
|
||||
// Draw background: custom image > solid color > default Nomad theme image
|
||||
const bgSrc = backgroundUrl || (backgroundColor ? null : "/karaoke-bg.png")
|
||||
if (bgSrc) {
|
||||
try {
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const el = new Image()
|
||||
el.onload = () => resolve(el)
|
||||
el.onerror = reject
|
||||
el.src = bgSrc
|
||||
})
|
||||
ctx.drawImage(img, 0, 0, CANVAS_W, CANVAS_H)
|
||||
} catch {
|
||||
ctx.fillStyle = backgroundColor || "#000000"
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
} else {
|
||||
ctx.fillStyle = backgroundColor || "#000000"
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
|
||||
// Draw sample lyrics in the lower third (where they typically appear)
|
||||
// Draw 4 lines of sample lyrics, vertically centered
|
||||
const fontSize = 120
|
||||
const fontFamily = "'Arial', 'Helvetica', sans-serif"
|
||||
ctx.font = `700 ${fontSize}px ${fontFamily}`
|
||||
@@ -48,34 +69,54 @@ export function KaraokeBackgroundPreview({ backgroundUrl }: KaraokeBackgroundPre
|
||||
ctx.textBaseline = "middle"
|
||||
|
||||
const centerX = CANVAS_W / 2
|
||||
const lineHeight = fontSize * 1.4
|
||||
const baseY = CANVAS_H * 0.75
|
||||
const lineHeight = fontSize * 1.5
|
||||
const totalHeight = lineHeight * SAMPLE_LINES.length
|
||||
const startY = (CANVAS_H - totalHeight) / 2 + lineHeight / 2
|
||||
|
||||
// Line 1: partially "sung" (first half highlighted)
|
||||
const words1 = SAMPLE_LINE_1.split(" ")
|
||||
const midPoint = Math.ceil(words1.length / 2)
|
||||
const sungPart = words1.slice(0, midPoint).join(" ")
|
||||
const unsungPart = " " + words1.slice(midPoint).join(" ")
|
||||
SAMPLE_LINES.forEach((line, i) => {
|
||||
const y = startY + i * lineHeight
|
||||
|
||||
// Measure widths for positioning
|
||||
const fullWidth1 = ctx.measureText(SAMPLE_LINE_1).width
|
||||
const sungWidth = ctx.measureText(sungPart).width
|
||||
const startX1 = centerX - fullWidth1 / 2
|
||||
if (i === 1) {
|
||||
// Line 2: partially "sung" — highlight first portion
|
||||
const words = line.split(" ")
|
||||
const midPoint = 3 // "This is Califor" split mid-word effect
|
||||
const sungText = words.slice(0, midPoint).join(" ")
|
||||
// Simulate mid-word highlight: "Califor" is partially sung
|
||||
const sungPart = sungText.slice(0, -2)
|
||||
const transitionChar = sungText.slice(-2)
|
||||
const unsungPart = words.slice(midPoint).join(" ")
|
||||
|
||||
// Draw sung portion
|
||||
ctx.fillStyle = SUNG_COLOR
|
||||
ctx.textAlign = "left"
|
||||
ctx.fillText(sungPart, startX1, baseY)
|
||||
const fullText = line
|
||||
const fullWidth = ctx.measureText(fullText).width
|
||||
const lineStartX = centerX - fullWidth / 2
|
||||
|
||||
// Draw unsung portion
|
||||
ctx.fillStyle = UNSUNG_COLOR
|
||||
ctx.fillText(unsungPart, startX1 + sungWidth, baseY)
|
||||
// Sung portion
|
||||
ctx.fillStyle = effectiveSungColor
|
||||
ctx.textAlign = "left"
|
||||
ctx.fillText(sungPart, lineStartX, y)
|
||||
|
||||
// Line 2: all unsung
|
||||
ctx.fillStyle = UNSUNG_COLOR
|
||||
ctx.textAlign = "center"
|
||||
ctx.fillText(SAMPLE_LINE_2, centerX, baseY + lineHeight)
|
||||
}, [backgroundUrl])
|
||||
// Transition characters (still sung color)
|
||||
const sungPartWidth = ctx.measureText(sungPart).width
|
||||
ctx.fillStyle = effectiveSungColor
|
||||
ctx.fillText(transitionChar, lineStartX + sungPartWidth, y)
|
||||
|
||||
// Unsung portion
|
||||
const transWidth = ctx.measureText(transitionChar).width
|
||||
ctx.fillStyle = effectiveUnsungColor
|
||||
ctx.fillText(" " + unsungPart, lineStartX + sungPartWidth + transWidth, y)
|
||||
|
||||
ctx.textAlign = "center"
|
||||
} else if (i === 0) {
|
||||
// Line 1: fully sung (already passed)
|
||||
ctx.fillStyle = effectiveSungColor
|
||||
ctx.fillText(line, centerX, y)
|
||||
} else {
|
||||
// Lines 3-4: unsung (upcoming)
|
||||
ctx.fillStyle = effectiveUnsungColor
|
||||
ctx.fillText(line, centerX, y)
|
||||
}
|
||||
})
|
||||
}, [backgroundUrl, backgroundColor, effectiveSungColor, effectiveUnsungColor])
|
||||
|
||||
useEffect(() => {
|
||||
draw()
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useRef, useCallback, useEffect, useState } from "react"
|
||||
import { api, adminApi, Job } from "@/lib/api"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, Settings } from "lucide-react"
|
||||
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, Settings, Lock, Globe, Pencil } from "lucide-react"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -14,14 +14,26 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { EditTrackModal } from "./EditTrackModal"
|
||||
|
||||
interface OutputLinksProps {
|
||||
job: Job
|
||||
onJobUpdated?: () => void
|
||||
}
|
||||
|
||||
export function OutputLinks({ job }: OutputLinksProps) {
|
||||
export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
// Use file_urls from job directly - no API call needed
|
||||
const downloadUrls = job.file_urls || null
|
||||
// Use state_data from job directly - no API call needed
|
||||
@@ -35,6 +47,9 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
const [emailInput, setEmailInput] = useState("")
|
||||
const [isSendingEmail, setIsSendingEmail] = useState(false)
|
||||
const [emailSent, setEmailSent] = useState(false)
|
||||
const [showVisibilityDialog, setShowVisibilityDialog] = useState(false)
|
||||
const [isChangingVisibility, setIsChangingVisibility] = useState(false)
|
||||
const [showEditModal, setShowEditModal] = useState(false)
|
||||
const copyTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const messageTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const emailTimeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
@@ -49,7 +64,7 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
}, [])
|
||||
|
||||
const { user } = useAuth()
|
||||
const { features } = useTenant()
|
||||
const { features, tenantId } = useTenant()
|
||||
const isAdmin = user?.role === 'admin'
|
||||
|
||||
// Check if outputs have been deleted by admin
|
||||
@@ -59,6 +74,11 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
const showYoutubeLink = features.youtube_upload && youtubeUrl && !outputsDeleted
|
||||
const showDropboxLink = features.dropbox_upload && dropboxUrl && !outputsDeleted
|
||||
|
||||
// Visibility change: available for completed consumer jobs (not tenant)
|
||||
const isPrivate = !!job.is_private
|
||||
const visibilityChangeInProgress = !!job.state_data?.visibility_change_in_progress
|
||||
const canChangeVisibility = job.status === "complete" && !tenantId && !visibilityChangeInProgress
|
||||
|
||||
const copyToClipboard = useCallback(async (url: string) => {
|
||||
// Check if clipboard API is available
|
||||
if (!navigator?.clipboard?.writeText) {
|
||||
@@ -138,6 +158,22 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
}
|
||||
}, [job.job_id, emailInput])
|
||||
|
||||
const handleChangeVisibility = useCallback(async () => {
|
||||
const targetVisibility = isPrivate ? 'public' : 'private'
|
||||
setIsChangingVisibility(true)
|
||||
setShowVisibilityDialog(false)
|
||||
|
||||
try {
|
||||
await api.changeVisibility(job.job_id, targetVisibility)
|
||||
onJobUpdated?.()
|
||||
} catch (err) {
|
||||
console.error("Failed to change visibility:", err)
|
||||
alert(`Failed to change visibility. ${err instanceof Error ? err.message : 'Please try again.'}`)
|
||||
} finally {
|
||||
setIsChangingVisibility(false)
|
||||
}
|
||||
}, [job.job_id, isPrivate, onJobUpdated])
|
||||
|
||||
const hasOutputs = showYoutubeLink || showDropboxLink || (downloadUrls && Object.keys(downloadUrls).length > 0)
|
||||
|
||||
// Check if we have any downloads (and outputs haven't been deleted)
|
||||
@@ -155,7 +191,7 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* Links, Downloads, and Admin Tools - all in one row */}
|
||||
{(hasDownloads || hasExternalLinks || isAdmin) && (
|
||||
{(hasDownloads || hasExternalLinks || isAdmin || canChangeVisibility) && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{/* Links first */}
|
||||
{hasExternalLinks && (
|
||||
@@ -265,6 +301,29 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Change Visibility Button */}
|
||||
{canChangeVisibility && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); setShowVisibilityDialog(true) }}
|
||||
disabled={isChangingVisibility}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-[#252525] hover:bg-[#333333] text-[var(--text)] border border-[var(--card-border)] transition-colors disabled:opacity-50"
|
||||
title={isPrivate ? "Make this track public" : "Make this track private"}
|
||||
>
|
||||
{isChangingVisibility ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : isPrivate ? (
|
||||
<Globe className="w-3 h-3" />
|
||||
) : (
|
||||
<Lock className="w-3 h-3" />
|
||||
)}
|
||||
{isChangingVisibility
|
||||
? (isPrivate ? "Making Public..." : "Making Private...")
|
||||
: (isPrivate ? "Make Public" : "Make Private")
|
||||
}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Admin Email Tools (only when job has outputs) */}
|
||||
{isAdmin && hasOutputs && (
|
||||
<div className="flex">
|
||||
@@ -295,6 +354,19 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Edit Track (visible when job is complete and has outputs) */}
|
||||
{job.status === "complete" && !outputsDeleted && hasOutputs && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); setShowEditModal(true) }}
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-amber-600 hover:bg-amber-500 text-white transition-colors"
|
||||
title="Edit lyrics, instrumental, or metadata"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
Edit
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Admin Link (always visible for admins) */}
|
||||
{isAdmin && (
|
||||
<a
|
||||
@@ -310,7 +382,7 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hasOutputs && !isAdmin && (
|
||||
{!hasOutputs && !isAdmin && !canChangeVisibility && (
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>No outputs available yet</p>
|
||||
)}
|
||||
|
||||
@@ -371,6 +443,64 @@ export function OutputLinks({ job }: OutputLinksProps) {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Change Visibility Confirmation Dialog */}
|
||||
<AlertDialog open={showVisibilityDialog} onOpenChange={setShowVisibilityDialog}>
|
||||
<AlertDialogContent onClick={(e) => e.stopPropagation()}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{isPrivate ? "Make This Track Public?" : "Make This Track Private?"}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-3">
|
||||
{isPrivate ? (
|
||||
<>
|
||||
<p>This will:</p>
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li>Remove any custom styling (backgrounds, colors) and reset to the standard Nomad Karaoke theme</li>
|
||||
<li>Regenerate title and end screens</li>
|
||||
<li>Re-render the karaoke video with default branding</li>
|
||||
<li>Publish to YouTube, Google Drive, and Dropbox</li>
|
||||
</ul>
|
||||
<p>This process takes approximately 15-30 minutes. You'll receive an email when it's complete.</p>
|
||||
<p className="font-medium" style={{ color: 'var(--text)' }}>
|
||||
Any custom styling you applied will be permanently removed.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>This will:</p>
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li>Remove the video from YouTube</li>
|
||||
<li>Remove files from Google Drive</li>
|
||||
<li>Move Dropbox files from the public folder to the private folder</li>
|
||||
<li>Assign a new private brand code</li>
|
||||
</ul>
|
||||
<p>The video content won't change. This usually takes about 1-2 minutes.</p>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
You can change it back to public later, but that will require re-rendering the video (~15-30 minutes).
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleChangeVisibility}>
|
||||
{isPrivate ? "Make Public" : "Make Private"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Edit Track Modal */}
|
||||
<EditTrackModal
|
||||
job={job}
|
||||
open={showEditModal}
|
||||
onOpenChange={setShowEditModal}
|
||||
onEditStarted={onJobUpdated}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useRef, useCallback } from "react"
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { CheckCircle2, Upload, Music, Loader2, AlertTriangle } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const ACCEPTED_AUDIO_TYPES = ".mp3,.wav,.flac,.m4a,.ogg,.aac"
|
||||
const ACCEPTED_AUDIO_MIMES = [
|
||||
"audio/mpeg", "audio/wav", "audio/x-wav", "audio/flac",
|
||||
"audio/mp4", "audio/m4a", "audio/ogg", "audio/aac",
|
||||
"application/octet-stream", // fallback for unrecognized
|
||||
]
|
||||
|
||||
interface TenantJobFlowProps {
|
||||
onJobCreated: () => void
|
||||
}
|
||||
|
||||
type SubmitPhase = "idle" | "creating" | "uploading-mixed" | "uploading-instrumental" | "completing" | "done"
|
||||
|
||||
export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
const { branding } = useTenant()
|
||||
|
||||
// Form fields
|
||||
const [artist, setArtist] = useState("")
|
||||
const [title, setTitle] = useState("")
|
||||
const [mixedFile, setMixedFile] = useState<File | null>(null)
|
||||
const [instrumentalFile, setInstrumentalFile] = useState<File | null>(null)
|
||||
|
||||
// Submission state
|
||||
const [phase, setPhase] = useState<SubmitPhase>("idle")
|
||||
const [uploadProgress, setUploadProgress] = useState(0)
|
||||
const [error, setError] = useState("")
|
||||
const [jobId, setJobId] = useState<string | null>(null)
|
||||
|
||||
// Refs for file inputs
|
||||
const mixedInputRef = useRef<HTMLInputElement>(null)
|
||||
const instrumentalInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const canSubmit = artist.trim() && title.trim() && mixedFile && instrumentalFile && phase === "idle"
|
||||
|
||||
const resetFlow = useCallback(() => {
|
||||
setArtist("")
|
||||
setTitle("")
|
||||
setMixedFile(null)
|
||||
setInstrumentalFile(null)
|
||||
setPhase("idle")
|
||||
setUploadProgress(0)
|
||||
setError("")
|
||||
setJobId(null)
|
||||
// Clear file inputs
|
||||
if (mixedInputRef.current) mixedInputRef.current.value = ""
|
||||
if (instrumentalInputRef.current) instrumentalInputRef.current.value = ""
|
||||
}, [])
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!canSubmit || !mixedFile || !instrumentalFile) return
|
||||
|
||||
setError("")
|
||||
setPhase("creating")
|
||||
|
||||
try {
|
||||
// Step 1: Create job with upload URLs
|
||||
const files = [
|
||||
{
|
||||
filename: mixedFile.name,
|
||||
content_type: mixedFile.type || "application/octet-stream",
|
||||
file_type: "audio",
|
||||
},
|
||||
{
|
||||
filename: instrumentalFile.name,
|
||||
content_type: instrumentalFile.type || "application/octet-stream",
|
||||
file_type: "existing_instrumental",
|
||||
},
|
||||
]
|
||||
|
||||
const createResponse = await api.createJobWithUploadUrls(
|
||||
artist.trim(),
|
||||
title.trim(),
|
||||
files,
|
||||
{ is_private: true, existing_instrumental: true },
|
||||
)
|
||||
|
||||
setJobId(createResponse.job_id)
|
||||
|
||||
// Step 2: Upload mixed audio
|
||||
setPhase("uploading-mixed")
|
||||
const audioUrl = createResponse.upload_urls.find(u => u.file_type === "audio")
|
||||
if (!audioUrl) throw new ApiError("No upload URL for audio file", 500)
|
||||
|
||||
await api.uploadToSignedUrl(
|
||||
audioUrl.upload_url,
|
||||
mixedFile,
|
||||
audioUrl.content_type,
|
||||
(loaded, total) => setUploadProgress(Math.round((loaded / total) * 50)),
|
||||
)
|
||||
|
||||
// Step 3: Upload instrumental
|
||||
setPhase("uploading-instrumental")
|
||||
const instrumentalUrl = createResponse.upload_urls.find(u => u.file_type === "existing_instrumental")
|
||||
if (!instrumentalUrl) throw new ApiError("No upload URL for instrumental file", 500)
|
||||
|
||||
await api.uploadToSignedUrl(
|
||||
instrumentalUrl.upload_url,
|
||||
instrumentalFile,
|
||||
instrumentalUrl.content_type,
|
||||
(loaded, total) => setUploadProgress(50 + Math.round((loaded / total) * 50)),
|
||||
)
|
||||
|
||||
// Step 4: Complete upload
|
||||
setPhase("completing")
|
||||
await api.completeJobUpload(createResponse.job_id, ["audio", "existing_instrumental"])
|
||||
|
||||
setPhase("done")
|
||||
onJobCreated()
|
||||
} catch (err: any) {
|
||||
const message = err instanceof ApiError
|
||||
? err.message
|
||||
: "Something went wrong. Please try again."
|
||||
setError(message)
|
||||
setPhase("idle")
|
||||
setUploadProgress(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Success view
|
||||
if (phase === "done") {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex flex-col items-center text-center py-5 space-y-3">
|
||||
<div
|
||||
className="w-12 h-12 rounded-full flex items-center justify-center"
|
||||
style={{ backgroundColor: "rgba(34, 197, 94, 0.15)" }}
|
||||
>
|
||||
<CheckCircle2 className="w-7 h-7 text-green-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: "var(--text)" }}>
|
||||
Track Submitted
|
||||
</h2>
|
||||
<p className="text-sm mt-1" style={{ color: "var(--text-muted)" }}>
|
||||
<span className="font-medium" style={{ color: "var(--text)" }}>
|
||||
{artist} - {title}
|
||||
</span>
|
||||
</p>
|
||||
{jobId && (
|
||||
<p className="text-xs mt-0.5 font-mono" style={{ color: "var(--text-muted)" }} data-testid="created-job-id">
|
||||
ID: {jobId.slice(0, 8)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Timeline — simplified for tenant (no audio processing step) */}
|
||||
<p className="text-xs font-semibold uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>
|
||||
What happens next
|
||||
</p>
|
||||
<div className="space-y-0 mt-3">
|
||||
{/* Step 1: Lyrics transcription */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-blue-500/15">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-blue-400">
|
||||
<path d="M8 1.5a1.25 1.25 0 0 1 1.177.825l.573 1.608 1.608.573a1.25 1.25 0 0 1 0 2.354l-1.608.573-.573 1.608a1.25 1.25 0 0 1-2.354 0l-.573-1.608-1.608-.573a1.25 1.25 0 0 1 0-2.354l1.608-.573.573-1.608A1.25 1.25 0 0 1 8 1.5Z" fill="currentColor" opacity="0.85"/>
|
||||
<path d="M12 9a1 1 0 0 1 .94.66l.36 1.02 1.02.36a1 1 0 0 1 0 1.884l-1.02.36-.36 1.02a1 1 0 0 1-1.88 0l-.36-1.02-1.02-.36a1 1 0 0 1 0-1.884l1.02-.36.36-1.02A1 1 0 0 1 12 9Z" fill="currentColor" opacity="0.55"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: "var(--card-border)" }} />
|
||||
</div>
|
||||
<div className="pb-4 pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Lyrics transcription</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
|
||||
We transcribe and sync lyrics from your audio. <span className="font-medium" style={{ color: "var(--text)" }}>~5 minutes</span>
|
||||
</p>
|
||||
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-blue-500/15 text-blue-400">
|
||||
Automatic
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step 2: User review */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: "rgba(255, 122, 204, 0.15)" }}>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ color: "var(--brand-pink)" }}>
|
||||
<path d="M8 2a3 3 0 1 0 0 6 3 3 0 0 0 0-6ZM3.5 13.5c0-2.485 2.015-4.5 4.5-4.5s4.5 2.015 4.5 4.5a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5Z" fill="currentColor" opacity="0.85"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: "var(--card-border)" }} />
|
||||
</div>
|
||||
<div className="pb-4 pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Review lyrics</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
|
||||
Check the synced lyrics and fix any errors.
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
|
||||
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: "rgba(255, 122, 204, 0.15)", color: "var(--brand-pink)" }}>
|
||||
You
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-[10px]" style={{ color: "var(--text-muted)" }}>
|
||||
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
|
||||
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
|
||||
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
|
||||
</svg>
|
||||
Email when ready
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step 3: Video delivered */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-green-500/15">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-green-400">
|
||||
<path d="M3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v11a.5.5 0 0 1-.765.424L8 11.28l-4.235 2.644A.5.5 0 0 1 3 13.5v-11Z" fill="currentColor" opacity="0.5"/>
|
||||
<path d="M6.354 7.854 7.5 9l2.146-2.146a.5.5 0 0 0-.708-.708L7.5 7.586l-.646-.647a.5.5 0 1 0-.708.708l.208.207Z" fill="currentColor"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Video delivered</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
|
||||
After approval, your karaoke video is rendered and delivered. <span className="font-medium" style={{ color: "var(--text)" }}>~10 minutes</span>
|
||||
</p>
|
||||
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-green-500/15 text-green-400">
|
||||
Automatic
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-[10px] text-center" style={{ color: "var(--text-muted)" }}>
|
||||
Track progress in the <span className="font-medium" style={{ color: "var(--text)" }}>Recent Jobs</span> list.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={resetFlow}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
style={{ borderColor: "var(--card-border)", color: "var(--text)" }}
|
||||
>
|
||||
<Music className="w-4 h-4 mr-2" />
|
||||
Submit Another Track
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const isSubmitting = phase !== "idle"
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Artist */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="tenant-artist" style={{ color: "var(--text)" }}>Artist</Label>
|
||||
<Input
|
||||
id="tenant-artist"
|
||||
placeholder="e.g. Adele"
|
||||
value={artist}
|
||||
onChange={e => setArtist(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
style={{ borderColor: "var(--card-border)", color: "var(--text)", backgroundColor: "var(--input)" }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="tenant-title" style={{ color: "var(--text)" }}>Title</Label>
|
||||
<Input
|
||||
id="tenant-title"
|
||||
placeholder="e.g. Someone Like You"
|
||||
value={title}
|
||||
onChange={e => setTitle(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
style={{ borderColor: "var(--card-border)", color: "var(--text)", backgroundColor: "var(--input)" }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Mixed Audio */}
|
||||
<FileDropZone
|
||||
id="tenant-mixed-audio"
|
||||
label="Mixed Audio"
|
||||
hint="The full song with vocals"
|
||||
file={mixedFile}
|
||||
onFileSelect={setMixedFile}
|
||||
inputRef={mixedInputRef}
|
||||
disabled={isSubmitting}
|
||||
accept={ACCEPTED_AUDIO_TYPES}
|
||||
/>
|
||||
|
||||
{/* Instrumental Audio */}
|
||||
<FileDropZone
|
||||
id="tenant-instrumental-audio"
|
||||
label="Instrumental Audio"
|
||||
hint="The instrumental (backing track)"
|
||||
file={instrumentalFile}
|
||||
onFileSelect={setInstrumentalFile}
|
||||
inputRef={instrumentalInputRef}
|
||||
disabled={isSubmitting}
|
||||
accept={ACCEPTED_AUDIO_TYPES}
|
||||
/>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="flex items-start gap-2 text-sm p-3 rounded-lg" style={{ backgroundColor: "rgba(239, 68, 68, 0.1)", color: "#ef4444" }}>
|
||||
<AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Progress */}
|
||||
{isSubmitting && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<span>
|
||||
{phase === "creating" && "Creating job..."}
|
||||
{phase === "uploading-mixed" && "Uploading mixed audio..."}
|
||||
{phase === "uploading-instrumental" && "Uploading instrumental..."}
|
||||
{phase === "completing" && "Finalizing..."}
|
||||
</span>
|
||||
</div>
|
||||
{(phase === "uploading-mixed" || phase === "uploading-instrumental") && (
|
||||
<div className="w-full h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: "var(--card-border)" }}>
|
||||
<div
|
||||
className="h-full rounded-full transition-all duration-300"
|
||||
style={{
|
||||
width: `${uploadProgress}%`,
|
||||
backgroundColor: "var(--tenant-primary, var(--brand-pink))",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Submit */}
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!canSubmit}
|
||||
className="w-full"
|
||||
style={{
|
||||
backgroundColor: canSubmit ? "var(--tenant-primary, var(--brand-pink))" : undefined,
|
||||
color: canSubmit ? "var(--primary-foreground)" : undefined,
|
||||
}}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Submit Track
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// File drop zone sub-component
|
||||
// ============================================================================
|
||||
|
||||
interface FileDropZoneProps {
|
||||
id: string
|
||||
label: string
|
||||
hint: string
|
||||
file: File | null
|
||||
onFileSelect: (file: File | null) => void
|
||||
inputRef: React.RefObject<HTMLInputElement | null>
|
||||
disabled: boolean
|
||||
accept: string
|
||||
}
|
||||
|
||||
function FileDropZone({ id, label, hint, file, onFileSelect, inputRef, disabled, accept }: FileDropZoneProps) {
|
||||
const [isDragOver, setIsDragOver] = useState(false)
|
||||
|
||||
function handleDrop(e: React.DragEvent) {
|
||||
e.preventDefault()
|
||||
setIsDragOver(false)
|
||||
if (disabled) return
|
||||
const droppedFile = e.dataTransfer.files[0]
|
||||
if (droppedFile) onFileSelect(droppedFile)
|
||||
}
|
||||
|
||||
function handleDragOver(e: React.DragEvent) {
|
||||
e.preventDefault()
|
||||
if (!disabled) setIsDragOver(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={id} style={{ color: "var(--text)" }}>{label}</Label>
|
||||
<div
|
||||
className={`relative border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors ${
|
||||
disabled ? "opacity-50 cursor-not-allowed" : "hover:border-white/30"
|
||||
}`}
|
||||
style={{
|
||||
borderColor: isDragOver ? "var(--tenant-primary, var(--brand-pink))" : "var(--card-border)",
|
||||
backgroundColor: isDragOver ? "rgba(255, 255, 255, 0.03)" : "transparent",
|
||||
}}
|
||||
onClick={() => !disabled && inputRef.current?.click()}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={() => setIsDragOver(false)}
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
id={id}
|
||||
type="file"
|
||||
accept={accept}
|
||||
className="hidden"
|
||||
disabled={disabled}
|
||||
onChange={e => {
|
||||
const f = e.target.files?.[0]
|
||||
if (f) onFileSelect(f)
|
||||
}}
|
||||
/>
|
||||
{file ? (
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Music className="w-4 h-4 shrink-0" style={{ color: "var(--tenant-primary, var(--brand-pink))" }} />
|
||||
<span className="text-sm truncate" style={{ color: "var(--text)" }}>{file.name}</span>
|
||||
<span className="text-xs shrink-0" style={{ color: "var(--text-muted)" }}>
|
||||
({(file.size / (1024 * 1024)).toFixed(1)} MB)
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<Upload className="w-5 h-5 mx-auto mb-1" style={{ color: "var(--text-muted)" }} />
|
||||
<p className="text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
Drop file here or <span style={{ color: "var(--tenant-primary, var(--brand-pink))" }}>browse</span>
|
||||
</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>{hint}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ interface TitleCardPreviewProps {
|
||||
artist: string
|
||||
title: string
|
||||
customBackgroundUrl?: string // Object URL from File for custom background
|
||||
backgroundColor?: string // Solid color hex (used when no customBackgroundUrl)
|
||||
titleColor?: string // Hex color override (default #ffffff)
|
||||
artistColor?: string // Hex color override (default #ffdf6b)
|
||||
}
|
||||
@@ -121,7 +122,7 @@ function drawTextBlock(
|
||||
}
|
||||
}
|
||||
|
||||
export function TitleCardPreview({ artist, title, customBackgroundUrl, titleColor, artistColor }: TitleCardPreviewProps) {
|
||||
export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroundColor, titleColor, artistColor }: TitleCardPreviewProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
|
||||
const effectiveTitleColor = titleColor || TITLE_COLOR
|
||||
@@ -133,7 +134,7 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, titleColo
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
|
||||
// Draw background image (custom or default)
|
||||
// Draw background: custom image > solid color > default image
|
||||
try {
|
||||
if (customBackgroundUrl) {
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
@@ -143,12 +144,15 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, titleColo
|
||||
el.src = customBackgroundUrl
|
||||
})
|
||||
ctx.drawImage(img, 0, 0, CANVAS_W, CANVAS_H)
|
||||
} else if (backgroundColor) {
|
||||
ctx.fillStyle = backgroundColor
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
} else {
|
||||
const bgImg = await loadBgImage()
|
||||
ctx.drawImage(bgImg, 0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
} catch {
|
||||
ctx.fillStyle = "#000000"
|
||||
ctx.fillStyle = backgroundColor || "#000000"
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
|
||||
@@ -188,7 +192,7 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, titleColo
|
||||
artist ? effectiveArtistColor : "rgba(255,223,107,0.25)",
|
||||
fontFamily,
|
||||
)
|
||||
}, [artist, title, customBackgroundUrl, effectiveTitleColor, effectiveArtistColor])
|
||||
}, [artist, title, customBackgroundUrl, backgroundColor, effectiveTitleColor, effectiveArtistColor])
|
||||
|
||||
useEffect(() => {
|
||||
draw()
|
||||
|
||||
@@ -3,39 +3,46 @@ import { CustomizeStep } from "../steps/CustomizeStep"
|
||||
|
||||
// Mock canvas-based components — they require browser APIs not available in jsdom
|
||||
jest.mock("../TitleCardPreview", () => ({
|
||||
TitleCardPreview: ({ artist, title, customBackgroundUrl, titleColor, artistColor }: any) => (
|
||||
TitleCardPreview: ({ artist, title, customBackgroundUrl, titleColor, artistColor, backgroundColor }: any) => (
|
||||
<div data-testid="title-card-preview"
|
||||
data-artist={artist}
|
||||
data-title={title}
|
||||
data-custom-bg={customBackgroundUrl || ""}
|
||||
data-title-color={titleColor || ""}
|
||||
data-artist-color={artistColor || ""}
|
||||
data-bg-color={backgroundColor || ""}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
|
||||
jest.mock("../KaraokeBackgroundPreview", () => ({
|
||||
KaraokeBackgroundPreview: ({ backgroundUrl }: any) => (
|
||||
<div data-testid="karaoke-bg-preview" data-url={backgroundUrl} />
|
||||
KaraokeBackgroundPreview: ({ backgroundUrl, backgroundColor, sungColor, unsungColor }: any) => (
|
||||
<div data-testid="karaoke-bg-preview"
|
||||
data-url={backgroundUrl || ""}
|
||||
data-bg-color={backgroundColor || ""}
|
||||
data-sung-color={sungColor || ""}
|
||||
data-unsung-color={unsungColor || ""}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
|
||||
jest.mock("../ImageUploadField", () => ({
|
||||
ImageUploadField: ({ label, file, onChange, disabled }: any) => (
|
||||
<div data-testid={`upload-${label.replace(/\s+/g, "-").toLowerCase()}`}>
|
||||
<span>{label}</span>
|
||||
ImageUploadField: ({ label, description, file, onChange, disabled, hidePreview }: any) => (
|
||||
<div data-testid={`upload-${(label || description || "field").replace(/\s+/g, "-").toLowerCase().slice(0, 30)}`}>
|
||||
{label && <span>{label}</span>}
|
||||
{description && <span>{description}</span>}
|
||||
{file && <span data-testid="file-name">{file.name}</span>}
|
||||
<button data-testid={`upload-btn-${label.replace(/\s+/g, "-").toLowerCase()}`}
|
||||
<button
|
||||
data-testid={`upload-btn`}
|
||||
onClick={() => onChange(new File(["data"], "test.png", { type: "image/png" }))}
|
||||
disabled={disabled}
|
||||
>
|
||||
Upload
|
||||
</button>
|
||||
<button data-testid={`clear-btn-${label.replace(/\s+/g, "-").toLowerCase()}`}
|
||||
onClick={() => onChange(null)}
|
||||
>
|
||||
<button data-testid={`clear-btn`} onClick={() => onChange(null)}>
|
||||
Clear
|
||||
</button>
|
||||
{hidePreview && <span data-testid="hide-preview" />}
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
@@ -48,7 +55,6 @@ const defaultProps = {
|
||||
onDisplayArtistChange: jest.fn(),
|
||||
onDisplayTitleChange: jest.fn(),
|
||||
isPrivate: false,
|
||||
onPrivateChange: jest.fn(),
|
||||
karaokeBackground: null as File | null,
|
||||
onKaraokeBackgroundChange: jest.fn(),
|
||||
introBackground: null as File | null,
|
||||
@@ -63,93 +69,139 @@ const defaultProps = {
|
||||
describe("CustomizeStep", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
// Mock URL.createObjectURL for the component's useMemo
|
||||
global.URL.createObjectURL = jest.fn(() => "blob:mock")
|
||||
global.URL.revokeObjectURL = jest.fn()
|
||||
})
|
||||
|
||||
it("renders title card preview with artist and title", () => {
|
||||
describe("public mode (isPrivate=false)", () => {
|
||||
it("shows title card preview and display fields, but no style options", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} />)
|
||||
|
||||
// Display override fields are shown
|
||||
expect(screen.getByLabelText(/Title Card Artist/)).toBeInTheDocument()
|
||||
expect(screen.getByLabelText(/Title Card Title/)).toBeInTheDocument()
|
||||
|
||||
// Title card preview is shown
|
||||
expect(screen.getByTestId("title-card-preview")).toBeInTheDocument()
|
||||
|
||||
// No style customization or karaoke preview
|
||||
expect(screen.queryByText("Custom Video Style")).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId("karaoke-bg-preview")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("calls onConfirm when create button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} />)
|
||||
|
||||
fireEvent.click(screen.getByText("Create Karaoke Video"))
|
||||
expect(defaultProps.onConfirm).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("shows loading state when isSubmitting", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} isSubmitting={true} />)
|
||||
expect(screen.getByText("Creating...")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe("private mode (isPrivate=true)", () => {
|
||||
it("shows custom video style section with side-by-side previews", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
expect(screen.getByText("Custom Video Style")).toBeInTheDocument()
|
||||
expect(screen.getByTestId("title-card-preview")).toBeInTheDocument()
|
||||
expect(screen.getByTestId("karaoke-bg-preview")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("renders title card preview with artist and title", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist")).toBe("Test Artist")
|
||||
expect(preview.getAttribute("data-title")).toBe("Test Song")
|
||||
})
|
||||
|
||||
it("uses displayArtist/displayTitle in preview when provided", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
displayArtist="Custom Artist"
|
||||
displayTitle="Custom Title"
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist")).toBe("Custom Artist")
|
||||
expect(preview.getAttribute("data-title")).toBe("Custom Title")
|
||||
})
|
||||
|
||||
it("shows color pickers for title card and lyrics", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
expect(screen.getByText("Artist Color")).toBeInTheDocument()
|
||||
expect(screen.getByText("Title Color")).toBeInTheDocument()
|
||||
expect(screen.getByText("Highlight Color")).toBeInTheDocument()
|
||||
expect(screen.getByText("Lyrics Color")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("passes color overrides to title card preview", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
colorOverrides={{ artist_color: "#ff0000", title_color: "#00ff00" }}
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist-color")).toBe("#ff0000")
|
||||
expect(preview.getAttribute("data-title-color")).toBe("#00ff00")
|
||||
})
|
||||
|
||||
it("passes lyrics color overrides to karaoke preview", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
colorOverrides={{ sung_lyrics_color: "#ff0000", unsung_lyrics_color: "#00ff00" }}
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("karaoke-bg-preview")
|
||||
expect(preview.getAttribute("data-sung-color")).toBe("#ff0000")
|
||||
expect(preview.getAttribute("data-unsung-color")).toBe("#00ff00")
|
||||
})
|
||||
|
||||
it("shows background mode toggles", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
// Two sets of Default/Image/Color toggles (one per canvas)
|
||||
const defaultBtns = screen.getAllByText("Default")
|
||||
const imageBtns = screen.getAllByText("Image")
|
||||
const colorBtns = screen.getAllByText("Color")
|
||||
|
||||
expect(defaultBtns).toHaveLength(2)
|
||||
expect(imageBtns).toHaveLength(2)
|
||||
expect(colorBtns).toHaveLength(2)
|
||||
})
|
||||
|
||||
it("calls onConfirm when create button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
fireEvent.click(screen.getByText("Create Karaoke Video"))
|
||||
expect(defaultProps.onConfirm).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("shows loading state when isSubmitting", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} isSubmitting={true} />)
|
||||
expect(screen.getByText("Creating...")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("calls onBack when back button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} />)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview).toBeInTheDocument()
|
||||
expect(preview.getAttribute("data-artist")).toBe("Test Artist")
|
||||
expect(preview.getAttribute("data-title")).toBe("Test Song")
|
||||
})
|
||||
|
||||
it("uses displayArtist/displayTitle in preview when provided", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
displayArtist="Custom Artist"
|
||||
displayTitle="Custom Title"
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist")).toBe("Custom Artist")
|
||||
expect(preview.getAttribute("data-title")).toBe("Custom Title")
|
||||
})
|
||||
|
||||
it("does NOT show custom video style section when isPrivate is false", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} />)
|
||||
|
||||
expect(screen.queryByText("Custom Video Style")).not.toBeInTheDocument()
|
||||
expect(screen.queryByText("Karaoke Background")).not.toBeInTheDocument()
|
||||
expect(screen.queryByText("Title Card Background")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows custom video style section when isPrivate is true", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
expect(screen.getByText("Custom Video Style")).toBeInTheDocument()
|
||||
expect(screen.getByText("Karaoke Background")).toBeInTheDocument()
|
||||
expect(screen.getByText("Title Card Background")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows color pickers when isPrivate is true", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
expect(screen.getByText("Artist Color")).toBeInTheDocument()
|
||||
expect(screen.getByText("Title Color")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("passes color overrides to title card preview", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
colorOverrides={{ artist_color: "#ff0000", title_color: "#00ff00" }}
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist-color")).toBe("#ff0000")
|
||||
expect(preview.getAttribute("data-title-color")).toBe("#00ff00")
|
||||
})
|
||||
|
||||
it("toggles private checkbox and triggers onPrivateChange", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} />)
|
||||
|
||||
const checkbox = screen.getByRole("checkbox")
|
||||
fireEvent.click(checkbox)
|
||||
|
||||
expect(defaultProps.onPrivateChange).toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it("calls onConfirm when create button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} />)
|
||||
|
||||
const button = screen.getByText("Create Karaoke Video")
|
||||
fireEvent.click(button)
|
||||
|
||||
expect(defaultProps.onConfirm).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("shows loading state when isSubmitting", () => {
|
||||
render(<CustomizeStep {...defaultProps} isSubmitting={true} />)
|
||||
|
||||
expect(screen.getByText("Creating...")).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByText("Back"))
|
||||
expect(defaultProps.onBack).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("disables form controls when isSubmitting", () => {
|
||||
@@ -158,55 +210,4 @@ describe("CustomizeStep", () => {
|
||||
const createBtn = screen.getByText("Creating...").closest("button")
|
||||
expect(createBtn).toBeDisabled()
|
||||
})
|
||||
|
||||
it("calls onBack when back button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} />)
|
||||
|
||||
const backBtn = screen.getByText("Back")
|
||||
fireEvent.click(backBtn)
|
||||
|
||||
expect(defaultProps.onBack).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("shows karaoke background preview when file is provided and isPrivate", () => {
|
||||
const file = new File(["data"], "karaoke-bg.png", { type: "image/png" })
|
||||
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
karaokeBackground={file}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByTestId("karaoke-bg-preview")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("does NOT show karaoke background preview when no file", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
karaokeBackground={null}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByTestId("karaoke-bg-preview")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("passes custom intro background to title card preview", () => {
|
||||
const file = new File(["data"], "intro-bg.png", { type: "image/png" })
|
||||
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
introBackground={file}
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
// Should have a blob URL for the custom background
|
||||
expect(preview.getAttribute("data-custom-bg")).toBe("blob:mock")
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useMemo, useCallback, useRef } from "react"
|
||||
import { api, ApiError, type UploadProgress } from "@/lib/api"
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import {
|
||||
ExtendedAudioSearchResult,
|
||||
groupResults,
|
||||
@@ -16,19 +16,16 @@ import {
|
||||
} from "@/lib/audio-search-utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Loader2, Music2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info } from "lucide-react"
|
||||
import { Loader2, ChevronDown, ChevronUp, Upload, Youtube, ArrowLeft, Check, AlertTriangle, CheckCircle2, Lightbulb, Info } from "lucide-react"
|
||||
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
|
||||
|
||||
interface AudioSourceStepProps {
|
||||
artist: string
|
||||
title: string
|
||||
displayArtist: string
|
||||
displayTitle: string
|
||||
isPrivate: boolean
|
||||
onSearchCompleted: (searchSessionId: string) => void
|
||||
onJobCreated: (jobId: string, source: "upload" | "url") => void
|
||||
onSearchResultChosen: (resultIndex: number) => void
|
||||
onFallbackComplete: () => void
|
||||
onUrlReady: (url: string) => void
|
||||
onFileReady: (file: File) => void
|
||||
onBack: () => void
|
||||
noCredits: boolean
|
||||
}
|
||||
@@ -93,13 +90,10 @@ function MismatchBadge({ searchTitle, result }: { searchTitle: string; result: E
|
||||
export function AudioSourceStep({
|
||||
artist,
|
||||
title,
|
||||
displayArtist,
|
||||
displayTitle,
|
||||
isPrivate,
|
||||
onSearchCompleted,
|
||||
onJobCreated,
|
||||
onSearchResultChosen,
|
||||
onFallbackComplete,
|
||||
onUrlReady,
|
||||
onFileReady,
|
||||
onBack,
|
||||
noCredits,
|
||||
}: AudioSourceStepProps) {
|
||||
@@ -116,9 +110,7 @@ export function AudioSourceStep({
|
||||
// Fallback form state
|
||||
const [uploadFile, setUploadFile] = useState<File | null>(null)
|
||||
const [youtubeUrl, setYoutubeUrl] = useState("")
|
||||
const [isSubmittingFallback, setIsSubmittingFallback] = useState(false)
|
||||
const [fallbackMode, setFallbackMode] = useState<"upload" | "url" | null>(null)
|
||||
const [uploadProgress, setUploadProgress] = useState<UploadProgress | null>(null)
|
||||
|
||||
// Search with retry for network failures
|
||||
const doSearch = useCallback(async (retryCount = 0): Promise<void> => {
|
||||
@@ -180,63 +172,16 @@ export function AudioSourceStep({
|
||||
})
|
||||
}
|
||||
|
||||
async function handleUploadSubmit(e: React.FormEvent) {
|
||||
function handleUploadSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!uploadFile) return
|
||||
|
||||
setIsSubmittingFallback(true)
|
||||
setError("")
|
||||
setIsCreditError(false)
|
||||
setIsTimeoutError(false)
|
||||
setUploadProgress(null)
|
||||
try {
|
||||
const response = await api.uploadJobSmart(
|
||||
uploadFile, artist.trim(), title.trim(),
|
||||
{ is_private: isPrivate },
|
||||
(progress) => setUploadProgress(progress),
|
||||
)
|
||||
onJobCreated(response.job_id, "upload" as const)
|
||||
onFallbackComplete()
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setIsCreditError(true)
|
||||
setError("You're out of credits. Buy more to continue creating karaoke videos.")
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError("Failed to upload file")
|
||||
}
|
||||
} finally {
|
||||
setIsSubmittingFallback(false)
|
||||
setUploadProgress(null)
|
||||
}
|
||||
onFileReady(uploadFile)
|
||||
}
|
||||
|
||||
async function handleUrlSubmit(e: React.FormEvent) {
|
||||
function handleUrlSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!youtubeUrl.trim()) return
|
||||
|
||||
setIsSubmittingFallback(true)
|
||||
setError("")
|
||||
setIsCreditError(false)
|
||||
try {
|
||||
const response = await api.createJobFromUrl(youtubeUrl.trim(), artist.trim(), title.trim(), {
|
||||
is_private: isPrivate,
|
||||
})
|
||||
onJobCreated(response.job_id, "url" as const)
|
||||
onFallbackComplete()
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 402) {
|
||||
setIsCreditError(true)
|
||||
setError("You're out of credits. Buy more to continue creating karaoke videos.")
|
||||
} else if (err instanceof ApiError) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError("Failed to create job from URL")
|
||||
}
|
||||
} finally {
|
||||
setIsSubmittingFallback(false)
|
||||
}
|
||||
onUrlReady(youtubeUrl.trim())
|
||||
}
|
||||
|
||||
const isLossyBest = confidence.bestCategory === 'YOUTUBE'
|
||||
@@ -254,7 +199,6 @@ export function AudioSourceStep({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleBack}
|
||||
disabled={isSubmittingFallback}
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
@@ -328,11 +272,9 @@ export function AudioSourceStep({
|
||||
setYoutubeUrl={setYoutubeUrl}
|
||||
uploadFile={uploadFile}
|
||||
setUploadFile={setUploadFile}
|
||||
isSubmittingFallback={isSubmittingFallback}
|
||||
noCredits={noCredits}
|
||||
onUrlSubmit={handleUrlSubmit}
|
||||
onUploadSubmit={handleUploadSubmit}
|
||||
uploadProgress={uploadProgress}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
@@ -369,11 +311,9 @@ export function AudioSourceStep({
|
||||
setYoutubeUrl={setYoutubeUrl}
|
||||
uploadFile={uploadFile}
|
||||
setUploadFile={setUploadFile}
|
||||
isSubmittingFallback={isSubmittingFallback}
|
||||
noCredits={noCredits}
|
||||
onUrlSubmit={handleUrlSubmit}
|
||||
onUploadSubmit={handleUploadSubmit}
|
||||
uploadProgress={uploadProgress}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -871,11 +811,9 @@ function FallbackSection({
|
||||
setYoutubeUrl,
|
||||
uploadFile,
|
||||
setUploadFile,
|
||||
isSubmittingFallback,
|
||||
noCredits,
|
||||
onUrlSubmit,
|
||||
onUploadSubmit,
|
||||
uploadProgress,
|
||||
}: {
|
||||
tier: number
|
||||
hasResults: boolean
|
||||
@@ -885,11 +823,9 @@ function FallbackSection({
|
||||
setYoutubeUrl: (url: string) => void
|
||||
uploadFile: File | null
|
||||
setUploadFile: (file: File | null) => void
|
||||
isSubmittingFallback: boolean
|
||||
noCredits: boolean
|
||||
onUrlSubmit: (e: React.FormEvent) => void
|
||||
onUploadSubmit: (e: React.FormEvent) => void
|
||||
uploadProgress: UploadProgress | null
|
||||
}) {
|
||||
const isTier3WithResults = tier === 3 && hasResults
|
||||
const largeButtons = !hasResults
|
||||
@@ -942,21 +878,16 @@ function FallbackSection({
|
||||
onChange={(e) => setYoutubeUrl(e.target.value)}
|
||||
className="pl-10 text-xs"
|
||||
style={{ backgroundColor: 'var(--background)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
disabled={isSubmittingFallback}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={!youtubeUrl.trim() || isSubmittingFallback || noCredits}
|
||||
disabled={!youtubeUrl.trim() || noCredits}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
|
||||
>
|
||||
{isSubmittingFallback ? (
|
||||
<><Loader2 className="w-3 h-3 mr-1 animate-spin" /> Creating...</>
|
||||
) : (
|
||||
"Use This URL"
|
||||
)}
|
||||
Use This URL
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
@@ -979,7 +910,6 @@ function FallbackSection({
|
||||
if (file) setUploadFile(file)
|
||||
}}
|
||||
className="sr-only"
|
||||
disabled={isSubmittingFallback}
|
||||
/>
|
||||
{uploadFile ? (
|
||||
<div>
|
||||
@@ -996,52 +926,20 @@ function FallbackSection({
|
||||
</label>
|
||||
|
||||
{/* Large file warning */}
|
||||
{uploadFile && uploadFile.size > 100 * 1024 * 1024 && !isSubmittingFallback && (
|
||||
{uploadFile && uploadFile.size > 100 * 1024 * 1024 && (
|
||||
<div className="flex items-start gap-2 rounded p-2 text-[10px] text-amber-400 bg-amber-500/10">
|
||||
<AlertTriangle className="w-3.5 h-3.5 shrink-0 mt-0.5" />
|
||||
<span>Large file ({(uploadFile.size / 1024 / 1024).toFixed(0)} MB) — upload may take a while depending on your connection.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Upload progress bar */}
|
||||
{uploadProgress && (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
<span>
|
||||
{uploadProgress.phase === 'creating' && 'Preparing upload...'}
|
||||
{uploadProgress.phase === 'uploading' && `Uploading... ${(uploadProgress.loaded / 1024 / 1024).toFixed(1)} / ${(uploadProgress.total / 1024 / 1024).toFixed(1)} MB`}
|
||||
{uploadProgress.phase === 'finalizing' && 'Finalizing...'}
|
||||
</span>
|
||||
{uploadProgress.phase === 'uploading' && uploadProgress.total > 0 && (
|
||||
<span>{Math.round((uploadProgress.loaded / uploadProgress.total) * 100)}%</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: 'var(--card-border)' }}>
|
||||
<div
|
||||
className="h-full rounded-full transition-all duration-300"
|
||||
style={{
|
||||
backgroundColor: 'var(--brand-pink)',
|
||||
width: uploadProgress.phase === 'creating' ? '5%'
|
||||
: uploadProgress.phase === 'finalizing' ? '95%'
|
||||
: uploadProgress.total > 0 ? `${Math.round((uploadProgress.loaded / uploadProgress.total) * 90) + 5}%`
|
||||
: '5%',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={!uploadFile || isSubmittingFallback || noCredits}
|
||||
disabled={!uploadFile || noCredits}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white"
|
||||
>
|
||||
{isSubmittingFallback ? (
|
||||
<><Loader2 className="w-3 h-3 mr-1 animate-spin" /> Uploading...</>
|
||||
) : (
|
||||
"Upload & Create"
|
||||
)}
|
||||
Use This File
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useRef } from "react"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { ArrowLeft, Loader2, Palette } from "lucide-react"
|
||||
import { ArrowLeft, Loader2, Palette, Image as ImageIcon, Paintbrush } from "lucide-react"
|
||||
import { TitleCardPreview } from "../TitleCardPreview"
|
||||
import { KaraokeBackgroundPreview } from "../KaraokeBackgroundPreview"
|
||||
import { ImageUploadField } from "../ImageUploadField"
|
||||
@@ -12,6 +12,8 @@ import { ImageUploadField } from "../ImageUploadField"
|
||||
export interface ColorOverrides {
|
||||
artist_color?: string
|
||||
title_color?: string
|
||||
sung_lyrics_color?: string
|
||||
unsung_lyrics_color?: string
|
||||
}
|
||||
|
||||
interface CustomizeStepProps {
|
||||
@@ -22,7 +24,6 @@ interface CustomizeStepProps {
|
||||
onDisplayArtistChange: (value: string) => void
|
||||
onDisplayTitleChange: (value: string) => void
|
||||
isPrivate: boolean
|
||||
onPrivateChange: (value: boolean) => void
|
||||
karaokeBackground: File | null
|
||||
onKaraokeBackgroundChange: (file: File | null) => void
|
||||
introBackground: File | null
|
||||
@@ -35,6 +36,163 @@ interface CustomizeStepProps {
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
// Preset colors for solid backgrounds
|
||||
const BG_PRESETS = [
|
||||
{ label: "Black", color: "#000000" },
|
||||
{ label: "Dark Blue", color: "#1a1a2e" },
|
||||
{ label: "Dark Purple", color: "#16213e" },
|
||||
{ label: "Green Screen", color: "#00b140" },
|
||||
{ label: "White", color: "#ffffff" },
|
||||
]
|
||||
|
||||
type BgMode = "default" | "image" | "solid"
|
||||
|
||||
/**
|
||||
* Generate a tiny 4x4 solid color PNG blob for uploading as a background.
|
||||
* The backend expects an image file, so we create one client-side.
|
||||
*/
|
||||
function generateSolidColorBlob(hexColor: string): Promise<File> {
|
||||
return new Promise((resolve) => {
|
||||
const canvas = document.createElement("canvas")
|
||||
canvas.width = 4
|
||||
canvas.height = 4
|
||||
const ctx = canvas.getContext("2d")!
|
||||
ctx.fillStyle = hexColor
|
||||
ctx.fillRect(0, 0, 4, 4)
|
||||
canvas.toBlob((blob) => {
|
||||
resolve(new File([blob!], `solid-${hexColor.replace('#', '')}.png`, { type: "image/png" }))
|
||||
}, "image/png")
|
||||
})
|
||||
}
|
||||
|
||||
function ColorPickerField({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
defaultColor,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
id: string
|
||||
label: string
|
||||
value?: string
|
||||
defaultColor: string
|
||||
onChange: (val: string | undefined) => void
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={id} className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
{label}
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
id={id}
|
||||
value={value || defaultColor}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={value || ""}
|
||||
placeholder={defaultColor}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (val === "" || /^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
onChange(val || undefined)
|
||||
}
|
||||
}}
|
||||
disabled={disabled}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ColorPresetButtons({
|
||||
presets,
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
presets: typeof BG_PRESETS
|
||||
value?: string
|
||||
onChange: (color: string) => void
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{presets.map((preset) => (
|
||||
<button
|
||||
key={preset.color}
|
||||
type="button"
|
||||
onClick={() => onChange(preset.color)}
|
||||
disabled={disabled}
|
||||
className={`flex items-center gap-1.5 px-2 py-1 rounded-md border text-[10px] transition-colors ${
|
||||
value === preset.color
|
||||
? 'border-[var(--brand-pink)]'
|
||||
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
|
||||
}`}
|
||||
style={{ backgroundColor: 'var(--secondary)' }}
|
||||
title={preset.label}
|
||||
>
|
||||
<span
|
||||
className="w-3 h-3 rounded-sm border shrink-0"
|
||||
style={{
|
||||
backgroundColor: preset.color,
|
||||
borderColor: preset.color === "#000000" ? 'var(--card-border)' : preset.color,
|
||||
}}
|
||||
/>
|
||||
<span style={{ color: 'var(--text-muted)' }}>{preset.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BgModeToggle({
|
||||
mode,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
mode: BgMode
|
||||
onChange: (mode: BgMode) => void
|
||||
disabled?: boolean
|
||||
}) {
|
||||
const options: { value: BgMode; label: string; icon: React.ReactNode }[] = [
|
||||
{ value: "default", label: "Default", icon: null },
|
||||
{ value: "image", label: "Image", icon: <ImageIcon className="w-3 h-3" /> },
|
||||
{ value: "solid", label: "Color", icon: <Paintbrush className="w-3 h-3" /> },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex rounded-md border overflow-hidden" style={{ borderColor: 'var(--card-border)' }}>
|
||||
{options.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => onChange(opt.value)}
|
||||
disabled={disabled}
|
||||
className={`flex items-center gap-1 px-2.5 py-1 text-[10px] font-medium transition-colors ${
|
||||
mode === opt.value ? 'text-white' : ''
|
||||
}`}
|
||||
style={{
|
||||
backgroundColor: mode === opt.value ? 'var(--brand-pink)' : 'var(--secondary)',
|
||||
color: mode === opt.value ? 'white' : 'var(--text-muted)',
|
||||
}}
|
||||
>
|
||||
{opt.icon}
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CustomizeStep({
|
||||
artist,
|
||||
title,
|
||||
@@ -43,7 +201,6 @@ export function CustomizeStep({
|
||||
onDisplayArtistChange,
|
||||
onDisplayTitleChange,
|
||||
isPrivate,
|
||||
onPrivateChange,
|
||||
karaokeBackground,
|
||||
onKaraokeBackgroundChange,
|
||||
introBackground,
|
||||
@@ -55,13 +212,22 @@ export function CustomizeStep({
|
||||
isSubmitting,
|
||||
disabled,
|
||||
}: CustomizeStepProps) {
|
||||
// The displayed artist/title on the title card
|
||||
const previewArtist = displayArtist.trim() || artist
|
||||
const previewTitle = displayTitle.trim() || title
|
||||
|
||||
// Background mode state (private only)
|
||||
const [karaokeBgMode, setKaraokeBgMode] = useState<BgMode>(
|
||||
karaokeBackground ? "image" : "default"
|
||||
)
|
||||
const [introBgMode, setIntroBgMode] = useState<BgMode>(
|
||||
introBackground ? "image" : "default"
|
||||
)
|
||||
const [karaokeSolidColor, setKaraokeSolidColor] = useState("#000000")
|
||||
const [introSolidColor, setIntroSolidColor] = useState("#000000")
|
||||
|
||||
// Create stable object URLs for previews and revoke on cleanup
|
||||
const prevKaraokeBlobUrl = useRef<string>()
|
||||
const prevIntroBlobUrl = useRef<string>()
|
||||
const prevKaraokeBlobUrl = useRef<string | undefined>(undefined)
|
||||
const prevIntroBlobUrl = useRef<string | undefined>(undefined)
|
||||
|
||||
const karaokeBackgroundUrl = useMemo(
|
||||
() => karaokeBackground ? URL.createObjectURL(karaokeBackground) : undefined,
|
||||
@@ -88,6 +254,129 @@ export function CustomizeStep({
|
||||
return () => { if (introBackgroundUrl) URL.revokeObjectURL(introBackgroundUrl) }
|
||||
}, [introBackgroundUrl])
|
||||
|
||||
// When switching background modes, update the file state accordingly
|
||||
function handleKaraokeBgModeChange(mode: BgMode) {
|
||||
setKaraokeBgMode(mode)
|
||||
if (mode === "default" || mode === "solid") {
|
||||
onKaraokeBackgroundChange(null)
|
||||
}
|
||||
if (mode === "solid") {
|
||||
// Generate solid color blob
|
||||
generateSolidColorBlob(karaokeSolidColor).then(onKaraokeBackgroundChange)
|
||||
}
|
||||
}
|
||||
|
||||
function handleIntroBgModeChange(mode: BgMode) {
|
||||
setIntroBgMode(mode)
|
||||
if (mode === "default" || mode === "solid") {
|
||||
onIntroBackgroundChange(null)
|
||||
}
|
||||
if (mode === "solid") {
|
||||
generateSolidColorBlob(introSolidColor).then(onIntroBackgroundChange)
|
||||
}
|
||||
}
|
||||
|
||||
function handleKaraokeSolidColorChange(color: string) {
|
||||
setKaraokeSolidColor(color)
|
||||
generateSolidColorBlob(color).then(onKaraokeBackgroundChange)
|
||||
}
|
||||
|
||||
function handleIntroSolidColorChange(color: string) {
|
||||
setIntroSolidColor(color)
|
||||
generateSolidColorBlob(color).then(onIntroBackgroundChange)
|
||||
}
|
||||
|
||||
// === PUBLIC MODE: Simple layout ===
|
||||
if (!isPrivate) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Customize & Create
|
||||
</h2>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Confirm the artist and title for your title card.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
disabled={disabled || isSubmitting}
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Title card preview */}
|
||||
<div className="mx-auto w-full sm:w-2/3">
|
||||
<TitleCardPreview
|
||||
artist={previewArtist}
|
||||
title={previewTitle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Display override fields */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="guided-display-artist" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Card Artist
|
||||
{!displayArtist.trim() && artist.trim() && (
|
||||
<span className="ml-1 opacity-50">(same as above)</span>
|
||||
)}
|
||||
</Label>
|
||||
<Input
|
||||
id="guided-display-artist"
|
||||
placeholder={artist || "Artist on title card"}
|
||||
value={displayArtist}
|
||||
onChange={(e) => onDisplayArtistChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="guided-display-title" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Card Title
|
||||
{!displayTitle.trim() && title.trim() && (
|
||||
<span className="ml-1 opacity-50">(same as above)</span>
|
||||
)}
|
||||
</Label>
|
||||
<Input
|
||||
id="guided-display-title"
|
||||
placeholder={title || "Title on title card"}
|
||||
value={displayTitle}
|
||||
onChange={(e) => onDisplayTitleChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
These default to your search values. Override for soundtracks, covers, or alternate formatting.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shadow-[0_0_15px_rgba(255,122,204,0.3)] hover:shadow-[0_0_20px_rgba(255,122,204,0.5)] h-11 text-base"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
"Create Karaoke Video"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// === PRIVATE MODE: Full customization ===
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -96,7 +385,7 @@ export function CustomizeStep({
|
||||
Customize & Create
|
||||
</h2>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Preview your title card and confirm your settings.
|
||||
Customize your private video's appearance.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
@@ -111,20 +400,6 @@ export function CustomizeStep({
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Title card preview - half width, centered */}
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs" style={{ color: 'var(--text-muted)' }}>Title Card Preview</Label>
|
||||
<div className="mx-auto w-full sm:w-1/2">
|
||||
<TitleCardPreview
|
||||
artist={previewArtist}
|
||||
title={previewTitle}
|
||||
customBackgroundUrl={introBackgroundUrl}
|
||||
titleColor={colorOverrides.title_color}
|
||||
artistColor={colorOverrides.artist_color}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Display override fields */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
@@ -164,137 +439,197 @@ export function CustomizeStep({
|
||||
These default to your search values. Override for soundtracks, covers, or alternate formatting.
|
||||
</p>
|
||||
|
||||
{/* Privacy toggle */}
|
||||
<div className="space-y-2 pt-2 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="guided-private"
|
||||
checked={isPrivate}
|
||||
onChange={(e) => onPrivateChange(e.target.checked)}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="guided-private" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (no YouTube upload)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
</p>
|
||||
</div>
|
||||
{/* Custom Video Style section */}
|
||||
<div
|
||||
className="space-y-4 rounded-lg border p-4"
|
||||
style={{ borderColor: 'var(--card-border)', backgroundColor: 'rgba(255,255,255,0.02)' }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Palette className="w-4 h-4" style={{ color: 'var(--brand-pink)' }} />
|
||||
<h3 className="text-sm font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Custom Video Style
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Custom Video Style section - only shown for private delivery */}
|
||||
{isPrivate && (
|
||||
<div
|
||||
className="space-y-4 rounded-lg border p-4"
|
||||
style={{ borderColor: 'var(--card-border)', backgroundColor: 'rgba(255,255,255,0.02)' }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Palette className="w-4 h-4" style={{ color: 'var(--brand-pink)' }} />
|
||||
<h3 className="text-sm font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Custom Video Style
|
||||
</h3>
|
||||
</div>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Upload custom backgrounds and choose colors for your branded karaoke video.
|
||||
</p>
|
||||
{/* Side-by-side preview canvases */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
{/* Title Card Preview + Controls */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-medium" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Card
|
||||
</Label>
|
||||
<BgModeToggle
|
||||
mode={introBgMode}
|
||||
onChange={handleIntroBgModeChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Karaoke Background */}
|
||||
<div className="space-y-2">
|
||||
<ImageUploadField
|
||||
label="Karaoke Background"
|
||||
description="Replaces the starfield behind lyrics during the song."
|
||||
file={karaokeBackground}
|
||||
onChange={onKaraokeBackgroundChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
<TitleCardPreview
|
||||
artist={previewArtist}
|
||||
title={previewTitle}
|
||||
customBackgroundUrl={introBackgroundUrl}
|
||||
backgroundColor={introBgMode === "solid" ? introSolidColor : undefined}
|
||||
titleColor={colorOverrides.title_color}
|
||||
artistColor={colorOverrides.artist_color}
|
||||
/>
|
||||
{karaokeBackgroundUrl && (
|
||||
<div className="mx-auto w-full sm:w-2/3">
|
||||
<KaraokeBackgroundPreview backgroundUrl={karaokeBackgroundUrl} />
|
||||
|
||||
{introBgMode === "image" && (
|
||||
<ImageUploadField
|
||||
label=""
|
||||
description="PNG or JPG background for the title card."
|
||||
file={introBackground}
|
||||
onChange={onIntroBackgroundChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
hidePreview
|
||||
/>
|
||||
)}
|
||||
|
||||
{introBgMode === "solid" && (
|
||||
<div className="space-y-2">
|
||||
<ColorPresetButtons
|
||||
presets={BG_PRESETS}
|
||||
value={introSolidColor}
|
||||
onChange={handleIntroSolidColorChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={introSolidColor}
|
||||
onChange={(e) => handleIntroSolidColorChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={introSolidColor}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (/^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
handleIntroSolidColorChange(val)
|
||||
}
|
||||
}}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Title card text colors */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<ColorPickerField
|
||||
id="artist-color"
|
||||
label="Artist Color"
|
||||
value={colorOverrides.artist_color}
|
||||
defaultColor="#ffdf6b"
|
||||
onChange={(val) => onColorOverridesChange({ ...colorOverrides, artist_color: val })}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
<ColorPickerField
|
||||
id="title-color"
|
||||
label="Title Color"
|
||||
value={colorOverrides.title_color}
|
||||
defaultColor="#ffffff"
|
||||
onChange={(val) => onColorOverridesChange({ ...colorOverrides, title_color: val })}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Title Card Background */}
|
||||
<div className="space-y-2">
|
||||
<ImageUploadField
|
||||
label="Title Card Background"
|
||||
description="Background image for the intro/title card shown before the song starts."
|
||||
file={introBackground}
|
||||
onChange={onIntroBackgroundChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
{/* Karaoke Preview + Controls */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-medium" style={{ color: 'var(--text-muted)' }}>
|
||||
Karaoke Video
|
||||
</Label>
|
||||
<BgModeToggle
|
||||
mode={karaokeBgMode}
|
||||
onChange={handleKaraokeBgModeChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<KaraokeBackgroundPreview
|
||||
backgroundUrl={karaokeBackgroundUrl}
|
||||
backgroundColor={karaokeBgMode === "solid" ? karaokeSolidColor : undefined}
|
||||
sungColor={colorOverrides.sung_lyrics_color}
|
||||
unsungColor={colorOverrides.unsung_lyrics_color}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Color overrides */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="artist-color" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Artist Color
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
id="artist-color"
|
||||
value={colorOverrides.artist_color || "#ffdf6b"}
|
||||
onChange={(e) => onColorOverridesChange({ ...colorOverrides, artist_color: e.target.value })}
|
||||
{karaokeBgMode === "image" && (
|
||||
<ImageUploadField
|
||||
label=""
|
||||
description="PNG or JPG background behind lyrics during the song."
|
||||
file={karaokeBackground}
|
||||
onChange={onKaraokeBackgroundChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
hidePreview
|
||||
/>
|
||||
)}
|
||||
|
||||
{karaokeBgMode === "solid" && (
|
||||
<div className="space-y-2">
|
||||
<ColorPresetButtons
|
||||
presets={BG_PRESETS}
|
||||
value={karaokeSolidColor}
|
||||
onChange={handleKaraokeSolidColorChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={colorOverrides.artist_color || ""}
|
||||
placeholder="#ffdf6b"
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (val === "" || /^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
onColorOverridesChange({ ...colorOverrides, artist_color: val || undefined })
|
||||
}
|
||||
}}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="title-color" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Color
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
id="title-color"
|
||||
value={colorOverrides.title_color || "#ffffff"}
|
||||
onChange={(e) => onColorOverridesChange({ ...colorOverrides, title_color: e.target.value })}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={colorOverrides.title_color || ""}
|
||||
placeholder="#ffffff"
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (val === "" || /^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
onColorOverridesChange({ ...colorOverrides, title_color: val || undefined })
|
||||
}
|
||||
}}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={karaokeSolidColor}
|
||||
onChange={(e) => handleKaraokeSolidColorChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={karaokeSolidColor}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (/^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
handleKaraokeSolidColorChange(val)
|
||||
}
|
||||
}}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lyrics colors */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<ColorPickerField
|
||||
id="sung-lyrics-color"
|
||||
label="Highlight Color"
|
||||
value={colorOverrides.sung_lyrics_color}
|
||||
defaultColor="#7070F7"
|
||||
onChange={(val) => onColorOverridesChange({ ...colorOverrides, sung_lyrics_color: val })}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
<ColorPickerField
|
||||
id="unsung-lyrics-color"
|
||||
label="Lyrics Color"
|
||||
value={colorOverrides.unsung_lyrics_color}
|
||||
defaultColor="#ffffff"
|
||||
onChange={(val) => onColorOverridesChange({ ...colorOverrides, unsung_lyrics_color: val })}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
Leave blank to use default Nomad theme colors.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
Leave colors blank to use default Nomad theme. Previews are approximate — final rendering may differ slightly.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Create button */}
|
||||
<Button
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"use client"
|
||||
|
||||
import { ArrowLeft, Globe, Lock, ExternalLink, Sparkles } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
interface VisibilityStepProps {
|
||||
isPrivate: boolean
|
||||
onPrivateChange: (value: boolean) => void
|
||||
onNext: () => void
|
||||
onBack: () => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function VisibilityStep({
|
||||
isPrivate,
|
||||
onPrivateChange,
|
||||
onNext,
|
||||
onBack,
|
||||
disabled,
|
||||
}: VisibilityStepProps) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
|
||||
How should your video be shared?
|
||||
</h2>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Choose how your finished karaoke video will be delivered.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
disabled={disabled}
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Published option */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPrivateChange(false)}
|
||||
disabled={disabled}
|
||||
className={`w-full text-left rounded-lg border-2 p-4 transition-all ${
|
||||
!isPrivate
|
||||
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
|
||||
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
|
||||
}`}
|
||||
style={{ backgroundColor: !isPrivate ? 'rgba(255,122,204,0.05)' : 'transparent' }}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Radio circle */}
|
||||
<div
|
||||
className={`mt-0.5 w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-colors ${
|
||||
!isPrivate ? 'border-[var(--brand-pink)]' : 'border-[var(--text-muted)]'
|
||||
}`}
|
||||
>
|
||||
{!isPrivate && (
|
||||
<div className="w-2.5 h-2.5 rounded-full bg-[var(--brand-pink)]" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="w-4 h-4" style={{ color: !isPrivate ? 'var(--brand-pink)' : 'var(--text-muted)' }} />
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Published
|
||||
</span>
|
||||
<span
|
||||
className="text-[10px] px-1.5 py-0.5 rounded-full font-medium"
|
||||
style={{ backgroundColor: 'rgba(255,122,204,0.15)', color: 'var(--brand-pink)' }}
|
||||
>
|
||||
Recommended
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
<p>Your karaoke video will be <span className="font-semibold" style={{ color: '#f59e0b' }}>shared with the world</span>:</p>
|
||||
|
||||
<ul className="space-y-2 ml-1">
|
||||
<li className="flex items-start gap-2">
|
||||
<Sparkles className="w-3.5 h-3.5 mt-0.5 shrink-0" style={{ color: 'var(--brand-pink)' }} />
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Uploaded to YouTube</strong> on the{" "}
|
||||
<a
|
||||
href="https://www.youtube.com/@nomadkaraoke/videos"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-0.5 underline"
|
||||
style={{ color: 'var(--brand-pink)' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Nomad Karaoke channel
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
{" "}— the easiest way for you (and anyone else) to sing this song anytime
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<Sparkles className="w-3.5 h-3.5 mt-0.5 shrink-0" style={{ color: 'var(--brand-pink)' }} />
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Shared with karaoke venues</strong> via Google Drive — your song will be available to sing at bars and venues around the world
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<Sparkles className="w-3.5 h-3.5 mt-0.5 shrink-0" style={{ color: 'var(--brand-pink)' }} />
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Source files delivered to you</strong> via Dropbox — all stems, highest quality formats, ready to download
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div
|
||||
className="rounded-md p-2.5 mt-1 text-xs"
|
||||
style={{ backgroundColor: 'rgba(255,122,204,0.08)', color: 'var(--text)' }}
|
||||
>
|
||||
By publishing, you're helping other fans of this song discover and enjoy it at karaoke nights everywhere. Share the joy!
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Private option */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPrivateChange(true)}
|
||||
disabled={disabled}
|
||||
className={`w-full text-left rounded-lg border-2 p-4 transition-all ${
|
||||
isPrivate
|
||||
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
|
||||
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
|
||||
}`}
|
||||
style={{ backgroundColor: isPrivate ? 'rgba(255,122,204,0.05)' : 'transparent' }}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Radio circle */}
|
||||
<div
|
||||
className={`mt-0.5 w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-colors ${
|
||||
isPrivate ? 'border-[var(--brand-pink)]' : 'border-[var(--text-muted)]'
|
||||
}`}
|
||||
>
|
||||
{isPrivate && (
|
||||
<div className="w-2.5 h-2.5 rounded-full bg-[var(--brand-pink)]" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Lock className="w-4 h-4" style={{ color: isPrivate ? 'var(--brand-pink)' : 'var(--text-muted)' }} />
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Private
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
<p>Your karaoke video stays just with you:</p>
|
||||
|
||||
<ul className="space-y-2 ml-1">
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="w-3.5 h-3.5 mt-0.5 shrink-0 flex items-center justify-center text-[10px]">•</span>
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Delivered via Dropbox only</strong> — no YouTube upload, no Google Drive sharing. Download and use however you see fit.
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="w-3.5 h-3.5 mt-0.5 shrink-0 flex items-center justify-center text-[10px]">•</span>
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Venue use is up to you</strong> — if you want to perform this track at a venue, you'll need to provide the files to the host yourself.
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="w-3.5 h-3.5 mt-0.5 shrink-0 flex items-center justify-center text-[10px]">•</span>
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>YouTube self-upload</strong> — you can upload to your own channel, but monetization is unlikely as song copyrights are typically held by record labels.
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="w-3.5 h-3.5 mt-0.5 shrink-0 flex items-center justify-center text-[10px]">•</span>
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Custom styling available</strong> — choose your own background images, colors, and text styles on the next step.
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Continue button */}
|
||||
<Button
|
||||
onClick={onNext}
|
||||
disabled={disabled}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shadow-[0_0_15px_rgba(255,122,204,0.3)] hover:shadow-[0_0_20px_rgba(255,122,204,0.5)] h-11 text-base"
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo, memo } from 'react'
|
||||
import { useState, useEffect, useCallback, useMemo, useRef, memo } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Video, Check, CheckCircle2 } from 'lucide-react'
|
||||
@@ -20,7 +20,8 @@ import {
|
||||
ModalContent,
|
||||
} from '@/lib/lyrics-review/types'
|
||||
import type { EditLog, EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
|
||||
import type { InstrumentalSelectionType } from '@/lib/api'
|
||||
import type { InstrumentalSelectionType, LyricsReviewApiClient } from '@/lib/api'
|
||||
import { lyricsReviewApi } from '@/lib/api'
|
||||
import { cn } from '@/lib/utils'
|
||||
import ReferenceView from './ReferenceView'
|
||||
import TranscriptionView from './TranscriptionView'
|
||||
@@ -47,6 +48,8 @@ import {
|
||||
getModalState,
|
||||
} from '@/lib/lyrics-review/utils/keyboardHandlers'
|
||||
import { createEditLog, addEditEntry, attachFeedback } from '@/lib/lyrics-review/utils/editLog'
|
||||
import { useReviewSessionAutoSave } from '@/hooks/use-review-session-autosave'
|
||||
import SessionRestoreDialog from './SessionRestoreDialog'
|
||||
import Header from './Header'
|
||||
import GapNavigator from './GapNavigator'
|
||||
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
|
||||
@@ -76,6 +79,11 @@ interface ApiClient {
|
||||
}>
|
||||
getPreviewVideoUrl: (hash: string) => string
|
||||
completeReview: () => Promise<{ status: string; job_status: string; message: string }>
|
||||
// Review session methods (optional - available in cloud mode)
|
||||
saveReviewSession?: LyricsReviewApiClient['saveReviewSession']
|
||||
listReviewSessions?: LyricsReviewApiClient['listReviewSessions']
|
||||
getReviewSession?: LyricsReviewApiClient['getReviewSession']
|
||||
deleteReviewSession?: LyricsReviewApiClient['deleteReviewSession']
|
||||
}
|
||||
|
||||
export interface LyricsAnalyzerProps {
|
||||
@@ -87,6 +95,7 @@ export interface LyricsAnalyzerProps {
|
||||
audioHash: string
|
||||
isLocalMode?: boolean
|
||||
jobId?: string
|
||||
hasExistingInstrumental?: boolean
|
||||
}
|
||||
|
||||
export default function LyricsAnalyzer({
|
||||
@@ -97,6 +106,7 @@ export default function LyricsAnalyzer({
|
||||
audioHash,
|
||||
isLocalMode = false,
|
||||
jobId,
|
||||
hasExistingInstrumental = false,
|
||||
}: LyricsAnalyzerProps) {
|
||||
const router = useRouter()
|
||||
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768
|
||||
@@ -147,6 +157,11 @@ export default function LyricsAnalyzer({
|
||||
// Stats panel visibility
|
||||
const [statsVisible, setStatsVisible] = useState(false)
|
||||
|
||||
// Session restore state
|
||||
const [sessionRestoreOpen, setSessionRestoreOpen] = useState(false)
|
||||
const [savedSessions, setSavedSessions] = useState<import('@/lib/api').ReviewSession[]>([])
|
||||
const [sessionsLoading, setSessionsLoading] = useState(false)
|
||||
|
||||
// Advanced mode for transcription view (Simple/Advanced toggle)
|
||||
const [advancedMode, setAdvancedMode] = useState(() => {
|
||||
if (typeof window === 'undefined') return false
|
||||
@@ -194,22 +209,86 @@ export default function LyricsAnalyzer({
|
||||
setHistoryIndex(0)
|
||||
}, [initialData])
|
||||
|
||||
// Load saved data
|
||||
// Load saved sessions on mount - check server first, fall back to localStorage
|
||||
useEffect(() => {
|
||||
const savedData = loadSavedData(initialData)
|
||||
if (savedData && typeof window !== 'undefined' && window.confirm('Found saved progress for this song. Would you like to restore it?')) {
|
||||
setHistory([savedData])
|
||||
setHistoryIndex(0)
|
||||
if (isReadOnly || !apiClient?.listReviewSessions) {
|
||||
// Local mode or read-only: use localStorage fallback
|
||||
const savedData = loadSavedData(initialData)
|
||||
if (savedData && typeof window !== 'undefined' && window.confirm('Found saved progress for this song. Would you like to restore it?')) {
|
||||
setHistory([savedData])
|
||||
setHistoryIndex(0)
|
||||
}
|
||||
return
|
||||
}
|
||||
}, [initialData])
|
||||
|
||||
// Save data
|
||||
// Cloud mode: check for server-side sessions
|
||||
let cancelled = false
|
||||
setSessionsLoading(true)
|
||||
apiClient.listReviewSessions().then(result => {
|
||||
if (cancelled) return
|
||||
setSessionsLoading(false)
|
||||
if (result.sessions.length > 0) {
|
||||
setSavedSessions(result.sessions)
|
||||
setSessionRestoreOpen(true)
|
||||
} else {
|
||||
// Fall back to localStorage if no server sessions
|
||||
const savedData = loadSavedData(initialData)
|
||||
if (savedData && typeof window !== 'undefined' && window.confirm('Found saved progress for this song. Would you like to restore it?')) {
|
||||
setHistory([savedData])
|
||||
setHistoryIndex(0)
|
||||
}
|
||||
}
|
||||
}).catch(() => {
|
||||
if (cancelled) return
|
||||
setSessionsLoading(false)
|
||||
// Fall back to localStorage on error
|
||||
const savedData = loadSavedData(initialData)
|
||||
if (savedData && typeof window !== 'undefined' && window.confirm('Found saved progress for this song. Would you like to restore it?')) {
|
||||
setHistory([savedData])
|
||||
setHistoryIndex(0)
|
||||
}
|
||||
})
|
||||
|
||||
return () => { cancelled = true }
|
||||
}, [initialData, isReadOnly]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Handler for restoring a session from the dialog
|
||||
const handleSessionRestore = useCallback((correctionData: CorrectionData) => {
|
||||
setHistory([correctionData])
|
||||
setHistoryIndex(0)
|
||||
}, [])
|
||||
|
||||
// Handler to open session browser from toolbar
|
||||
const handleOpenSessionBrowser = useCallback(async () => {
|
||||
if (!apiClient?.listReviewSessions) return
|
||||
setSessionsLoading(true)
|
||||
try {
|
||||
const result = await apiClient.listReviewSessions()
|
||||
setSavedSessions(result.sessions)
|
||||
} catch {
|
||||
setSavedSessions([])
|
||||
}
|
||||
setSessionsLoading(false)
|
||||
setSessionRestoreOpen(true)
|
||||
}, [apiClient])
|
||||
|
||||
// Save data (localStorage - instant crash recovery)
|
||||
useEffect(() => {
|
||||
if (!isReadOnly) {
|
||||
saveData(data, initialData)
|
||||
}
|
||||
}, [data, isReadOnly, initialData])
|
||||
|
||||
// Server-side session auto-save (periodic backup)
|
||||
const { saveSession } = useReviewSessionAutoSave({
|
||||
jobId: jobId ?? '',
|
||||
data,
|
||||
initialData,
|
||||
historyLength: history.length,
|
||||
isReadOnly: isReadOnly || !apiClient?.saveReviewSession,
|
||||
apiClient: apiClient as LyricsReviewApiClient,
|
||||
})
|
||||
|
||||
// Flash handler (defined early so gap navigation can use it)
|
||||
const handleFlash = useCallback((type: FlashType, info?: HighlightInfo) => {
|
||||
setFlashingType(null)
|
||||
@@ -763,8 +842,10 @@ export default function LyricsAnalyzer({
|
||||
if (typeof window !== 'undefined' && window.isAudioPlaying && window.toggleAudioPlayback) {
|
||||
window.toggleAudioPlayback()
|
||||
}
|
||||
// Trigger server-side session save on preview (signals completion milestone)
|
||||
saveSession('preview')
|
||||
setIsReviewModalOpen(true)
|
||||
}, [])
|
||||
}, [saveSession])
|
||||
|
||||
// Submit to server (save corrections, don't complete review yet)
|
||||
const handleSubmitToServer = useCallback(async () => {
|
||||
@@ -791,8 +872,21 @@ export default function LyricsAnalyzer({
|
||||
setIsReviewModalOpen(false)
|
||||
setIsSubmitting(false)
|
||||
|
||||
// 4. Navigate to instrumental review
|
||||
if (isLocalMode) {
|
||||
// 4. Navigate to instrumental review (or skip if existing instrumental uploaded)
|
||||
if (hasExistingInstrumental && jobId) {
|
||||
// Job has an instrumental uploaded at creation time — skip instrumental review
|
||||
// Submit with "custom" selection (maps to the uploaded instrumental)
|
||||
toast.success('Lyrics saved! Using uploaded instrumental, generating video...')
|
||||
try {
|
||||
const correctionData = await lyricsReviewApi.getCorrectionData(jobId)
|
||||
await lyricsReviewApi.completeReview(jobId, correctionData, 'custom')
|
||||
setShowSuccess(true)
|
||||
setCountdown(3)
|
||||
} catch (err) {
|
||||
console.error('Failed to complete review with uploaded instrumental:', err)
|
||||
toast.error('Failed to start video generation. Please try again.')
|
||||
}
|
||||
} else if (isLocalMode) {
|
||||
// Local mode: Show transition message, navigation handled by browser/server
|
||||
toast.success('Lyrics saved! Loading instrumental review...')
|
||||
setShowInstrumentalReview(true)
|
||||
@@ -811,7 +905,7 @@ export default function LyricsAnalyzer({
|
||||
toast.error('Failed to submit corrections. Please try again.')
|
||||
setIsSubmitting(false) // Reset on error so user can retry
|
||||
}
|
||||
}, [apiClient, data, timingOffsetMs, editLog, isLocalMode, jobId])
|
||||
}, [apiClient, data, timingOffsetMs, editLog, isLocalMode, jobId, hasExistingInstrumental])
|
||||
|
||||
// Play segment handler
|
||||
const handlePlaySegment = useCallback(
|
||||
@@ -1175,6 +1269,25 @@ export default function LyricsAnalyzer({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{apiClient?.saveReviewSession && (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => saveSession('manual')}
|
||||
disabled={history.length <= 1}
|
||||
>
|
||||
Save Progress
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleOpenSessionBrowser}
|
||||
>
|
||||
Session History
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<span className="text-sm text-muted-foreground">Lyrics look good?</span>
|
||||
<Button onClick={handleFinishReview} disabled={isReviewComplete}>
|
||||
{isReviewComplete ? 'Review Complete' : 'Preview Video'}
|
||||
@@ -1307,6 +1420,17 @@ export default function LyricsAnalyzer({
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{apiClient?.saveReviewSession && (
|
||||
<SessionRestoreDialog
|
||||
open={sessionRestoreOpen}
|
||||
onClose={() => setSessionRestoreOpen(false)}
|
||||
onRestore={handleSessionRestore}
|
||||
sessions={savedSessions}
|
||||
apiClient={apiClient as LyricsReviewApiClient}
|
||||
isLoading={sessionsLoading}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Loader2, Clock, Search, AlertTriangle } from 'lucide-react'
|
||||
import type { ReviewSession, ReviewSessionWithData, LyricsReviewApiClient } from '@/lib/api'
|
||||
import type { CorrectionData } from '@/lib/lyrics-review/types'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface SessionRestoreDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onRestore: (data: CorrectionData) => void
|
||||
sessions: ReviewSession[]
|
||||
apiClient: LyricsReviewApiClient
|
||||
currentAudioDuration?: number | null
|
||||
isLoading?: boolean
|
||||
}
|
||||
|
||||
function formatRelativeTime(dateStr: string | null): string {
|
||||
if (!dateStr) return 'Unknown'
|
||||
const date = new Date(dateStr)
|
||||
const now = new Date()
|
||||
const diffMs = now.getTime() - date.getTime()
|
||||
const diffMin = Math.floor(diffMs / 60000)
|
||||
const diffHr = Math.floor(diffMin / 60)
|
||||
const diffDay = Math.floor(diffHr / 24)
|
||||
|
||||
if (diffMin < 1) return 'Just now'
|
||||
if (diffMin < 60) return `${diffMin}m ago`
|
||||
if (diffHr < 24) return `${diffHr}h ago`
|
||||
if (diffDay < 7) return `${diffDay}d ago`
|
||||
return date.toLocaleDateString()
|
||||
}
|
||||
|
||||
function formatAbsoluteTime(dateStr: string | null): string {
|
||||
if (!dateStr) return ''
|
||||
return new Date(dateStr).toLocaleString()
|
||||
}
|
||||
|
||||
function TriggerBadge({ trigger }: { trigger: string }) {
|
||||
const colors: Record<string, string> = {
|
||||
auto: 'bg-gray-100 text-gray-600',
|
||||
preview: 'bg-blue-100 text-blue-700',
|
||||
manual: 'bg-green-100 text-green-700',
|
||||
}
|
||||
return (
|
||||
<span className={cn('px-1.5 py-0.5 rounded text-xs font-medium', colors[trigger] || colors.auto)}>
|
||||
{trigger}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function EditPreview({ session }: { session: ReviewSession }) {
|
||||
const { summary } = session
|
||||
const changedWords = summary?.changed_words || []
|
||||
|
||||
if (changedWords.length === 0) {
|
||||
return (
|
||||
<div className="text-sm text-muted-foreground italic p-4">
|
||||
No word-level changes recorded in this session.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2 p-2 overflow-y-auto max-h-[400px]">
|
||||
<div className="text-xs text-muted-foreground mb-2">
|
||||
{summary.corrections_made} change{summary.corrections_made !== 1 ? 's' : ''} across {summary.total_segments} segments
|
||||
</div>
|
||||
{changedWords.map((change, i) => (
|
||||
<div key={i} className="flex items-start gap-2 text-sm py-1 border-b border-border/50 last:border-0">
|
||||
<span className="text-muted-foreground text-xs min-w-[24px] text-right">
|
||||
S{change.segment_index + 1}
|
||||
</span>
|
||||
<span className="text-red-500 line-through">{change.original}</span>
|
||||
<span className="text-muted-foreground">→</span>
|
||||
<span className="text-green-600 font-medium">{change.corrected}</span>
|
||||
</div>
|
||||
))}
|
||||
{summary.corrections_made > changedWords.length && (
|
||||
<div className="text-xs text-muted-foreground pt-1">
|
||||
+{summary.corrections_made - changedWords.length} more changes
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function SessionRestoreDialog({
|
||||
open,
|
||||
onClose,
|
||||
onRestore,
|
||||
sessions,
|
||||
apiClient,
|
||||
currentAudioDuration,
|
||||
isLoading = false,
|
||||
}: SessionRestoreDialogProps) {
|
||||
const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null)
|
||||
const [isRestoring, setIsRestoring] = useState(false)
|
||||
const [searchMode, setSearchMode] = useState<'this-job' | 'all-jobs'>('this-job')
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [crossJobSessions, setCrossJobSessions] = useState<ReviewSession[]>([])
|
||||
const [isSearching, setIsSearching] = useState(false)
|
||||
const [durationWarning, setDurationWarning] = useState<{ source: number; current: number } | null>(null)
|
||||
|
||||
// Auto-select most recent session
|
||||
useEffect(() => {
|
||||
if (sessions.length > 0 && !selectedSessionId) {
|
||||
setSelectedSessionId(sessions[0].session_id)
|
||||
}
|
||||
}, [sessions, selectedSessionId])
|
||||
|
||||
const displayedSessions = searchMode === 'this-job' ? sessions : crossJobSessions
|
||||
|
||||
const selectedSession = displayedSessions.find(s => s.session_id === selectedSessionId) || null
|
||||
|
||||
const handleSearch = useCallback(async () => {
|
||||
if (!searchQuery.trim()) return
|
||||
setIsSearching(true)
|
||||
try {
|
||||
// Use fetch directly for cross-job search (not part of job-scoped client)
|
||||
const { getAccessToken, API_BASE_URL } = await import('@/lib/api')
|
||||
const token = getAccessToken()
|
||||
const headers: HeadersInit = {}
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`
|
||||
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/review/sessions/search?q=${encodeURIComponent(searchQuery)}&limit=20`,
|
||||
{ headers }
|
||||
)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setCrossJobSessions(data.sessions || [])
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Cross-job search failed:', err)
|
||||
} finally {
|
||||
setIsSearching(false)
|
||||
}
|
||||
}, [searchQuery])
|
||||
|
||||
const handleRestore = useCallback(async () => {
|
||||
if (!selectedSession) return
|
||||
setIsRestoring(true)
|
||||
try {
|
||||
// Check duration mismatch for cross-job restores
|
||||
if (
|
||||
searchMode === 'all-jobs' &&
|
||||
currentAudioDuration &&
|
||||
selectedSession.audio_duration_seconds &&
|
||||
Math.abs(currentAudioDuration - selectedSession.audio_duration_seconds) > 2
|
||||
) {
|
||||
setDurationWarning({
|
||||
source: selectedSession.audio_duration_seconds,
|
||||
current: currentAudioDuration,
|
||||
})
|
||||
setIsRestoring(false)
|
||||
return
|
||||
}
|
||||
|
||||
await doRestore()
|
||||
} catch (err) {
|
||||
console.error('Failed to restore session:', err)
|
||||
setIsRestoring(false)
|
||||
}
|
||||
}, [selectedSession, searchMode, currentAudioDuration])
|
||||
|
||||
const doRestore = useCallback(async () => {
|
||||
if (!selectedSession) return
|
||||
setIsRestoring(true)
|
||||
try {
|
||||
// For cross-job sessions, we need to fetch from that job's endpoint
|
||||
const jobId = selectedSession.job_id
|
||||
const sessionId = selectedSession.session_id
|
||||
|
||||
let correctionData: CorrectionData | null = null
|
||||
|
||||
if (searchMode === 'this-job') {
|
||||
const full = await apiClient.getReviewSession(sessionId)
|
||||
correctionData = full.correction_data
|
||||
} else {
|
||||
// Cross-job: use direct fetch
|
||||
const { getAccessToken, API_BASE_URL } = await import('@/lib/api')
|
||||
const token = getAccessToken()
|
||||
const headers: HeadersInit = {}
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`
|
||||
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/review/${jobId}/sessions/${sessionId}`,
|
||||
{ headers }
|
||||
)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
correctionData = data.correction_data
|
||||
}
|
||||
}
|
||||
|
||||
if (correctionData) {
|
||||
onRestore(correctionData)
|
||||
onClose()
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to restore session:', err)
|
||||
} finally {
|
||||
setIsRestoring(false)
|
||||
setDurationWarning(null)
|
||||
}
|
||||
}, [selectedSession, searchMode, apiClient, onRestore, onClose])
|
||||
|
||||
const formatDuration = (seconds: number) => {
|
||||
const m = Math.floor(seconds / 60)
|
||||
const s = Math.round(seconds % 60)
|
||||
return `${m}:${s.toString().padStart(2, '0')}`
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open && !durationWarning} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent className="max-w-3xl max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Saved Review Sessions</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Tab switcher */}
|
||||
<div className="flex gap-2 border-b pb-2">
|
||||
<Button
|
||||
variant={searchMode === 'this-job' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setSearchMode('this-job')}
|
||||
>
|
||||
This Job ({sessions.length})
|
||||
</Button>
|
||||
<Button
|
||||
variant={searchMode === 'all-jobs' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setSearchMode('all-jobs')}
|
||||
>
|
||||
All Jobs
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Cross-job search */}
|
||||
{searchMode === 'all-jobs' && (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Search by artist, title, or job ID..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
|
||||
/>
|
||||
<Button onClick={handleSearch} disabled={isSearching} size="sm">
|
||||
{isSearching ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : displayedSessions.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
{searchMode === 'all-jobs' ? 'Search for sessions across all jobs' : 'No saved sessions found'}
|
||||
</div>
|
||||
) : (
|
||||
/* Split pane: session list (left) + preview (right) */
|
||||
<div className="flex gap-4 min-h-[300px] flex-1 overflow-hidden">
|
||||
{/* Session list */}
|
||||
<div className="w-1/2 overflow-y-auto border rounded-md">
|
||||
{displayedSessions.map((session) => (
|
||||
<button
|
||||
key={session.session_id}
|
||||
onClick={() => setSelectedSessionId(session.session_id)}
|
||||
className={cn(
|
||||
'w-full text-left px-3 py-2.5 border-b last:border-0 hover:bg-accent/50 transition-colors',
|
||||
selectedSessionId === session.session_id && 'bg-accent'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium" title={formatAbsoluteTime(session.updated_at)}>
|
||||
<Clock className="h-3 w-3 inline mr-1 opacity-50" />
|
||||
{formatRelativeTime(session.updated_at)}
|
||||
</span>
|
||||
<TriggerBadge trigger={session.trigger} />
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-0.5">
|
||||
{session.edit_count} edit{session.edit_count !== 1 ? 's' : ''}
|
||||
{searchMode === 'all-jobs' && session.artist && (
|
||||
<> · {session.artist} - {session.title}</>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Edit preview */}
|
||||
<div className="w-1/2 border rounded-md overflow-y-auto">
|
||||
{selectedSession ? (
|
||||
<EditPreview session={selectedSession} />
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground p-4 italic">
|
||||
Select a session to preview changes
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Start Fresh
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleRestore}
|
||||
disabled={!selectedSession || isRestoring}
|
||||
>
|
||||
{isRestoring && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Restore Selected
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Duration mismatch warning dialog */}
|
||||
<Dialog open={!!durationWarning} onOpenChange={() => setDurationWarning(null)}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-yellow-500" />
|
||||
Duration Mismatch
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
{durationWarning && (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The selected session is from a track with a different duration:
|
||||
</p>
|
||||
<div className="bg-muted rounded-md p-3 text-sm space-y-1">
|
||||
<div>This job: <strong>{formatDuration(durationWarning.current)}</strong> ({Math.round(durationWarning.current)}s)</div>
|
||||
<div>Source session: <strong>{formatDuration(durationWarning.source)}</strong> ({Math.round(durationWarning.source)}s)</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Timing alignment may not match. Word timestamps from the source session will be preserved as-is.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDurationWarning(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={doRestore} disabled={isRestoring}>
|
||||
{isRestoring && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Restore Anyway
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import SessionRestoreDialog from '../SessionRestoreDialog'
|
||||
import type { ReviewSession, LyricsReviewApiClient, ReviewSessionWithData } from '@/lib/api'
|
||||
|
||||
function makeSession(overrides: Partial<ReviewSession> = {}): ReviewSession {
|
||||
return {
|
||||
session_id: 'session-1',
|
||||
job_id: 'job-1',
|
||||
user_email: 'user@test.com',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
edit_count: 5,
|
||||
trigger: 'auto',
|
||||
audio_duration_seconds: 180,
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
summary: {
|
||||
total_segments: 10,
|
||||
total_words: 100,
|
||||
corrections_made: 3,
|
||||
changed_words: [
|
||||
{ original: 'hello', corrected: 'hallo', segment_index: 0 },
|
||||
{ original: 'world', corrected: 'werld', segment_index: 1 },
|
||||
],
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeMockApiClient(): LyricsReviewApiClient {
|
||||
return {
|
||||
submitCorrections: jest.fn(),
|
||||
submitAnnotations: jest.fn(),
|
||||
submitEditLog: jest.fn(),
|
||||
updateHandlers: jest.fn(),
|
||||
addLyrics: jest.fn(),
|
||||
getAudioUrl: jest.fn(),
|
||||
generatePreviewVideo: jest.fn(),
|
||||
getPreviewVideoUrl: jest.fn(),
|
||||
completeReview: jest.fn(),
|
||||
saveReviewSession: jest.fn(),
|
||||
listReviewSessions: jest.fn(),
|
||||
getReviewSession: jest.fn().mockResolvedValue({
|
||||
session_id: 'session-1',
|
||||
correction_data: { corrected_segments: [] },
|
||||
} as Partial<ReviewSessionWithData>),
|
||||
deleteReviewSession: jest.fn(),
|
||||
}
|
||||
}
|
||||
|
||||
describe('SessionRestoreDialog', () => {
|
||||
const defaultProps = {
|
||||
open: true,
|
||||
onClose: jest.fn(),
|
||||
onRestore: jest.fn(),
|
||||
sessions: [makeSession()],
|
||||
apiClient: makeMockApiClient(),
|
||||
currentAudioDuration: 180,
|
||||
}
|
||||
|
||||
it('renders dialog with title when open', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText('Saved Review Sessions')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render content when closed', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} open={false} />)
|
||||
expect(screen.queryByText('Saved Review Sessions')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows loading spinner when isLoading', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} isLoading={true} />)
|
||||
// Should not show session list
|
||||
expect(screen.queryByText('5 edits')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows empty state when no sessions', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} sessions={[]} />)
|
||||
expect(screen.getByText('No saved sessions found')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('displays session list with edit count', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText('5 edits')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows trigger badge', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText('auto')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows edit preview for selected session', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
// First session should be auto-selected
|
||||
expect(screen.getByText('hello')).toBeInTheDocument()
|
||||
expect(screen.getByText('hallo')).toBeInTheDocument()
|
||||
expect(screen.getByText('world')).toBeInTheDocument()
|
||||
expect(screen.getByText('werld')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows correction count in preview', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText(/3 changes? across 10 segments/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows "No word-level changes" when summary has no changed_words', () => {
|
||||
const session = makeSession({
|
||||
summary: { total_segments: 5, total_words: 50, corrections_made: 0, changed_words: [] },
|
||||
})
|
||||
render(<SessionRestoreDialog {...defaultProps} sessions={[session]} />)
|
||||
expect(screen.getByText('No word-level changes recorded in this session.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders multiple sessions in the list', () => {
|
||||
const sessions = [
|
||||
makeSession({ session_id: 's1', edit_count: 3, trigger: 'manual' }),
|
||||
makeSession({ session_id: 's2', edit_count: 10, trigger: 'preview' }),
|
||||
]
|
||||
render(<SessionRestoreDialog {...defaultProps} sessions={sessions} />)
|
||||
expect(screen.getByText('3 edits')).toBeInTheDocument()
|
||||
expect(screen.getByText('10 edits')).toBeInTheDocument()
|
||||
expect(screen.getByText('manual')).toBeInTheDocument()
|
||||
expect(screen.getByText('preview')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onRestore with correction data when Restore Selected is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const apiClient = makeMockApiClient()
|
||||
const onRestore = jest.fn()
|
||||
const correctionData = { corrected_segments: [{ id: 's1', text: 'test', words: [], start_time: 0, end_time: 1 }] }
|
||||
|
||||
;(apiClient.getReviewSession as jest.Mock).mockResolvedValue({
|
||||
session_id: 'session-1',
|
||||
correction_data: correctionData,
|
||||
})
|
||||
|
||||
render(
|
||||
<SessionRestoreDialog
|
||||
{...defaultProps}
|
||||
apiClient={apiClient}
|
||||
onRestore={onRestore}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(screen.getByText('Restore Selected'))
|
||||
|
||||
expect(apiClient.getReviewSession).toHaveBeenCalledWith('session-1')
|
||||
expect(onRestore).toHaveBeenCalledWith(correctionData)
|
||||
})
|
||||
|
||||
it('calls onClose when Start Fresh is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onClose = jest.fn()
|
||||
render(<SessionRestoreDialog {...defaultProps} onClose={onClose} />)
|
||||
|
||||
await user.click(screen.getByText('Start Fresh'))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows tab buttons for This Job and All Jobs', () => {
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
expect(screen.getByText(/This Job/)).toBeInTheDocument()
|
||||
expect(screen.getByText('All Jobs')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows session count in This Job tab', () => {
|
||||
const sessions = [makeSession({ session_id: 's1' }), makeSession({ session_id: 's2' })]
|
||||
render(<SessionRestoreDialog {...defaultProps} sessions={sessions} />)
|
||||
expect(screen.getByText('This Job (2)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows search input when All Jobs tab is selected', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
|
||||
await user.click(screen.getByText('All Jobs'))
|
||||
expect(screen.getByPlaceholderText('Search by artist, title, or job ID...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows artist and title for cross-job sessions', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
// Mock the global fetch for cross-job search
|
||||
const mockFetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
sessions: [
|
||||
makeSession({ session_id: 'cross-1', artist: 'Other Artist', title: 'Other Song', edit_count: 7 }),
|
||||
],
|
||||
}),
|
||||
})
|
||||
global.fetch = mockFetch
|
||||
|
||||
render(<SessionRestoreDialog {...defaultProps} />)
|
||||
|
||||
// Switch to All Jobs tab
|
||||
await user.click(screen.getByText('All Jobs'))
|
||||
|
||||
// Type search query and submit
|
||||
const input = screen.getByPlaceholderText('Search by artist, title, or job ID...')
|
||||
await user.type(input, 'Other Artist{Enter}')
|
||||
|
||||
// Wait for results
|
||||
expect(mockFetch).toHaveBeenCalled()
|
||||
|
||||
// Should show the cross-job session with artist info
|
||||
expect(await screen.findByText(/Other Artist/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,220 @@
|
||||
import { test, expect, Page } from "@playwright/test";
|
||||
import * as path from "path";
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
|
||||
/**
|
||||
* Tenant Portal Job Submission - Production E2E Test
|
||||
*
|
||||
* Tests the full tenant portal flow:
|
||||
* 1. Navigate to tenant portal with admin auth
|
||||
* 2. Verify tenant branding (logo, title, simplified form)
|
||||
* 3. Submit a track (mixed + instrumental audio)
|
||||
* 4. Wait for job processing
|
||||
* 5. Verify job metadata (is_private, tenant_id, brand_prefix)
|
||||
*
|
||||
* Run with:
|
||||
* KARAOKE_ADMIN_TOKEN=xxx npx playwright test e2e/production/tenant-job-submission.spec.ts \
|
||||
* --config=playwright.production.config.ts --reporter=list
|
||||
*
|
||||
* Environment variables:
|
||||
* KARAOKE_ADMIN_TOKEN - Admin token for authentication (required)
|
||||
* TENANT_PORTAL_URL - Override tenant portal URL (default: https://vocalstar.nomadkaraoke.com)
|
||||
*/
|
||||
|
||||
const TENANT_PORTAL_URL = process.env.TENANT_PORTAL_URL || "https://vocalstar.nomadkaraoke.com";
|
||||
const API_URL = "https://api.nomadkaraoke.com";
|
||||
const CONSUMER_PORTAL_URL = "https://gen.nomadkaraoke.com";
|
||||
|
||||
const TIMEOUTS = {
|
||||
action: 30_000,
|
||||
expect: 60_000,
|
||||
apiCall: 120_000,
|
||||
jobProcessing: 600_000,
|
||||
fullTest: 1_200_000, // 20 minutes
|
||||
};
|
||||
|
||||
function getAdminToken(): string | null {
|
||||
return process.env.KARAOKE_ADMIN_TOKEN || process.env.KARAOKE_ACCESS_TOKEN || null;
|
||||
}
|
||||
|
||||
async function authenticatePage(page: Page, token: string): Promise<void> {
|
||||
await page.addInitScript((t) => {
|
||||
localStorage.setItem("karaoke_access_token", t);
|
||||
}, token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a minimal WAV file for testing uploads.
|
||||
* Returns the path to the temporary file.
|
||||
*/
|
||||
function createTestAudioFile(name: string): string {
|
||||
const tmpDir = os.tmpdir();
|
||||
const filePath = path.join(tmpDir, name);
|
||||
|
||||
// Minimal WAV header (44 bytes) + 1 second of silence at 8kHz mono 8-bit
|
||||
const sampleRate = 8000;
|
||||
const numSamples = sampleRate; // 1 second
|
||||
const dataSize = numSamples;
|
||||
const fileSize = 36 + dataSize;
|
||||
|
||||
const buffer = Buffer.alloc(44 + dataSize);
|
||||
|
||||
// RIFF header
|
||||
buffer.write("RIFF", 0);
|
||||
buffer.writeUInt32LE(fileSize, 4);
|
||||
buffer.write("WAVE", 8);
|
||||
|
||||
// fmt chunk
|
||||
buffer.write("fmt ", 12);
|
||||
buffer.writeUInt32LE(16, 16); // chunk size
|
||||
buffer.writeUInt16LE(1, 20); // PCM format
|
||||
buffer.writeUInt16LE(1, 22); // mono
|
||||
buffer.writeUInt32LE(sampleRate, 24);
|
||||
buffer.writeUInt32LE(sampleRate, 28); // byte rate
|
||||
buffer.writeUInt16LE(1, 32); // block align
|
||||
buffer.writeUInt16LE(8, 34); // bits per sample
|
||||
|
||||
// data chunk
|
||||
buffer.write("data", 36);
|
||||
buffer.writeUInt32LE(dataSize, 40);
|
||||
// Silence: fill with 128 (center value for 8-bit PCM)
|
||||
buffer.fill(128, 44);
|
||||
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
async function getJobDetails(token: string, jobId: string): Promise<any> {
|
||||
const response = await fetch(`${API_URL}/api/jobs/${jobId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get job ${jobId}: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
test.describe("Tenant Portal Job Submission", () => {
|
||||
test.describe.configure({ retries: 0 });
|
||||
|
||||
let adminToken: string = "";
|
||||
let testAudioPath: string;
|
||||
let testInstrumentalPath: string;
|
||||
let createdJobId: string | null = null;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
const token = getAdminToken();
|
||||
if (token) {
|
||||
adminToken = token;
|
||||
}
|
||||
|
||||
// Create test audio files
|
||||
testAudioPath = createTestAudioFile("test-mixed-audio.wav");
|
||||
testInstrumentalPath = createTestAudioFile("test-instrumental.wav");
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
// Clean up temp files
|
||||
for (const f of [testAudioPath, testInstrumentalPath]) {
|
||||
if (f && fs.existsSync(f)) {
|
||||
fs.unlinkSync(f);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up test job if created
|
||||
if (createdJobId && adminToken) {
|
||||
try {
|
||||
await fetch(`${API_URL}/api/admin/jobs/${createdJobId}`, {
|
||||
method: "DELETE",
|
||||
headers: { "X-Admin-Token": adminToken },
|
||||
});
|
||||
console.log(`Cleaned up test job ${createdJobId}`);
|
||||
} catch {
|
||||
console.warn(`Failed to clean up test job ${createdJobId}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("Tenant portal shows simplified form, not consumer wizard", async ({ page }) => {
|
||||
test.skip(!adminToken, "KARAOKE_ADMIN_TOKEN not set");
|
||||
test.setTimeout(TIMEOUTS.expect);
|
||||
|
||||
await authenticatePage(page, adminToken);
|
||||
await page.goto(`${TENANT_PORTAL_URL}/app`, { waitUntil: "networkidle", timeout: TIMEOUTS.action });
|
||||
|
||||
// Should NOT show the consumer wizard step indicators
|
||||
await expect(page.getByText("Choose Audio")).not.toBeVisible({ timeout: 5_000 });
|
||||
|
||||
// Should show tenant-specific card title
|
||||
await expect(page.getByText("Submit Track")).toBeVisible({ timeout: TIMEOUTS.expect });
|
||||
await expect(page.getByText("Upload your mixed audio and instrumental")).toBeVisible();
|
||||
|
||||
// Should show 4 form fields
|
||||
await expect(page.getByLabel("Artist")).toBeVisible();
|
||||
await expect(page.getByLabel("Title")).toBeVisible();
|
||||
await expect(page.getByText("Mixed Audio")).toBeVisible();
|
||||
await expect(page.getByText("Instrumental Audio")).toBeVisible();
|
||||
});
|
||||
|
||||
test("Submit track through tenant portal", async ({ page }) => {
|
||||
test.skip(!adminToken, "KARAOKE_ADMIN_TOKEN not set");
|
||||
test.setTimeout(TIMEOUTS.fullTest);
|
||||
|
||||
await authenticatePage(page, adminToken);
|
||||
await page.goto(`${TENANT_PORTAL_URL}/app`, { waitUntil: "networkidle", timeout: TIMEOUTS.action });
|
||||
|
||||
// Fill form
|
||||
await page.getByLabel("Artist").fill("E2E Test Artist");
|
||||
await page.getByLabel("Title").fill("E2E Test Tenant Track");
|
||||
|
||||
// Upload mixed audio
|
||||
const mixedInput = page.locator("#tenant-mixed-audio");
|
||||
await mixedInput.setInputFiles(testAudioPath);
|
||||
|
||||
// Upload instrumental
|
||||
const instrumentalInput = page.locator("#tenant-instrumental-audio");
|
||||
await instrumentalInput.setInputFiles(testInstrumentalPath);
|
||||
|
||||
// Submit
|
||||
await page.getByRole("button", { name: /Submit Track/i }).click();
|
||||
|
||||
// Wait for success
|
||||
await expect(page.getByText("Track Submitted")).toBeVisible({ timeout: TIMEOUTS.apiCall });
|
||||
|
||||
// Extract job ID from success view
|
||||
const jobIdElement = page.locator('[data-testid="created-job-id"]');
|
||||
const jobIdText = await jobIdElement.textContent();
|
||||
const shortId = jobIdText?.replace("ID: ", "").trim();
|
||||
expect(shortId).toBeTruthy();
|
||||
if (shortId) createdJobId = shortId;
|
||||
console.log(`Created tenant job with short ID: ${shortId}`);
|
||||
|
||||
// Verify success timeline shows tenant-specific steps (no "Audio processing" step)
|
||||
await expect(page.getByText("Lyrics transcription")).toBeVisible();
|
||||
await expect(page.getByText("Review lyrics")).toBeVisible();
|
||||
await expect(page.getByText("Video delivered")).toBeVisible();
|
||||
|
||||
// The timeline should NOT mention "Audio processing" or "Download" (consumer flow terms)
|
||||
const bodyText = await page.locator("body").textContent();
|
||||
expect(bodyText).not.toContain("Audio processing");
|
||||
expect(bodyText).not.toContain("separate vocals");
|
||||
});
|
||||
|
||||
test("Consumer portal still works normally", async ({ page }) => {
|
||||
test.skip(!adminToken, "KARAOKE_ADMIN_TOKEN not set");
|
||||
test.setTimeout(TIMEOUTS.expect);
|
||||
|
||||
await authenticatePage(page, adminToken);
|
||||
await page.goto(`${CONSUMER_PORTAL_URL}/app`, { waitUntil: "networkidle", timeout: TIMEOUTS.action });
|
||||
|
||||
// Consumer portal should show the full wizard
|
||||
await expect(page.getByText("Create Karaoke Video")).toBeVisible({ timeout: TIMEOUTS.expect });
|
||||
await expect(page.getByText("Turn any song into a karaoke video")).toBeVisible();
|
||||
|
||||
// Should NOT show tenant-specific text
|
||||
const bodyText = await page.locator("body").textContent();
|
||||
expect(bodyText).not.toContain("Submit Track");
|
||||
expect(bodyText).not.toContain("Upload your mixed audio and instrumental");
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,22 @@ interface TenantConfigResponse {
|
||||
const API_BASE_URL = "https://api.nomadkaraoke.com"
|
||||
const CACHE_TTL_SECONDS = 300 // 5 minutes
|
||||
|
||||
/**
|
||||
* Compute a contrasting foreground color (black or white) for a given hex color.
|
||||
* Uses WCAG relative luminance to determine which provides better contrast.
|
||||
*/
|
||||
function getContrastColor(hexColor: string): string {
|
||||
const hex = hexColor.replace("#", "")
|
||||
const r = parseInt(hex.slice(0, 2), 16) / 255
|
||||
const g = parseInt(hex.slice(2, 4), 16) / 255
|
||||
const b = parseInt(hex.slice(4, 6), 16) / 255
|
||||
|
||||
const toLinear = (c: number) => (c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4))
|
||||
const luminance = 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b)
|
||||
|
||||
return luminance > 0.179 ? "#000000" : "#ffffff"
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract tenant ID from hostname.
|
||||
* Supports: {tenant}.nomadkaraoke.com and {tenant}.gen.nomadkaraoke.com
|
||||
@@ -150,6 +166,7 @@ export const onRequest: PagesFunction = async (context) => {
|
||||
const cssVars = [
|
||||
`--tenant-primary:${branding.primary_color}`,
|
||||
`--tenant-secondary:${branding.secondary_color}`,
|
||||
`--primary-foreground:${getContrastColor(branding.primary_color)}`,
|
||||
]
|
||||
if (branding.accent_color) {
|
||||
cssVars.push(`--tenant-accent:${branding.accent_color}`)
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { useReviewSessionAutoSave } from '../use-review-session-autosave'
|
||||
import type { CorrectionData } from '@/lib/lyrics-review/types'
|
||||
import type { LyricsReviewApiClient } from '@/lib/api'
|
||||
|
||||
// Minimal CorrectionData factory
|
||||
function makeCorrectionData(overrides: Partial<CorrectionData> = {}): CorrectionData {
|
||||
return {
|
||||
original_segments: [],
|
||||
reference_lyrics: {},
|
||||
anchor_sequences: [],
|
||||
gap_sequences: [],
|
||||
resized_segments: [],
|
||||
corrections_made: 0,
|
||||
confidence: 1,
|
||||
corrections: [],
|
||||
corrected_segments: [],
|
||||
metadata: {
|
||||
anchor_sequences_count: 0,
|
||||
gap_sequences_count: 0,
|
||||
total_words: 0,
|
||||
correction_ratio: 0,
|
||||
},
|
||||
correction_steps: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeSegment(words: string[]) {
|
||||
return {
|
||||
id: `seg-${Math.random()}`,
|
||||
text: words.join(' '),
|
||||
words: words.map((text) => ({
|
||||
id: `w-${Math.random()}`,
|
||||
text,
|
||||
start_time: 0,
|
||||
end_time: 1,
|
||||
confidence: 1,
|
||||
})),
|
||||
start_time: 0,
|
||||
end_time: 1,
|
||||
}
|
||||
}
|
||||
|
||||
function makeMockApiClient(overrides: Partial<LyricsReviewApiClient> = {}): LyricsReviewApiClient {
|
||||
return {
|
||||
submitCorrections: jest.fn(),
|
||||
submitAnnotations: jest.fn(),
|
||||
submitEditLog: jest.fn(),
|
||||
updateHandlers: jest.fn(),
|
||||
addLyrics: jest.fn(),
|
||||
getAudioUrl: jest.fn(),
|
||||
generatePreviewVideo: jest.fn(),
|
||||
getPreviewVideoUrl: jest.fn(),
|
||||
completeReview: jest.fn(),
|
||||
saveReviewSession: jest.fn().mockResolvedValue({ status: 'saved', session_id: 'test-session' }),
|
||||
listReviewSessions: jest.fn().mockResolvedValue({ sessions: [] }),
|
||||
getReviewSession: jest.fn(),
|
||||
deleteReviewSession: jest.fn(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('useReviewSessionAutoSave', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
it('does not save when historyLength <= 1 (no edits)', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 1,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('saves when historyLength > 1 and trigger is manual', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 5,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(1)
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
4, // historyLength - 1
|
||||
'manual',
|
||||
expect.objectContaining({
|
||||
total_segments: expect.any(Number),
|
||||
corrections_made: expect.any(Number),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('does not save again if historyLength has not changed since last save', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 3,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Second call with same historyLength should be skipped
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does not save in read-only mode (no interval set)', () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 5,
|
||||
isReadOnly: true,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
// Advance timer past 60s
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(120_000)
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('auto-saves on 60-second interval', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 5,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
// Advance to 60s
|
||||
await act(async () => {
|
||||
jest.advanceTimersByTime(60_000)
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(1)
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
4,
|
||||
'auto',
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
|
||||
it('handles save failure gracefully without throwing', async () => {
|
||||
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation()
|
||||
const apiClient = makeMockApiClient({
|
||||
saveReviewSession: jest.fn().mockRejectedValue(new Error('Network error')),
|
||||
})
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 3,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
expect(consoleWarn).toHaveBeenCalledWith(
|
||||
'Review session auto-save failed:',
|
||||
expect.any(Error)
|
||||
)
|
||||
consoleWarn.mockRestore()
|
||||
})
|
||||
|
||||
it('computes correct summary with word changes', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const initialData = makeCorrectionData({
|
||||
corrected_segments: [makeSegment(['hello', 'world', 'foo'])],
|
||||
})
|
||||
const currentData = makeCorrectionData({
|
||||
corrected_segments: [makeSegment(['hallo', 'world', 'bar'])],
|
||||
})
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: currentData,
|
||||
initialData,
|
||||
historyLength: 3,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
const summary = (apiClient.saveReviewSession as jest.Mock).mock.calls[0][3]
|
||||
expect(summary.total_segments).toBe(1)
|
||||
expect(summary.total_words).toBe(3)
|
||||
expect(summary.corrections_made).toBe(2)
|
||||
expect(summary.changed_words).toHaveLength(2)
|
||||
expect(summary.changed_words[0]).toEqual(
|
||||
expect.objectContaining({ original: 'hello', corrected: 'hallo', segment_index: 0 })
|
||||
)
|
||||
})
|
||||
|
||||
it('caps changed_words at 50', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
// Create segments with 60 different words
|
||||
const initialWords = Array.from({ length: 60 }, (_, i) => `word${i}`)
|
||||
const currentWords = Array.from({ length: 60 }, (_, i) => `changed${i}`)
|
||||
const initialData = makeCorrectionData({
|
||||
corrected_segments: [makeSegment(initialWords)],
|
||||
})
|
||||
const currentData = makeCorrectionData({
|
||||
corrected_segments: [makeSegment(currentWords)],
|
||||
})
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: currentData,
|
||||
initialData,
|
||||
historyLength: 2,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
const summary = (apiClient.saveReviewSession as jest.Mock).mock.calls[0][3]
|
||||
expect(summary.corrections_made).toBe(60)
|
||||
expect(summary.changed_words).toHaveLength(50) // Capped at 50
|
||||
})
|
||||
|
||||
it('saves with preview trigger', async () => {
|
||||
const apiClient = makeMockApiClient()
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 10,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('preview')
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
9,
|
||||
'preview',
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
|
||||
it('does not update lastBackupHistoryLength on non-saved/skipped status', async () => {
|
||||
const apiClient = makeMockApiClient({
|
||||
saveReviewSession: jest.fn().mockResolvedValue({ status: 'error' }),
|
||||
})
|
||||
const { result } = renderHook(() =>
|
||||
useReviewSessionAutoSave({
|
||||
jobId: 'job-1',
|
||||
data: makeCorrectionData(),
|
||||
initialData: makeCorrectionData(),
|
||||
historyLength: 5,
|
||||
isReadOnly: false,
|
||||
apiClient,
|
||||
})
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
// Should still try on second call since first didn't save
|
||||
await act(async () => {
|
||||
await result.current.saveSession('manual')
|
||||
})
|
||||
|
||||
expect(apiClient.saveReviewSession).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { api } from '@/lib/api'
|
||||
import { useTenant } from '@/lib/tenant'
|
||||
|
||||
// LocalStorage key for tracking prompt dismissal
|
||||
const PUSH_PROMPT_DISMISSED_KEY = 'karaoke_push_prompt_dismissed'
|
||||
@@ -164,6 +165,9 @@ export function usePushNotifications(): UsePushNotificationsReturn {
|
||||
const vapidPublicKeyRef = useRef<string | null>(null)
|
||||
const registrationRef = useRef<ServiceWorkerRegistration | null>(null)
|
||||
|
||||
// Get tenant context for scoping push subscriptions
|
||||
const { tenantId } = useTenant()
|
||||
|
||||
// Check browser support and initial state
|
||||
useEffect(() => {
|
||||
const checkSupport = async () => {
|
||||
@@ -272,9 +276,9 @@ export function usePushNotifications(): UsePushNotificationsReturn {
|
||||
})
|
||||
}
|
||||
|
||||
// Send subscription to backend
|
||||
// Send subscription to backend with tenant scope
|
||||
const { endpoint, keys } = subscriptionToApiFormat(subscription)
|
||||
await api.subscribePush(endpoint, keys, getDeviceName())
|
||||
await api.subscribePush(endpoint, keys, getDeviceName(), tenantId)
|
||||
|
||||
setIsSubscribed(true)
|
||||
return true
|
||||
@@ -283,7 +287,7 @@ export function usePushNotifications(): UsePushNotificationsReturn {
|
||||
setError(err instanceof Error ? err.message : 'Failed to subscribe')
|
||||
return false
|
||||
}
|
||||
}, [isSupported, isPushEnabled])
|
||||
}, [isSupported, isPushEnabled, tenantId])
|
||||
|
||||
/**
|
||||
* Unsubscribe from push notifications
|
||||
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user