mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 09:14:03 +09:00
Compare commits
No files matched your search
@@ -0,0 +1,109 @@
|
||||
# Plan: Admin Feedback Visibility
|
||||
|
||||
**Created:** 2026-03-23
|
||||
**Branch:** feat/sess-20260323-1454-feedback-email-debug
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
User feedback submissions are stored in Firestore (`user_feedback` collection) but are completely invisible to the admin. The admin panel only shows a boolean "Feedback Submitted: Yes/No" badge per user. This plan adds:
|
||||
|
||||
1. **Admin UI page** to browse and review all submitted feedback
|
||||
2. **Email notification** to admin@nomadkaraoke.com on each new submission
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Admin page at `/admin/feedback` listing all feedback with ratings, text, timestamps, and user info
|
||||
- [ ] Sortable by date (newest first by default) and filterable by search (email)
|
||||
- [ ] Star ratings rendered visually (not just numbers)
|
||||
- [ ] Email sent to admin@nomadkaraoke.com immediately when feedback is submitted
|
||||
- [ ] Email includes all feedback content (ratings, text fields, user email)
|
||||
- [ ] Test data filtering works (exclude_test toggle)
|
||||
- [ ] Sidebar navigation includes new "Feedback" item
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Admin API Endpoint
|
||||
Add `GET /api/admin/feedback` to `backend/api/routes/admin.py`. Follows the standard admin endpoint pattern: `require_admin` dependency, pagination with `limit`/`offset`/`search`/`exclude_test`, returns Pydantic response model. Queries `user_feedback` Firestore collection.
|
||||
|
||||
### Admin UI Page
|
||||
New page at `frontend/app/admin/feedback/page.tsx`. Follows existing admin page patterns (Card, Table, Badge, pagination, search input, loading states). Uses `adminApi.listFeedback()` to fetch data.
|
||||
|
||||
### Email Notification
|
||||
Add a new method to `EmailService` (or call `send_email` directly) from the `submit_user_feedback` endpoint in `users.py`. Uses the existing SendGrid infrastructure — no new template service templates needed since this is an internal admin notification (simple HTML table with the feedback data).
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Backend — Admin feedback list endpoint
|
||||
|
||||
1. [ ] Add `AdminFeedbackItem` and `AdminFeedbackListResponse` Pydantic models to `admin.py`
|
||||
2. [ ] Add `GET /api/admin/feedback` endpoint with:
|
||||
- Pagination: `limit=50`, `offset=0`
|
||||
- Search by user email
|
||||
- `exclude_test` filter (reuse `is_test_email`)
|
||||
- Sort by `created_at` descending
|
||||
- Return: items, total, offset, limit, has_more
|
||||
3. [ ] Add aggregate stats in response: average ratings, total count
|
||||
|
||||
### Step 2: Backend — Email notification on submission
|
||||
|
||||
4. [ ] Add `send_feedback_notification` method to `EmailService` that sends an HTML email to `admin@nomadkaraoke.com` containing:
|
||||
- User email
|
||||
- All 4 star ratings
|
||||
- All text fields
|
||||
- Would recommend / would use again
|
||||
- Submitted timestamp
|
||||
- Link to admin feedback page
|
||||
5. [ ] Call `send_feedback_notification` from `submit_user_feedback` in `users.py` (fire-and-forget, don't block the user response on email success)
|
||||
|
||||
### Step 3: Frontend — Admin API client
|
||||
|
||||
6. [ ] Add `listFeedback` method to `adminApi` in `frontend/lib/api.ts`
|
||||
7. [ ] Add TypeScript types for `AdminFeedbackItem` and `AdminFeedbackListResponse`
|
||||
|
||||
### Step 4: Frontend — Admin feedback page
|
||||
|
||||
8. [ ] Create `frontend/app/admin/feedback/page.tsx` with:
|
||||
- Table: user email, date, overall rating (stars), ease of use, lyrics accuracy, correction experience, would recommend, would use again
|
||||
- Expandable rows or click-to-detail for text fields (what went well, what could improve, additional comments)
|
||||
- Search by email
|
||||
- Pagination (50 per page)
|
||||
- Refresh button
|
||||
- Test data toggle (via `useAdminSettings`)
|
||||
9. [ ] Add "Feedback" item to admin sidebar in `frontend/components/admin/admin-sidebar.tsx` with `MessageSquare` icon
|
||||
|
||||
### Step 5: Testing
|
||||
|
||||
10. [ ] Backend unit test for `GET /api/admin/feedback` endpoint (pagination, search, exclude_test)
|
||||
11. [ ] Backend unit test for `send_feedback_notification` email method
|
||||
12. [ ] Frontend component test for feedback page (render, empty state)
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/admin.py` | Modify | Add feedback list endpoint + response models |
|
||||
| `backend/api/routes/users.py` | Modify | Add email notification call in `submit_user_feedback` |
|
||||
| `backend/services/email_service.py` | Modify | Add `send_feedback_notification` method |
|
||||
| `frontend/lib/api.ts` | Modify | Add `adminApi.listFeedback()` method + types |
|
||||
| `frontend/app/admin/feedback/page.tsx` | Create | Admin feedback review page |
|
||||
| `frontend/components/admin/admin-sidebar.tsx` | Modify | Add "Feedback" nav item |
|
||||
| `backend/tests/test_admin_feedback.py` | Create | Tests for admin feedback endpoint |
|
||||
| `backend/tests/test_feedback_email.py` | Create | Tests for feedback email notification |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: Admin endpoint (pagination, filtering, sorting), email method (content formatting, send call)
|
||||
- **Integration**: Submit feedback → verify email service called
|
||||
- **Manual verification**: Check email arrives in admin@nomadkaraoke.com inbox after submission
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should the admin page show feedback from the old `beta_feedback` collection too, or just `user_feedback`? (Recommendation: just `user_feedback` — the beta collection is legacy)
|
||||
- [ ] Should there be any spam/quality detection flagging? (Some submissions appear to game the system for credits)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Backend: Remove endpoint from admin.py, revert email call in users.py
|
||||
- Frontend: Delete feedback page, remove sidebar item
|
||||
- No data migration needed — Firestore collection unchanged
|
||||
@@ -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,151 @@
|
||||
# Plan: AI-Powered Credit Gating
|
||||
|
||||
**Created:** 2026-03-23
|
||||
**Branch:** feat/sess-20260323-1716-ai-credit-gating
|
||||
**Status:** Implemented
|
||||
|
||||
## Overview
|
||||
|
||||
Replace the automatic welcome/feedback credit grants with an AI-powered evaluation step. When a user triggers a credit grant (email verification or feedback submission), instead of immediately granting credits, we collect abuse signals and ask Gemini to make a grant/deny decision. Suspected abusers get a friendly rejection email (CC'd to Andrew) instead of free credits.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Welcome credit grants go through AI evaluation before granting
|
||||
- [ ] Feedback credit grants go through AI evaluation before granting
|
||||
- [ ] AI evaluates: fingerprint correlations, IP correlations, IP geo info, user agent, signup recency patterns
|
||||
- [ ] Approved users get credits as before (seamless experience)
|
||||
- [ ] Rejected users get a friendly-but-firm email explaining the situation, CC'd to andrew@beveridge.uk
|
||||
- [ ] Rejection email invites them to reply if it's a mistake
|
||||
- [ ] Decision is logged to Firestore for audit trail
|
||||
- [ ] Fail-open: if AI evaluation fails, grant credits (don't punish users for our errors)
|
||||
- [ ] Admin can override decisions via existing admin credit grant endpoint
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Architecture
|
||||
|
||||
```
|
||||
User verifies email / submits feedback
|
||||
↓
|
||||
Collect abuse signals (sync, fast):
|
||||
- User's fingerprint + IP
|
||||
- Other accounts with same fingerprint (from correlations)
|
||||
- Other accounts with same IP
|
||||
- IP geolocation info
|
||||
- Recent signup count from same IP/fingerprint (last 24h)
|
||||
- User agent string
|
||||
- For feedback: the feedback content itself
|
||||
↓
|
||||
Call Gemini (vertexai/gemini-2.5-pro-preview) with structured prompt:
|
||||
- Present all signals
|
||||
- Ask for JSON response: {decision: "grant" | "deny", reasoning: string, confidence: number}
|
||||
↓
|
||||
If "grant": grant credits normally, log decision
|
||||
If "deny": skip credit grant, send rejection email, log decision
|
||||
If AI call fails: grant credits (fail-open), log error
|
||||
```
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
1. **Two-phase verification**: The magic link verify endpoint returns immediately with session + a `credit_status: "evaluating"` field. The frontend shows a "preparing your account" loading screen, then polls/waits for the evaluation result via a new lightweight endpoint. This keeps the auth flow snappy while the AI evaluation runs in the background of the same request or via a short follow-up call. The frontend then shows either a celebratory "2 free credits!" interstitial or a "sorry, couldn't grant credits" interstitial before navigating to the dashboard.
|
||||
|
||||
2. **Fail-open**: If Gemini is down or returns an error, we grant credits. Better to let an occasional abuser through than block legitimate users.
|
||||
|
||||
3. **Use google-genai directly**: The project already has `langchain-google-genai` installed. We can use the simpler `google.generativeai` library directly for a focused prompt/response, or use the existing LangChain setup. We'll use `google.generativeai` for simplicity since this is a single-turn evaluation, not an agentic workflow.
|
||||
|
||||
4. **Structured JSON output**: Ask Gemini for structured output with decision, reasoning, and confidence to make decisions parseable and auditable.
|
||||
|
||||
5. **Log all decisions**: Store every evaluation in a `credit_evaluations` Firestore collection for audit trail and to tune the prompt over time.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Add google-generativeai dependency
|
||||
- Add `google-generativeai` to pyproject.toml (lightweight, direct Gemini access)
|
||||
- Verify it works with Vertex AI auth in the nomadkaraoke project
|
||||
|
||||
### Step 2: Create credit evaluation service
|
||||
- New file: `backend/services/credit_evaluation_service.py`
|
||||
- `CreditEvaluationService` class with:
|
||||
- `evaluate_credit_grant(email, grant_type, feedback_content=None) -> CreditEvaluation`
|
||||
- Collects all abuse signals by calling existing services (user_service, ip_geolocation_service)
|
||||
- Builds prompt with signals
|
||||
- Calls Gemini for decision
|
||||
- Logs decision to Firestore
|
||||
- Returns structured result
|
||||
|
||||
### Step 3: Build the Gemini prompt
|
||||
- System prompt explaining the role: "You are an anti-abuse evaluator for a karaoke video service..."
|
||||
- Present all signals in a structured format
|
||||
- Request JSON response: `{decision: "grant"|"deny", reasoning: "...", confidence: 0.0-1.0}`
|
||||
- Include clear guidelines: same fingerprint across accounts = very suspicious, same IP = somewhat suspicious, etc.
|
||||
|
||||
### Step 4: Create rejection email template
|
||||
- Add `send_credit_denied_email(email, reasoning)` to EmailService
|
||||
- Friendly-but-firm tone
|
||||
- CC andrew@beveridge.uk
|
||||
- Invite reply if it's a mistake
|
||||
- Use existing email template infrastructure (branding, styling)
|
||||
|
||||
### Step 5: Integrate into welcome credit flow
|
||||
- Modify `grant_welcome_credits_if_eligible()` in user_service.py
|
||||
- Before granting: call `CreditEvaluationService.evaluate_credit_grant(email, "welcome")`
|
||||
- If denied: send rejection email, return False
|
||||
- If error: log warning, grant anyway (fail-open)
|
||||
|
||||
### Step 6: Integrate into feedback credit flow
|
||||
- Modify feedback endpoint in users.py
|
||||
- Before granting credits: evaluate with feedback content included
|
||||
- If denied: return different response message, send rejection email
|
||||
- If error: grant anyway
|
||||
|
||||
### Step 7: Add Firestore collection for audit trail
|
||||
- Collection: `credit_evaluations`
|
||||
- Document fields: email, grant_type, decision, reasoning, confidence, signals_snapshot, model_used, evaluated_at
|
||||
- TTL: keep indefinitely (small volume, high audit value)
|
||||
|
||||
### Step 8: Tests
|
||||
- Unit tests for signal collection
|
||||
- Unit tests for prompt building
|
||||
- Unit tests for decision parsing (grant/deny/error cases)
|
||||
- Integration test for the evaluation service with mocked Gemini
|
||||
- Integration test for welcome credit flow with evaluation
|
||||
- Integration test for feedback credit flow with evaluation
|
||||
- Test fail-open behavior
|
||||
|
||||
### Step 9: Configuration
|
||||
- Add env vars: `CREDIT_EVAL_MODEL` (default: "gemini-2.5-pro-preview"), `CREDIT_EVAL_ENABLED` (default: true)
|
||||
- Add to config.py
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `pyproject.toml` | Modify | Add google-generativeai dependency |
|
||||
| `backend/config.py` | Modify | Add credit evaluation config vars |
|
||||
| `backend/services/credit_evaluation_service.py` | Create | New service: collect signals, call Gemini, log decision |
|
||||
| `backend/services/user_service.py` | Modify | Integrate evaluation into welcome credit grant |
|
||||
| `backend/api/routes/users.py` | Modify | Integrate evaluation into feedback credit grant |
|
||||
| `backend/services/email_service.py` | Modify | Add credit denied email template |
|
||||
| `backend/tests/test_credit_evaluation.py` | Create | Tests for evaluation service |
|
||||
| `backend/tests/test_anti_abuse.py` | Modify | Update welcome credit tests for evaluation |
|
||||
| `frontend/app/auth/verify/page.tsx` | Modify | Add "preparing account" loading + credit result interstitial |
|
||||
| `frontend/lib/api.ts` | Modify | Add credit evaluation status endpoint |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: Signal collection, prompt building, response parsing, fail-open behavior
|
||||
- **Integration tests**: Full evaluation flow with mocked Gemini responses
|
||||
- **E2E tests**: Manual verification in production with test accounts
|
||||
- **Edge cases**: Gemini timeout, malformed response, missing signals, first-ever user (no correlations)
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **Gemini model**: Using `gemini-3.1-pro-preview` as specified — already available in the nomadkaraoke GCP project.
|
||||
|
||||
2. **Latency UX**: Frontend shows a friendly "preparing your account" loading screen while evaluation runs. Then transitions to either a celebratory "2 free credits!" message (with gentle reminder not to abuse) or a "sorry, couldn't grant free credits" message with a buy credits CTA. User clicks through to dashboard from either.
|
||||
|
||||
3. **Should we also gate the existing rate limiter?** Currently `is_signup_rate_limited()` silently blocks at 2 accounts per IP/fingerprint per 24h. The AI evaluation is complementary — rate limiter blocks obvious rapid abuse, AI evaluation catches more subtle patterns.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Set `CREDIT_EVAL_ENABLED=false` in Cloud Run env vars → immediate rollback to auto-grant behavior. No data model changes needed. The evaluation service is purely additive.
|
||||
@@ -0,0 +1,150 @@
|
||||
# Plan: Block Disposable Email Registration
|
||||
|
||||
**Created:** 2026-03-19
|
||||
**Branch:** feat/sess-20260319-1332-disposable-email-abuse
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Users are signing up with disposable email addresses (yopmail.com, emailhook.site, etc.) to get unlimited free credits (2 per account). The `EmailValidationService` already exists with 160+ disposable domains but is **never called during signup**. We need to wire it into the magic link flow and show a friendly rejection message.
|
||||
|
||||
## Context
|
||||
|
||||
- The `EmailValidationService` (`backend/services/email_validation_service.py`) is fully implemented with disposable domain detection, email/IP blocklists, and admin management APIs
|
||||
- The admin blocklist management routes exist (`backend/api/routes/rate_limits.py`) and work
|
||||
- The magic link endpoint (`POST /api/users/auth/magic-link` in `backend/api/routes/users.py:133`) **never calls** the validation service
|
||||
- Currently 1 yopmail user and 1 emailhook.site user in `gen_users`
|
||||
- Each new account gets 2 free welcome credits automatically
|
||||
|
||||
## Requirements
|
||||
|
||||
- [x] Reject disposable email domains at the magic link endpoint (backend)
|
||||
- [x] Return a **specific, distinguishable error** so the frontend can show a friendly message (not the generic "email enumeration" response)
|
||||
- [x] Show a warm, friendly message in the AuthDialog explaining why and encouraging real email use
|
||||
- [x] Add `emailhook.site` to the default disposable domains list
|
||||
- [x] Add backend unit tests for the integration
|
||||
- [x] Add frontend test coverage for the new error state
|
||||
|
||||
## Design Decision: Explicit Rejection vs Silent Failure
|
||||
|
||||
The current magic link endpoint returns a generic success message to prevent email enumeration. For disposable emails, we will **explicitly reject** with a 422 status and a specific error message. This is the right trade-off because:
|
||||
|
||||
1. We *want* the user to know their disposable email won't work (so they can use a real one)
|
||||
2. Disposable domain detection is not sensitive information — the blocklist is public knowledge
|
||||
3. The friendly message serves our goal of converting them to real email users
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Backend — Add disposable email check to magic link endpoint
|
||||
|
||||
**File:** `backend/api/routes/users.py`
|
||||
|
||||
Add the `EmailValidationService` check **after** email lowercasing (line 158) and **before** tenant validation (line 164). Return a 422 with a friendly message.
|
||||
|
||||
```python
|
||||
# Check for disposable email domains
|
||||
email_validation = get_email_validation_service()
|
||||
if email_validation.is_disposable_domain(email):
|
||||
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="disposable_email_not_allowed"
|
||||
)
|
||||
```
|
||||
|
||||
Use a machine-readable error code (`disposable_email_not_allowed`) so the frontend can match on it and show the custom friendly message. This keeps the backend response lean and puts the UX copy in the frontend where it belongs.
|
||||
|
||||
### Step 2: Backend — Also check email and IP blocklists
|
||||
|
||||
In the same location, add checks for explicitly blocked emails and IPs:
|
||||
|
||||
```python
|
||||
if email_validation.is_email_blocked(email):
|
||||
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
|
||||
# Silent reject — return generic success to prevent enumeration
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
ip_address = http_request.client.host if http_request.client else None
|
||||
if ip_address and email_validation.is_ip_blocked(ip_address):
|
||||
logger.warning(f"Blocked IP signup attempt: {ip_address}")
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
```
|
||||
|
||||
Note: Blocked emails/IPs get silent rejection (anti-enumeration). Disposable domains get explicit rejection (we want the user to switch to a real email).
|
||||
|
||||
### Step 3: Backend — Add `emailhook.site` to default disposable domains
|
||||
|
||||
**File:** `backend/services/email_validation_service.py`
|
||||
|
||||
Add `emailhook.site` to `DEFAULT_DISPOSABLE_DOMAINS` set.
|
||||
|
||||
### Step 4: Frontend — Handle the disposable email error in AuthDialog
|
||||
|
||||
**File:** `frontend/components/auth/AuthDialog.tsx`
|
||||
|
||||
The `sendMagicLink` call in `auth.ts` already catches errors and sets `error` from the API response message. The `handleResponse` in `api.ts` throws an `ApiError` with the `detail` string for non-200 responses.
|
||||
|
||||
Update `handleSendMagicLink` to detect the `disposable_email_not_allowed` error code and show a friendly multi-line message instead of the terse error string:
|
||||
|
||||
```tsx
|
||||
const success = await sendMagicLink(email.trim().toLowerCase())
|
||||
if (success) {
|
||||
setStep("sent")
|
||||
}
|
||||
// If error contains our specific code, override with friendly message
|
||||
// (the error state is already set by the auth store)
|
||||
```
|
||||
|
||||
We need to detect the specific error. The cleanest approach: check the error string in the `displayError` rendering. If it matches `disposable_email_not_allowed`, render a custom friendly block instead of the red error text.
|
||||
|
||||
The friendly message:
|
||||
|
||||
> **We don't support disposable email addresses**
|
||||
>
|
||||
> We'd love to help you create karaoke videos! Please use your regular email address so we can send you a notification when your video is ready.
|
||||
>
|
||||
> We promise — no spam, no marketing emails, ever. We only email you about your karaoke videos.
|
||||
|
||||
### Step 5: Backend tests
|
||||
|
||||
**File:** `backend/tests/test_email_validation_integration.py` (new)
|
||||
|
||||
Test cases:
|
||||
1. Magic link with disposable email returns 422 with `disposable_email_not_allowed`
|
||||
2. Magic link with legitimate email proceeds normally
|
||||
3. Magic link with blocked email returns silent success (no actual email sent)
|
||||
4. Magic link with blocked IP returns silent success
|
||||
|
||||
### Step 6: Frontend tests
|
||||
|
||||
**File:** `frontend/components/__tests__/AuthDialog.test.tsx` (new or extend existing)
|
||||
|
||||
Test cases:
|
||||
1. Submitting a disposable email shows the friendly rejection message
|
||||
2. The friendly message contains the key copy (no spam promise, use real email)
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/users.py` | Modify | Add email validation checks to magic link endpoint |
|
||||
| `backend/services/email_validation_service.py` | Modify | Add `emailhook.site` to default domains |
|
||||
| `frontend/components/auth/AuthDialog.tsx` | Modify | Handle disposable email error with friendly message |
|
||||
| `backend/tests/test_email_validation_integration.py` | Create | Integration tests for the validation in signup flow |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests:** Validate `is_disposable_domain` catches yopmail, emailhook.site (already covered in existing tests)
|
||||
- **Integration tests:** New test file verifying the magic link endpoint rejects disposable emails with 422
|
||||
- **Frontend tests:** Verify the AuthDialog shows friendly message on disposable email error
|
||||
- **Manual verification:** Try signing up with `test@yopmail.com` on dev server to see the UX
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Remove the validation check from `send_magic_link()` in `users.py`. The `EmailValidationService` itself remains unchanged (it's already deployed and used by admin routes).
|
||||
@@ -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.
|
||||
+376
-115
@@ -628,7 +628,24 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
- name: Start Docker for GCS emulator
|
||||
- name: Wait for Docker to be available
|
||||
run: |
|
||||
# Self-hosted runners may still be initializing Docker on boot.
|
||||
# Wait up to 60s for the docker command and daemon to be ready.
|
||||
for i in $(seq 1 12); do
|
||||
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
|
||||
echo "Docker is ready"
|
||||
exit 0
|
||||
fi
|
||||
echo "Waiting for Docker... (attempt $i/12)"
|
||||
sleep 5
|
||||
done
|
||||
echo "ERROR: Docker not available after 60s"
|
||||
echo "PATH=$PATH"
|
||||
which docker 2>&1 || echo "docker binary not found"
|
||||
exit 1
|
||||
|
||||
- name: Pull GCS emulator image
|
||||
run: docker pull fsouza/fake-gcs-server:latest
|
||||
|
||||
- name: Run emulator integration tests
|
||||
@@ -942,6 +959,11 @@ jobs:
|
||||
REPOSITORY: karaoke-repo
|
||||
BASE_IMAGE_NAME: karaoke-backend-base
|
||||
APP_IMAGE_NAME: karaoke-backend
|
||||
# GPU image for audio worker (L4 in us-east4)
|
||||
GPU_REGISTRY: us-east4-docker.pkg.dev
|
||||
GPU_REPOSITORY: karaoke-backend-gpu
|
||||
GPU_BASE_IMAGE_NAME: karaoke-backend-gpu-base
|
||||
GPU_APP_IMAGE_NAME: karaoke-backend
|
||||
steps:
|
||||
- name: Check disk space (aggressive for Docker builds)
|
||||
run: |
|
||||
@@ -999,14 +1021,15 @@ jobs:
|
||||
version: "latest"
|
||||
|
||||
# ============================================
|
||||
# Deploy to GCE Encoding Worker (Immutable Deployment Pattern)
|
||||
# Blue-Green Deploy to GCE Encoding Worker
|
||||
#
|
||||
# This pattern ensures version consistency:
|
||||
# 1. Upload wheel to FIXED path (no version sorting)
|
||||
# 2. Upload startup.sh (logic can change without image rebuild)
|
||||
# 3. Write version manifest for verification
|
||||
# 4. Restart service (triggers bootstrap.sh -> startup.sh)
|
||||
# 5. STRICTLY verify deployed version (fail CI on mismatch)
|
||||
# This pattern ensures zero-downtime deployments:
|
||||
# 1. Upload wheel + startup.sh + version manifest to GCS
|
||||
# 2. Read blue-green config from Firestore
|
||||
# 3. Start secondary VM, wait for health + version match
|
||||
# 4. Deep health check: submit a real encode test
|
||||
# 5. Swap primary/secondary in Firestore (atomic transaction)
|
||||
# 6. Drain and stop old primary
|
||||
#
|
||||
# See infrastructure/encoding-worker/README.md for details
|
||||
# ============================================
|
||||
@@ -1017,12 +1040,12 @@ jobs:
|
||||
name: package-dist
|
||||
path: dist/
|
||||
|
||||
- name: Deploy to GCE Encoding Worker
|
||||
- name: Deploy to GCS
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
BUCKET="gs://karaoke-gen-storage-${{ env.PROJECT_ID }}"
|
||||
|
||||
echo "🚀 Deploying encoding worker v${VERSION}..."
|
||||
echo "Deploying encoding worker v${VERSION}..."
|
||||
|
||||
# 1. Find the wheel file
|
||||
WHEEL_FILE=$(ls dist/*.whl | head -1)
|
||||
@@ -1030,11 +1053,11 @@ jobs:
|
||||
echo "::error::No wheel file found in dist/"
|
||||
exit 1
|
||||
fi
|
||||
echo "📦 Found wheel: $WHEEL_FILE"
|
||||
echo "Found wheel: $WHEEL_FILE"
|
||||
|
||||
# 2. Upload wheel to FIXED path (atomic via temp file)
|
||||
# This eliminates version sorting - always use karaoke_gen-current.whl
|
||||
echo "📤 Uploading wheel to fixed path..."
|
||||
echo "Uploading wheel to fixed path..."
|
||||
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/karaoke_gen-current.whl.tmp"
|
||||
gsutil mv "${BUCKET}/wheels/karaoke_gen-current.whl.tmp" \
|
||||
"${BUCKET}/wheels/karaoke_gen-current.whl"
|
||||
@@ -1043,132 +1066,267 @@ jobs:
|
||||
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/"
|
||||
|
||||
# 3. Upload startup.sh (allows logic changes without image rebuild)
|
||||
echo "📤 Uploading startup.sh..."
|
||||
echo "Uploading startup.sh..."
|
||||
gsutil cp infrastructure/encoding-worker/startup.sh \
|
||||
"${BUCKET}/encoding-worker/startup.sh"
|
||||
|
||||
# 4. Write version manifest for verification
|
||||
echo "📝 Writing version manifest..."
|
||||
echo "Writing version manifest..."
|
||||
echo "${VERSION}" | gsutil cp - "${BUCKET}/encoding-worker/version.txt"
|
||||
|
||||
echo "✅ GCS deployment complete"
|
||||
echo "GCS deployment complete"
|
||||
|
||||
- name: Drain active encoding jobs before restart
|
||||
- name: Install Firestore client
|
||||
run: pip install google-cloud-firestore
|
||||
|
||||
- name: Read Firestore config
|
||||
id: config
|
||||
run: |
|
||||
# Graceful drain: wait for any active encoding jobs to finish before
|
||||
# restarting the worker. This prevents killing in-flight FFmpeg encodes.
|
||||
#
|
||||
# The /health endpoint returns active_jobs count. We poll until it's 0
|
||||
# or until the drain timeout expires (10 minutes — well within the
|
||||
# longest encoding time of ~5 min for a full 4-format encode).
|
||||
python3 << 'PYEOF'
|
||||
import json, os
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
doc = db.collection("config").document("encoding-worker").get()
|
||||
if not doc.exists:
|
||||
print("::error::Encoding worker config not found in Firestore")
|
||||
raise SystemExit(1)
|
||||
data = doc.to_dict()
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
|
||||
for key in ["primary_vm", "primary_ip", "primary_version",
|
||||
"secondary_vm", "secondary_ip"]:
|
||||
f.write(f"{key}={data.get(key, '')}\n")
|
||||
f.write(f"deploy_in_progress={str(data.get('deploy_in_progress', False)).lower()}\n")
|
||||
print(f"Config: primary={data['primary_vm']}, secondary={data['secondary_vm']}")
|
||||
PYEOF
|
||||
|
||||
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
|
||||
DRAIN_TIMEOUT=600 # 10 minutes
|
||||
POLL_INTERVAL=15
|
||||
ELAPSED=0
|
||||
- name: Wait for concurrent deploy
|
||||
if: steps.config.outputs.deploy_in_progress == 'true'
|
||||
run: |
|
||||
echo "Another deploy is in progress, waiting..."
|
||||
python3 << 'PYEOF'
|
||||
import time
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
for i in range(20):
|
||||
time.sleep(30)
|
||||
doc = db.collection("config").document("encoding-worker").get()
|
||||
if not doc.to_dict().get("deploy_in_progress", False):
|
||||
print("Concurrent deploy finished, proceeding")
|
||||
break
|
||||
else:
|
||||
print("::error::Timed out waiting for concurrent deploy (10 min)")
|
||||
raise SystemExit(1)
|
||||
PYEOF
|
||||
|
||||
echo "🔍 Checking for active encoding jobs before restart..."
|
||||
- name: Set deploy in progress
|
||||
run: |
|
||||
python3 << 'PYEOF'
|
||||
from datetime import datetime, timezone
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
db.collection("config").document("encoding-worker").update({
|
||||
"deploy_in_progress": True,
|
||||
"deploy_in_progress_since": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
print("Set deploy_in_progress=true")
|
||||
PYEOF
|
||||
|
||||
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
HEALTH=$(curl -sf -H "X-API-Key: $WORKER_KEY" "$WORKER_URL/health" 2>/dev/null || echo '{"active_jobs": -1}')
|
||||
ACTIVE=$(echo "$HEALTH" | grep -o '"active_jobs":[0-9]*' | cut -d: -f2)
|
||||
- name: Start secondary VM
|
||||
run: |
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
echo "Starting secondary VM: $SECONDARY_VM"
|
||||
gcloud compute instances start "$SECONDARY_VM" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
if [ -z "$ACTIVE" ] || [ "$ACTIVE" = "-1" ]; then
|
||||
echo "⚠️ Could not reach health endpoint (worker may already be down). Proceeding with restart."
|
||||
for i in $(seq 1 12); do
|
||||
STATUS=$(gcloud compute instances describe "$SECONDARY_VM" \
|
||||
--zone=us-central1-c --project=nomadkaraoke \
|
||||
--format='value(status)')
|
||||
echo "VM status: $STATUS (attempt $i/12)"
|
||||
if [ "$STATUS" = "RUNNING" ]; then
|
||||
break
|
||||
fi
|
||||
|
||||
if [ "$ACTIVE" = "0" ]; then
|
||||
echo "✅ No active encoding jobs. Safe to restart."
|
||||
break
|
||||
fi
|
||||
|
||||
echo "⏳ $ACTIVE active encoding job(s) running. Waiting ${POLL_INTERVAL}s... (${ELAPSED}s/${DRAIN_TIMEOUT}s)"
|
||||
sleep $POLL_INTERVAL
|
||||
ELAPSED=$((ELAPSED + POLL_INTERVAL))
|
||||
sleep 10
|
||||
done
|
||||
|
||||
if [ $ELAPSED -ge $DRAIN_TIMEOUT ]; then
|
||||
echo "⚠️ Drain timeout reached (${DRAIN_TIMEOUT}s) with jobs still active. Proceeding with restart."
|
||||
echo " Active jobs will be recoverable via idempotent /encode endpoint (PR #413)."
|
||||
fi
|
||||
|
||||
- name: Restart GCE Encoding Worker
|
||||
- name: Wait for service health
|
||||
id: health
|
||||
continue-on-error: true
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
HEALTH_URL="http://${SECONDARY_IP}:8080/health"
|
||||
|
||||
echo "🔄 Restarting encoding worker..."
|
||||
|
||||
# Use IAP tunneling - works directly with service account credentials
|
||||
gcloud compute ssh encoding-worker \
|
||||
--zone=us-central1-c \
|
||||
--project=nomadkaraoke \
|
||||
--tunnel-through-iap \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
|
||||
echo "⏳ Waiting for service to start (up to 60s)..."
|
||||
sleep 20
|
||||
|
||||
- name: Verify Encoding Worker Version
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
|
||||
echo "🔍 Verifying encoding worker version..."
|
||||
|
||||
# Retry loop - service may take time to fully start
|
||||
MAX_RETRIES=6
|
||||
RETRY_DELAY=10
|
||||
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Attempt $i/$MAX_RETRIES..."
|
||||
|
||||
NEW_VERSION=$(gcloud compute ssh encoding-worker \
|
||||
--zone=us-central1-c \
|
||||
--project=nomadkaraoke \
|
||||
--tunnel-through-iap \
|
||||
--command="curl -s http://localhost:8080/health 2>/dev/null | grep -o '\"wheel_version\":\"[^\"]*\"' | cut -d'\"' -f4" 2>/dev/null || echo "")
|
||||
|
||||
if [ "$NEW_VERSION" = "$VERSION" ]; then
|
||||
echo "✅ Encoding worker version verified: v$NEW_VERSION"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ -n "$NEW_VERSION" ]; then
|
||||
echo "⚠️ Version: $NEW_VERSION (expected: $VERSION)"
|
||||
else
|
||||
echo "⚠️ Health endpoint not responding yet"
|
||||
fi
|
||||
|
||||
if [ $i -lt $MAX_RETRIES ]; then
|
||||
echo " Retrying in ${RETRY_DELAY}s..."
|
||||
sleep $RETRY_DELAY
|
||||
echo "Waiting for service at $HEALTH_URL..."
|
||||
for i in $(seq 1 18); do
|
||||
RESPONSE=$(curl -sf "$HEALTH_URL" 2>/dev/null || echo "")
|
||||
if [ -n "$RESPONSE" ]; then
|
||||
WHEEL_VERSION=$(echo "$RESPONSE" | jq -r '.wheel_version // empty')
|
||||
echo "Health: version=$WHEEL_VERSION"
|
||||
if [ "$WHEEL_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "Version matches! Service is healthy."
|
||||
echo "healthy=true" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
echo "Attempt $i/18 - waiting 10s..."
|
||||
sleep 10
|
||||
done
|
||||
|
||||
# STRICT VERIFICATION: Fail CI on version mismatch
|
||||
echo ""
|
||||
echo "=============================================="
|
||||
echo "❌ ENCODING WORKER DEPLOYMENT FAILED"
|
||||
echo "=============================================="
|
||||
echo "Expected version: $VERSION"
|
||||
echo "Deployed version: $NEW_VERSION"
|
||||
echo ""
|
||||
echo "Possible causes:"
|
||||
echo " - GCS upload failed (check 'Deploy to GCE' step)"
|
||||
echo " - startup.sh download failed (check VM logs)"
|
||||
echo " - Wheel installation failed (check VM logs)"
|
||||
echo ""
|
||||
echo "To debug, SSH to VM and check logs:"
|
||||
echo " gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke --tunnel-through-iap"
|
||||
echo " sudo journalctl -u encoding-worker -n 100"
|
||||
echo " cat /var/log/encoding-worker-startup.log"
|
||||
echo "=============================================="
|
||||
|
||||
echo "::error::Service did not become healthy within 3 minutes"
|
||||
echo "healthy=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
|
||||
- name: Deep health check - real encode test
|
||||
if: steps.health.outputs.healthy == 'true'
|
||||
id: encode-test
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
echo "Uploading test assets to GCS..."
|
||||
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
|
||||
gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass
|
||||
|
||||
echo "Submitting test encode to $SECONDARY_IP..."
|
||||
RESPONSE=$(curl -sf -X POST "http://${SECONDARY_IP}:8080/encode-preview" \
|
||||
-H "X-API-Key: $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"job_id": "deploy-health-check",
|
||||
"ass_gcs_path": "gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass",
|
||||
"duration_seconds": 10
|
||||
}')
|
||||
|
||||
echo "Encode response: $RESPONSE"
|
||||
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
|
||||
|
||||
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "completed" ]; then
|
||||
echo "::error::Encode test failed with status: $STATUS"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for i in $(seq 1 12); do
|
||||
sleep 5
|
||||
JOB_STATUS=$(curl -sf \
|
||||
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
|
||||
-H "X-API-Key: $API_KEY" | jq -r '.status // "unknown"')
|
||||
echo "Encode status: $JOB_STATUS (attempt $i/12)"
|
||||
if [ "$JOB_STATUS" = "completed" ]; then
|
||||
echo "Encode test passed!"
|
||||
echo "passed=true" >> $GITHUB_OUTPUT
|
||||
gsutil rm -f gs://karaoke-gen-storage-nomadkaraoke/deploy-test/** || true
|
||||
exit 0
|
||||
elif [ "$JOB_STATUS" = "failed" ]; then
|
||||
echo "::error::Encode test failed"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "::error::Encode test timed out after 60s"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
|
||||
- name: Rollback on failure
|
||||
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed == 'false'
|
||||
run: |
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
if [ -n "$SECONDARY_VM" ]; then
|
||||
echo "Stopping secondary VM $SECONDARY_VM due to failed deploy"
|
||||
gcloud compute instances stop "$SECONDARY_VM" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
fi
|
||||
|
||||
python3 -c "
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project='nomadkaraoke')
|
||||
db.collection('config').document('encoding-worker').update({
|
||||
'deploy_in_progress': False,
|
||||
'deploy_in_progress_since': None,
|
||||
})
|
||||
print('Cleared deploy_in_progress flag')
|
||||
" || true
|
||||
|
||||
- name: Swap primary in Firestore
|
||||
if: steps.encode-test.outputs.passed == 'true'
|
||||
env:
|
||||
NEW_PRIMARY: ${{ steps.config.outputs.secondary_vm }}
|
||||
NEW_PRIMARY_IP: ${{ steps.config.outputs.secondary_ip }}
|
||||
NEW_VERSION: ${{ steps.version_check.outputs.version }}
|
||||
OLD_PRIMARY: ${{ steps.config.outputs.primary_vm }}
|
||||
OLD_PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
|
||||
OLD_VERSION: ${{ steps.config.outputs.primary_version }}
|
||||
run: |
|
||||
echo "Swapping: $OLD_PRIMARY -> secondary, $NEW_PRIMARY -> primary"
|
||||
python3 << 'PYEOF'
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from google.cloud import firestore
|
||||
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
doc_ref = db.collection("config").document("encoding-worker")
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
@firestore.transactional
|
||||
def swap(transaction):
|
||||
transaction.update(doc_ref, {
|
||||
"primary_vm": os.environ["NEW_PRIMARY"],
|
||||
"primary_ip": os.environ["NEW_PRIMARY_IP"],
|
||||
"primary_version": os.environ["NEW_VERSION"],
|
||||
"primary_deployed_at": now,
|
||||
"secondary_vm": os.environ["OLD_PRIMARY"],
|
||||
"secondary_ip": os.environ["OLD_PRIMARY_IP"],
|
||||
"secondary_version": os.environ["OLD_VERSION"],
|
||||
"secondary_deployed_at": now,
|
||||
"last_swap_at": now,
|
||||
"deploy_in_progress": False,
|
||||
"deploy_in_progress_since": None,
|
||||
})
|
||||
|
||||
transaction = db.transaction()
|
||||
swap(transaction)
|
||||
print(f"Swapped: {os.environ['NEW_PRIMARY']} is now primary")
|
||||
PYEOF
|
||||
|
||||
- name: Drain and stop old primary
|
||||
if: steps.encode-test.outputs.passed == 'true'
|
||||
run: |
|
||||
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
|
||||
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
|
||||
if [ "$ACTIVE_JOBS" -gt 0 ]; then
|
||||
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
|
||||
DRAIN_TIMEOUT=600
|
||||
ELAPSED=0
|
||||
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
if [ "$ACTIVE_JOBS" -eq 0 ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
echo "Stopping old primary: $OLD_PRIMARY"
|
||||
gcloud compute instances stop "$OLD_PRIMARY" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
- name: Configure Docker for Artifact Registry
|
||||
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
run: |
|
||||
gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
gcloud auth configure-docker ${{ env.GPU_REGISTRY }} --quiet
|
||||
|
||||
# ============================================
|
||||
# Docker Build with BuildKit + Registry Cache
|
||||
@@ -1287,6 +1445,86 @@ jobs:
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
# ============================================
|
||||
# GPU Image Build (for audio worker with L4 GPU)
|
||||
# Same pattern as base image: hash check → rebuild if needed
|
||||
# GPU image lives in us-east4 (co-located with GPU instances)
|
||||
# ============================================
|
||||
|
||||
- name: Calculate GPU base image hash
|
||||
id: gpu-base-hash
|
||||
run: |
|
||||
# Hash Dockerfile.gpu-base + pyproject.toml (deps that affect GPU image)
|
||||
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base pyproject.toml | sha256sum | cut -d' ' -f1)
|
||||
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
|
||||
echo "📋 GPU base content hash: $CURRENT_HASH"
|
||||
|
||||
- name: Check if GPU base image exists and is current
|
||||
id: check-gpu-base
|
||||
run: |
|
||||
GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
|
||||
EXISTING_HASH=""
|
||||
|
||||
MANIFEST=$(docker manifest inspect $GPU_BASE_IMAGE 2>/dev/null || echo "")
|
||||
CONFIG_DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
|
||||
|
||||
if [ -n "$CONFIG_DIGEST" ] && [ "$CONFIG_DIGEST" != "null" ] && [ "$CONFIG_DIGEST" != "" ]; then
|
||||
echo "📋 Found GPU manifest, config digest: $CONFIG_DIGEST"
|
||||
TOKEN=$(gcloud auth print-access-token)
|
||||
CONFIG_JSON=$(curl -sL -H "Authorization: Bearer $TOKEN" \
|
||||
"https://${{ env.GPU_REGISTRY }}/v2/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}/blobs/$CONFIG_DIGEST" 2>/dev/null)
|
||||
EXISTING_HASH=$(echo "$CONFIG_JSON" | jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
|
||||
echo "📋 Registry GPU base image hash: $EXISTING_HASH"
|
||||
else
|
||||
echo "⚠️ No existing GPU base image found in registry - will build"
|
||||
fi
|
||||
|
||||
if [ "${{ steps.gpu-base-hash.outputs.hash }}" != "$EXISTING_HASH" ]; then
|
||||
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or pyproject.toml changed)"
|
||||
echo " Current: ${{ steps.gpu-base-hash.outputs.hash }}"
|
||||
echo " Registry: $EXISTING_HASH"
|
||||
echo "needs_rebuild=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "✅ GPU base image is up to date"
|
||||
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Build and push GPU base image (if needed)
|
||||
if: steps.check-gpu-base.outputs.needs_rebuild == 'true'
|
||||
timeout-minutes: 45
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile.gpu-base
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
|
||||
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
build-args: |
|
||||
BUILD_DATE=${{ github.run_id }}
|
||||
BUILD_ID=${{ github.sha }}
|
||||
BASE_CONTENT_HASH=${{ steps.gpu-base-hash.outputs.hash }}
|
||||
provenance: false
|
||||
|
||||
- name: Build and push GPU app image
|
||||
timeout-minutes: 10
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:latest
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
build-args: |
|
||||
BASE_IMAGE=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
|
||||
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
# ============================================
|
||||
# Deploy to Cloud Run
|
||||
# ============================================
|
||||
@@ -1316,9 +1554,32 @@ jobs:
|
||||
--min-instances 4 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true" \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
run: |
|
||||
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
|
||||
echo "📦 Updating Cloud Run Jobs..."
|
||||
|
||||
# Video encoding job (CPU, us-central1)
|
||||
gcloud run jobs update video-encoding-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
# Audio separation job (GPU, us-east4) — uses GPU image
|
||||
gcloud run jobs update audio-separation-job \
|
||||
--image "$GPU_IMAGE" \
|
||||
--region us-east4 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
echo "✅ Cloud Run Jobs updated"
|
||||
|
||||
- name: Verify deployment and version
|
||||
run: |
|
||||
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
|
||||
@@ -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` |
|
||||
|
||||
@@ -27,7 +28,7 @@
|
||||
|
||||
- **Backend**: FastAPI on Cloud Run, Firestore, GCS, Secret Manager
|
||||
- **Frontend**: Next.js on Cloudflare Pages
|
||||
- **Processing**: Modal (GPU audio separation), AudioShake/Whisper (transcription)
|
||||
- **Processing**: Cloud Run GPU (L4 audio separation), AudioShake/Whisper (transcription)
|
||||
- **Infra**: Pulumi IaC, GitHub Actions CI/CD
|
||||
|
||||
## Essential Rules
|
||||
|
||||
@@ -13,7 +13,8 @@ help:
|
||||
@echo "Available commands:"
|
||||
@echo " make test - Run ALL tests (backend + frontend, installs deps automatically)"
|
||||
@echo " make test-backend - Run backend tests only (unit + emulator)"
|
||||
@echo " make test-frontend - Run frontend tests only (unit + E2E)"
|
||||
@echo " make test-frontend - Run frontend unit tests (Jest)"
|
||||
@echo " make test-frontend-e2e - Run frontend E2E tests (Playwright, requires dev server)"
|
||||
@echo " make test-unit - Run unit tests only (karaoke_gen package)"
|
||||
@echo " make test-e2e - Run emulator tests with auto-start/stop"
|
||||
@echo " make install - Install all dependencies (backend + frontend)"
|
||||
@@ -89,10 +90,15 @@ test-backend: test-unit test-backend-unit test-e2e
|
||||
@echo ""
|
||||
@echo "✅ Backend tests passed!"
|
||||
|
||||
# Run frontend tests (unit + E2E)
|
||||
# Run frontend unit tests (Jest only - E2E requires manual setup)
|
||||
test-frontend: install-frontend
|
||||
@echo "=== Running frontend tests ==="
|
||||
cd frontend && timeout $(TEST_TIMEOUT) npm run test:all
|
||||
@echo "=== Running frontend unit tests ==="
|
||||
cd frontend && timeout $(TEST_TIMEOUT) npm run test:unit
|
||||
|
||||
# Run frontend E2E tests (requires dev server - run manually, not in make test)
|
||||
test-frontend-e2e: install-frontend
|
||||
@echo "=== Running frontend E2E tests ==="
|
||||
cd frontend && timeout $(TEST_TIMEOUT) npm run test:e2e
|
||||
|
||||
# Run ALL tests (backend + frontend) - use this before committing!
|
||||
test: test-backend test-frontend
|
||||
|
||||
+9
-1
@@ -26,7 +26,15 @@ COPY backend /app/backend
|
||||
# Note: lyrics_transcriber is now a subpackage of karaoke_gen
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
COPY pyproject.toml README.md LICENSE /app/
|
||||
RUN pip install --no-cache-dir -e .
|
||||
# GPU images (MODEL_DIR set in base): use --no-deps to preserve pinned torch cu126
|
||||
# and audio-separator[gpu]. Without this, pip upgrades torch to cu130 (breaks CUDA
|
||||
# on Cloud Run L4 drivers) and reinstalls audio-separator[cpu] (breaks GPU ONNX).
|
||||
# CPU images: normal install resolves all deps from pyproject.toml.
|
||||
RUN if [ -n "$MODEL_DIR" ]; then \
|
||||
pip install --no-cache-dir --no-deps -e .; \
|
||||
else \
|
||||
pip install --no-cache-dir -e .; \
|
||||
fi
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models
|
||||
# This image is rebuilt only when deps or models change (infrequently).
|
||||
#
|
||||
# Build with: gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
|
||||
# Or manually: docker build -f backend/Dockerfile.gpu-base -t karaoke-backend-gpu-base .
|
||||
#
|
||||
# Layer caching strategy:
|
||||
# 1. System deps + fonts + ffmpeg (rarely change, always cached)
|
||||
# 2. CUDA library path configuration
|
||||
# 3. pyproject.toml + package stubs (changes with dep updates)
|
||||
# 4. pip install karaoke-gen deps + audio-separator[gpu] (slow, cached unless pyproject.toml changes)
|
||||
# 5. Source code copy (changes every rebuild, but AFTER deps are installed)
|
||||
# 6. spaCy model download (cached unless pip install layer changes)
|
||||
# 7. Pre-downloaded ensemble preset models (~1-1.5 GB, cached unless pip layer changes)
|
||||
|
||||
FROM nvidia/cuda:12.6.3-runtime-ubuntu22.04
|
||||
|
||||
# Prevent interactive prompts during package installation
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Install Python 3.11 from deadsnakes PPA and system dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
software-properties-common \
|
||||
&& add-apt-repository -y ppa:deadsnakes/ppa \
|
||||
&& apt-get update && apt-get install -y --no-install-recommends \
|
||||
# Python 3.11
|
||||
python3.11 \
|
||||
python3.11-dev \
|
||||
python3.11-venv \
|
||||
# Audio libraries
|
||||
libsndfile1 \
|
||||
libsox-dev \
|
||||
sox \
|
||||
# Build tools
|
||||
build-essential \
|
||||
# Utilities
|
||||
curl \
|
||||
xz-utils \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& python3.11 --version
|
||||
|
||||
# Install comprehensive font support for international lyrics and symbols
|
||||
# Noto fonts provide full Unicode coverage including:
|
||||
# - Latin, Greek, Cyrillic (core)
|
||||
# - CJK: Chinese, Japanese, Korean (~150MB)
|
||||
# - Arabic, Hebrew, Thai, Hindi, and other scripts (extra)
|
||||
# - Color emoji (limited support in libass, but available)
|
||||
# - Musical symbols (♪ ♫ etc.)
|
||||
# Note: This adds ~200-300MB to the image but ensures all languages render correctly
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk \
|
||||
fonts-noto-extra \
|
||||
fonts-noto-color-emoji \
|
||||
fontconfig \
|
||||
&& fc-cache -f \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install FFmpeg from Ubuntu package
|
||||
# The audio worker only uses FFmpeg for format conversion and padding, not
|
||||
# encoding-intensive tasks, so the Debian package is sufficient. The static
|
||||
# build from johnvansickle.com is used for the encoding worker instead.
|
||||
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Set Python 3.11 as default and install pip
|
||||
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1 \
|
||||
&& update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1 \
|
||||
&& curl -sS https://bootstrap.pypa.io/get-pip.py | python3.11 \
|
||||
&& python3 -m pip install --no-cache-dir --upgrade pip setuptools wheel
|
||||
|
||||
# Set up CUDA library paths so GPU-accelerated packages can find CUDA libs at runtime
|
||||
RUN echo '/usr/local/cuda/lib64' >> /etc/ld.so.conf.d/cuda.conf && ldconfig
|
||||
|
||||
# Environment configuration for CUDA and Python
|
||||
ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH \
|
||||
PATH=/usr/local/cuda/bin:$PATH \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
MODEL_DIR=/models
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy ONLY dependency specification files first (changes less often than source code)
|
||||
COPY pyproject.toml README.md LICENSE /app/
|
||||
|
||||
# Create minimal package stubs so pip can resolve the editable install
|
||||
# pip install -e . needs package directories to exist but doesn't validate content
|
||||
RUN mkdir -p /app/karaoke_gen /app/lyrics_transcriber_temp /app/backend && \
|
||||
touch /app/karaoke_gen/__init__.py /app/lyrics_transcriber_temp/__init__.py /app/backend/__init__.py
|
||||
|
||||
# Install all karaoke-gen Python dependencies (the slow part)
|
||||
# BuildKit cache mount preserves downloaded wheels across builds
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pip install --upgrade pip && \
|
||||
pip install -e .
|
||||
|
||||
# Install audio-separator with GPU support (PyTorch + CUDA + onnxruntime-gpu)
|
||||
# This is separate from pip install -e . to keep layer caching granular
|
||||
#
|
||||
# IMPORTANT: Install PyTorch cu126 FIRST, then audio-separator[gpu].
|
||||
# The default audio-separator[gpu] pulls PyTorch cu130, but Cloud Run L4 GPUs
|
||||
# have NVIDIA driver 570 which only supports up to CUDA 12.8. PyTorch cu130
|
||||
# fails with "NVIDIA driver is too old". PyTorch cu126 works with 12.8 drivers.
|
||||
# Installing torch first means audio-separator[gpu] sees it as already satisfied.
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pip install torch==2.6.0+cu126 torchvision==0.21.0+cu126 --index-url https://download.pytorch.org/whl/cu126 && \
|
||||
pip install "audio-separator[gpu]"
|
||||
|
||||
# Now copy actual source code (AFTER deps installed, so code changes don't
|
||||
# invalidate the expensive pip install layer in registry cache)
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
|
||||
COPY backend /app/backend
|
||||
|
||||
# Download spaCy language model for lyrics transcription
|
||||
# Must be done at build time, not runtime (Cloud Run network restrictions)
|
||||
RUN python -m spacy download en_core_web_sm
|
||||
|
||||
# Create models directory and pre-download ensemble preset models
|
||||
# Baking models into the image eliminates cold-start model download latency.
|
||||
# Total model size: ~1-1.5 GB for instrumental_clean + karaoke presets.
|
||||
RUN mkdir -p /models
|
||||
COPY backend/scripts/download_models.py /tmp/download_models.py
|
||||
RUN python /tmp/download_models.py /models && \
|
||||
rm /tmp/download_models.py && \
|
||||
ls -lh /models/
|
||||
|
||||
# Label with build info
|
||||
ARG BUILD_DATE
|
||||
ARG BUILD_ID
|
||||
ARG BASE_CONTENT_HASH
|
||||
LABEL org.opencontainers.image.created="${BUILD_DATE}"
|
||||
LABEL org.opencontainers.image.revision="${BUILD_ID}"
|
||||
LABEL org.opencontainers.image.title="karaoke-backend-gpu-base"
|
||||
LABEL org.opencontainers.image.description="GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models for karaoke-backend audio worker"
|
||||
LABEL base.content.hash="${BASE_CONTENT_HASH}"
|
||||
@@ -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(
|
||||
|
||||
+915
-4
@@ -22,7 +22,9 @@ 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 backend.services.ip_geolocation_service import get_ip_geolocation_service
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
|
||||
@@ -1045,6 +1047,7 @@ class TriggerWorkerResponse(BaseModel):
|
||||
ALLOWED_RESET_STATES = {
|
||||
"pending",
|
||||
"awaiting_audio_selection",
|
||||
"awaiting_audio_edit", # Re-enter audio editing phase
|
||||
"awaiting_review", # Combined review (lyrics + instrumental selection)
|
||||
# Note: awaiting_instrumental_selection removed - deprecated by combined review flow (Jan 2026)
|
||||
"instrumental_selected", # Re-run video generation with same settings
|
||||
@@ -1081,6 +1084,22 @@ STATE_DATA_CLEAR_KEYS = {
|
||||
"screens_progress",
|
||||
"encoding_progress",
|
||||
],
|
||||
"awaiting_audio_edit": [
|
||||
# Clear edit state so user starts fresh
|
||||
"audio_edit_stack",
|
||||
"audio_edit_redo_stack",
|
||||
"audio_edit_uploads",
|
||||
# Clear downstream processing flags
|
||||
"audio_complete",
|
||||
"lyrics_complete",
|
||||
"review_complete",
|
||||
"corrected_lyrics",
|
||||
"instrumental_selection",
|
||||
"video_progress",
|
||||
"render_progress",
|
||||
"screens_progress",
|
||||
"encoding_progress",
|
||||
],
|
||||
"awaiting_review": [
|
||||
# Combined review - user reviews lyrics AND selects instrumental in one step
|
||||
"review_complete",
|
||||
@@ -1202,6 +1221,18 @@ async def reset_job(
|
||||
# Add timeline event
|
||||
clear_updates["timeline"] = ArrayUnion([timeline_event])
|
||||
|
||||
# Special handling for awaiting_audio_edit: restore original input audio
|
||||
# The submit endpoint copies edited audio to input_media_gcs_path,
|
||||
# so we must restore the original path so the user starts fresh.
|
||||
if target_state == "awaiting_audio_edit":
|
||||
original_path = current_state_data.get("original_input_media_gcs_path")
|
||||
if original_path:
|
||||
clear_updates["input_media_gcs_path"] = original_path
|
||||
logger.info(
|
||||
f"Admin reset job {job_id}: Restoring input_media_gcs_path "
|
||||
f"to original: {original_path}"
|
||||
)
|
||||
|
||||
# Execute the update
|
||||
job_ref.update(clear_updates)
|
||||
|
||||
@@ -1591,6 +1622,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 +1761,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 +1805,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 +2143,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 +3097,856 @@ 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,
|
||||
}
|
||||
|
||||
|
||||
# ─── Audio Edit Reviews ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class AudioEditReviewSummary(BaseModel):
|
||||
job_id: str
|
||||
artist: str
|
||||
title: str
|
||||
user_email: str
|
||||
status: str
|
||||
created_at: Optional[str] = None
|
||||
updated_at: Optional[str] = None
|
||||
session_count: int = 0
|
||||
total_edits: int = 0
|
||||
original_duration: Optional[float] = None
|
||||
current_duration: Optional[float] = None
|
||||
latest_trigger: Optional[str] = None
|
||||
|
||||
|
||||
class AudioEditReviewListResponse(BaseModel):
|
||||
reviews: List[AudioEditReviewSummary]
|
||||
total: int
|
||||
has_more: bool
|
||||
|
||||
|
||||
@router.get("/audio-edit-reviews", response_model=AudioEditReviewListResponse)
|
||||
def list_audio_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 audio edit sessions."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
user_service = get_user_service()
|
||||
db = user_service.db
|
||||
fs = FirestoreService()
|
||||
|
||||
STREAM_LIMIT = 10000
|
||||
reviews = []
|
||||
streamed = 0
|
||||
|
||||
for doc in db.collection("jobs").limit(STREAM_LIMIT).stream():
|
||||
streamed += 1
|
||||
data = doc.to_dict()
|
||||
state_data = data.get("state_data") or {}
|
||||
|
||||
# Only include jobs that have been through audio edit
|
||||
# (have edit stack or have audio edit sessions)
|
||||
has_edit_stack = bool(state_data.get("audio_edit_stack"))
|
||||
status = data.get("status", "")
|
||||
is_in_audio_edit = status in (
|
||||
"awaiting_audio_edit", "in_audio_edit", "audio_edit_complete"
|
||||
)
|
||||
|
||||
if not has_edit_stack and not is_in_audio_edit:
|
||||
# Quick check: does this job have any audio edit sessions subcollection?
|
||||
sessions_ref = db.collection("jobs").document(doc.id).collection("audio_edit_sessions")
|
||||
if not next(sessions_ref.limit(1).stream(), None):
|
||||
continue
|
||||
|
||||
email = data.get("user_email", "")
|
||||
if exclude_test and is_test_email(email):
|
||||
continue
|
||||
|
||||
artist = data.get("artist", "")
|
||||
title = data.get("title", "")
|
||||
|
||||
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
|
||||
|
||||
# Get session summary info
|
||||
sessions = fs.list_audio_edit_sessions(doc.id)
|
||||
session_count = len(sessions)
|
||||
total_edits = 0
|
||||
latest_trigger = None
|
||||
current_duration = None
|
||||
original_duration = None
|
||||
|
||||
if sessions:
|
||||
latest = sessions[0] # Already sorted by updated_at DESC
|
||||
total_edits = latest.edit_count
|
||||
latest_trigger = latest.trigger
|
||||
current_duration = latest.audio_duration_seconds
|
||||
original_duration = latest.original_duration_seconds
|
||||
|
||||
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(AudioEditReviewSummary(
|
||||
job_id=doc.id,
|
||||
artist=artist or "",
|
||||
title=title or "",
|
||||
user_email=email or "",
|
||||
status=status,
|
||||
created_at=_to_iso(created_at),
|
||||
updated_at=_to_iso(updated_at),
|
||||
session_count=session_count,
|
||||
total_edits=total_edits,
|
||||
original_duration=original_duration,
|
||||
current_duration=current_duration,
|
||||
latest_trigger=latest_trigger,
|
||||
))
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {doc.id}: Error building audio edit review summary: {e}")
|
||||
continue
|
||||
|
||||
if streamed >= STREAM_LIMIT:
|
||||
logger.warning(f"Audio edit reviews stream hit limit ({STREAM_LIMIT}), results may be incomplete")
|
||||
|
||||
reviews.sort(
|
||||
key=lambda r: r.updated_at or r.created_at or "",
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
total = len(reviews)
|
||||
paginated = reviews[offset : offset + limit]
|
||||
|
||||
return AudioEditReviewListResponse(
|
||||
reviews=paginated,
|
||||
total=total,
|
||||
has_more=(offset + limit) < total,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/audio-edit-reviews/{job_id}")
|
||||
async def get_audio_edit_review_detail(
|
||||
job_id: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Get full audio edit review detail for one job, including all sessions."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
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()
|
||||
fs = FirestoreService()
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
# Get all sessions
|
||||
sessions = fs.list_audio_edit_sessions(job_id)
|
||||
sessions_data = []
|
||||
for session in sessions:
|
||||
session_dict = session.to_dict()
|
||||
# Convert datetimes to ISO strings
|
||||
for key in ("created_at", "updated_at"):
|
||||
val = session_dict.get(key)
|
||||
if hasattr(val, "isoformat"):
|
||||
session_dict[key] = val.isoformat()
|
||||
sessions_data.append(session_dict)
|
||||
|
||||
# Get current edit stack from state_data
|
||||
state_data = job.state_data or {}
|
||||
edit_stack = state_data.get("audio_edit_stack", [])
|
||||
|
||||
# Generate signed URLs for original and current audio
|
||||
original_audio_url = None
|
||||
current_audio_url = None
|
||||
transcoding = AudioTranscodingService(storage_service=storage)
|
||||
|
||||
if job.input_media_gcs_path:
|
||||
try:
|
||||
current_audio_url = await transcoding.get_review_audio_url_async(
|
||||
job.input_media_gcs_path, expiration_minutes=120
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not generate current audio URL: {e}")
|
||||
|
||||
# Original audio (before edits)
|
||||
original_path = state_data.get("original_input_media_gcs_path") or job.input_media_gcs_path
|
||||
if original_path and original_path != job.input_media_gcs_path:
|
||||
try:
|
||||
original_audio_url = await transcoding.get_review_audio_url_async(
|
||||
original_path, expiration_minutes=120
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not generate original audio URL: {e}")
|
||||
|
||||
# Load edit log if it exists
|
||||
edit_log = None
|
||||
edit_log_path = f"jobs/{job_id}/audio_edit/edit_log.json"
|
||||
try:
|
||||
if storage.file_exists(edit_log_path):
|
||||
edit_log = storage.download_json(edit_log_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not load audio edit log: {e}")
|
||||
|
||||
return {
|
||||
"job": job_meta,
|
||||
"sessions": sessions_data,
|
||||
"edit_stack": edit_stack,
|
||||
"edit_log": edit_log,
|
||||
"original_audio_url": original_audio_url,
|
||||
"current_audio_url": current_audio_url,
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Anti-Abuse Investigation
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@router.get("/abuse/related/{email}")
|
||||
async def find_related_accounts(
|
||||
email: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Find accounts related to the given email by shared signup IP or device fingerprint.
|
||||
|
||||
Returns the target user plus lists of other accounts from the same IP and/or fingerprint.
|
||||
"""
|
||||
result = user_service.find_related_accounts(email)
|
||||
|
||||
if not result["user"]:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
user = result["user"]
|
||||
return {
|
||||
"user": {
|
||||
"email": user.email,
|
||||
"signup_ip": user.signup_ip,
|
||||
"device_fingerprint": user.device_fingerprint,
|
||||
"credits": user.credits,
|
||||
"total_jobs_created": user.total_jobs_created,
|
||||
"total_spent": user.total_spent,
|
||||
"created_at": str(user.created_at),
|
||||
},
|
||||
"related_by_ip": [
|
||||
{
|
||||
"email": u.email,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in result["by_ip"]
|
||||
],
|
||||
"related_by_fingerprint": [
|
||||
{
|
||||
"email": u.email,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in result["by_fingerprint"]
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/abuse/correlations")
|
||||
async def find_account_correlations(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Find clusters of accounts sharing the same device fingerprint or signup IP.
|
||||
|
||||
Returns fingerprint clusters (RED flag - near-certain multi-accounting) and
|
||||
IP clusters (ORANGE flag - suspicious but could be shared network), sorted
|
||||
by group size. Includes user agent data for additional correlation signal.
|
||||
"""
|
||||
result = user_service.find_account_correlations()
|
||||
user_agents = result.get("user_agents", {})
|
||||
|
||||
def serialize_cluster_user(u, include_user_agent=True):
|
||||
data = {
|
||||
"email": u.email,
|
||||
"signup_ip": u.signup_ip,
|
||||
"device_fingerprint": u.device_fingerprint,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_jobs_completed": u.total_jobs_completed,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
if include_user_agent:
|
||||
data["user_agent"] = user_agents.get(u.email)
|
||||
return data
|
||||
|
||||
return {
|
||||
"fingerprint_clusters": [
|
||||
{
|
||||
"fingerprint": cluster["fingerprint"],
|
||||
"count": len(cluster["users"]),
|
||||
"users": [serialize_cluster_user(u) for u in cluster["users"]],
|
||||
}
|
||||
for cluster in result["fingerprint_clusters"]
|
||||
],
|
||||
"ip_clusters": [
|
||||
{
|
||||
"ip": cluster["ip"],
|
||||
"count": len(cluster["users"]),
|
||||
"users": [serialize_cluster_user(u) for u in cluster["users"]],
|
||||
}
|
||||
for cluster in result["ip_clusters"]
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/abuse/suspicious")
|
||||
async def find_suspicious_accounts(
|
||||
min_jobs: int = 2,
|
||||
max_spend: int = 0,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Find accounts with many jobs but no (or low) spend.
|
||||
|
||||
Detects potential free-credit abusers: people creating multiple accounts
|
||||
to get welcome credits without ever paying.
|
||||
|
||||
Args:
|
||||
min_jobs: Minimum jobs created to flag (default: 2)
|
||||
max_spend: Maximum total_spent in cents (default: 0 = only free accounts)
|
||||
"""
|
||||
users = user_service.find_suspicious_accounts(min_jobs=min_jobs, max_spend=max_spend)
|
||||
|
||||
return {
|
||||
"count": len(users),
|
||||
"users": [
|
||||
{
|
||||
"email": u.email,
|
||||
"signup_ip": u.signup_ip,
|
||||
"device_fingerprint": u.device_fingerprint,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_jobs_completed": u.total_jobs_completed,
|
||||
"total_spent": u.total_spent,
|
||||
"has_submitted_feedback": u.has_submitted_feedback,
|
||||
"created_at": str(u.created_at),
|
||||
"last_login_at": str(u.last_login_at) if u.last_login_at else None,
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/abuse/by-ip/{ip_address:path}")
|
||||
async def find_users_by_ip(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""Find all users who signed up from a specific IP address."""
|
||||
users = user_service.find_users_by_signup_ip(ip_address)
|
||||
return {
|
||||
"ip_address": ip_address,
|
||||
"count": len(users),
|
||||
"users": [
|
||||
{
|
||||
"email": u.email,
|
||||
"device_fingerprint": u.device_fingerprint,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/abuse/by-fingerprint/{fingerprint}")
|
||||
async def find_users_by_fingerprint(
|
||||
fingerprint: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""Find all users who signed up with a specific device fingerprint."""
|
||||
users = user_service.find_users_by_fingerprint(fingerprint)
|
||||
return {
|
||||
"device_fingerprint": fingerprint,
|
||||
"count": len(users),
|
||||
"users": [
|
||||
{
|
||||
"email": u.email,
|
||||
"signup_ip": u.signup_ip,
|
||||
"credits": u.credits,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/abuse/backfill-ips")
|
||||
async def backfill_signup_ips(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Backfill signup_ip for existing users from their earliest session or magic link.
|
||||
|
||||
One-time operation to populate signup_ip for users created before the field was added.
|
||||
Only updates users who currently have signup_ip=None.
|
||||
"""
|
||||
from backend.services.user_service import SESSIONS_COLLECTION, MAGIC_LINKS_COLLECTION
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
db = user_service.db
|
||||
updated = 0
|
||||
skipped = 0
|
||||
no_ip_found = 0
|
||||
|
||||
# Known bad IPs (load balancer / proxy IPs that aren't real client IPs)
|
||||
BAD_IPS = {"169.254.169.126", "unknown", ""}
|
||||
|
||||
# Find all users without signup_ip or with a known-bad IP
|
||||
users_query = db.collection(USERS_COLLECTION).stream()
|
||||
|
||||
for user_doc in users_query:
|
||||
user_data = user_doc.to_dict()
|
||||
current_ip = user_data.get("signup_ip")
|
||||
if current_ip and current_ip not in BAD_IPS:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
email = user_data.get("email", "")
|
||||
if not email:
|
||||
continue
|
||||
|
||||
ip = None
|
||||
|
||||
# Try sessions first (most reliable — created at verification)
|
||||
# No order_by to avoid needing extra composite index; any IP is fine
|
||||
sessions = (
|
||||
db.collection(SESSIONS_COLLECTION)
|
||||
.where(filter=FieldFilter("user_email", "==", email))
|
||||
.limit(5)
|
||||
.stream()
|
||||
)
|
||||
for session_doc in sessions:
|
||||
session_data = session_doc.to_dict()
|
||||
candidate_ip = session_data.get("ip_address")
|
||||
if candidate_ip and candidate_ip not in BAD_IPS:
|
||||
ip = candidate_ip
|
||||
break
|
||||
|
||||
# Fallback: try magic links
|
||||
if not ip:
|
||||
links = (
|
||||
db.collection(MAGIC_LINKS_COLLECTION)
|
||||
.where(filter=FieldFilter("email", "==", email))
|
||||
.limit(5)
|
||||
.stream()
|
||||
)
|
||||
for link_doc in links:
|
||||
link_data = link_doc.to_dict()
|
||||
candidate_ip = link_data.get("ip_address")
|
||||
if candidate_ip:
|
||||
ip = candidate_ip
|
||||
break
|
||||
|
||||
if ip:
|
||||
user_doc.reference.update({"signup_ip": ip})
|
||||
updated += 1
|
||||
logger.info(f"Backfilled signup_ip for {email}: {ip}")
|
||||
else:
|
||||
# Clear bad IP if one was set (e.g., load balancer IP)
|
||||
if current_ip and current_ip in BAD_IPS:
|
||||
user_doc.reference.update({"signup_ip": None})
|
||||
updated += 1
|
||||
logger.info(f"Cleared bad signup_ip for {email}: {current_ip}")
|
||||
else:
|
||||
no_ip_found += 1
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"updated": updated,
|
||||
"skipped_already_set": skipped,
|
||||
"no_ip_found": no_ip_found,
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# IP Geolocation Lookup
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class IpBatchRequest(BaseModel):
|
||||
"""Request for batch IP geolocation lookup."""
|
||||
ips: list[str]
|
||||
|
||||
|
||||
@router.get("/abuse/ip-info/{ip_address:path}")
|
||||
async def get_ip_info(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Look up geolocation info for a single IP address."""
|
||||
geo_service = get_ip_geolocation_service()
|
||||
return geo_service.lookup_ip(ip_address)
|
||||
|
||||
|
||||
@router.post("/abuse/ip-info/batch")
|
||||
async def get_ip_info_batch(
|
||||
request: IpBatchRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Look up geolocation info for multiple IP addresses."""
|
||||
if len(request.ips) > 100:
|
||||
raise HTTPException(status_code=400, detail="Maximum 100 IPs per batch request")
|
||||
geo_service = get_ip_geolocation_service()
|
||||
return geo_service.lookup_ips_batch(request.ips)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# User Feedback
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class AdminFeedbackItem(BaseModel):
|
||||
"""Single feedback submission for admin view."""
|
||||
id: str
|
||||
user_email: str
|
||||
created_at: Optional[str] = None
|
||||
overall_rating: int
|
||||
ease_of_use_rating: int
|
||||
lyrics_accuracy_rating: int
|
||||
correction_experience_rating: int
|
||||
what_went_well: Optional[str] = None
|
||||
what_could_improve: Optional[str] = None
|
||||
additional_comments: Optional[str] = None
|
||||
would_recommend: bool = True
|
||||
would_use_again: bool = True
|
||||
|
||||
|
||||
class AdminFeedbackListResponse(BaseModel):
|
||||
"""Paginated list of feedback submissions."""
|
||||
items: List[AdminFeedbackItem]
|
||||
total: int
|
||||
offset: int
|
||||
limit: int
|
||||
has_more: bool
|
||||
avg_overall_rating: Optional[float] = None
|
||||
avg_ease_of_use_rating: Optional[float] = None
|
||||
avg_lyrics_accuracy_rating: Optional[float] = None
|
||||
avg_correction_experience_rating: Optional[float] = None
|
||||
|
||||
|
||||
@router.get("/feedback", response_model=AdminFeedbackListResponse)
|
||||
def list_user_feedback(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
search: Optional[str] = None,
|
||||
exclude_test: bool = False,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""List all user feedback submissions with pagination and search."""
|
||||
limit = max(1, min(limit, 200))
|
||||
offset = max(0, offset)
|
||||
|
||||
user_service = get_user_service()
|
||||
db = user_service.db
|
||||
|
||||
items = []
|
||||
for doc in db.collection("user_feedback").stream():
|
||||
data = doc.to_dict()
|
||||
email = data.get("user_email", "")
|
||||
|
||||
if exclude_test and is_test_email(email):
|
||||
continue
|
||||
|
||||
if search and search.lower() not in email.lower():
|
||||
continue
|
||||
|
||||
created_at = data.get("created_at")
|
||||
if created_at is not None and hasattr(created_at, "isoformat"):
|
||||
created_at = created_at.isoformat()
|
||||
elif created_at is not None:
|
||||
created_at = str(created_at)
|
||||
|
||||
items.append(AdminFeedbackItem(
|
||||
id=data.get("id", doc.id),
|
||||
user_email=email,
|
||||
created_at=created_at,
|
||||
overall_rating=data.get("overall_rating", 0),
|
||||
ease_of_use_rating=data.get("ease_of_use_rating", 0),
|
||||
lyrics_accuracy_rating=data.get("lyrics_accuracy_rating", 0),
|
||||
correction_experience_rating=data.get("correction_experience_rating", 0),
|
||||
what_went_well=data.get("what_went_well"),
|
||||
what_could_improve=data.get("what_could_improve"),
|
||||
additional_comments=data.get("additional_comments"),
|
||||
would_recommend=data.get("would_recommend", True),
|
||||
would_use_again=data.get("would_use_again", True),
|
||||
))
|
||||
|
||||
# Sort by newest first
|
||||
items.sort(key=lambda x: x.created_at or "", reverse=True)
|
||||
|
||||
# Compute aggregate stats
|
||||
total = len(items)
|
||||
avg_overall = sum(i.overall_rating for i in items) / total if total else None
|
||||
avg_ease = sum(i.ease_of_use_rating for i in items) / total if total else None
|
||||
avg_lyrics = sum(i.lyrics_accuracy_rating for i in items) / total if total else None
|
||||
avg_correction = sum(i.correction_experience_rating for i in items) / total if total else None
|
||||
|
||||
paginated = items[offset:offset + limit]
|
||||
|
||||
return AdminFeedbackListResponse(
|
||||
items=paginated,
|
||||
total=total,
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
has_more=(offset + limit) < total,
|
||||
avg_overall_rating=round(avg_overall, 2) if avg_overall is not None else None,
|
||||
avg_ease_of_use_rating=round(avg_ease, 2) if avg_ease is not None else None,
|
||||
avg_lyrics_accuracy_rating=round(avg_lyrics, 2) if avg_lyrics is not None else None,
|
||||
avg_correction_experience_rating=round(avg_correction, 2) if avg_correction is not None else None,
|
||||
)
|
||||
@@ -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
|
||||
|
||||
@@ -239,24 +240,24 @@ class AudioSelectResponse(BaseModel):
|
||||
selected_provider: str
|
||||
|
||||
|
||||
def extract_request_metadata(request: Request, created_from: str = "audio_search") -> Dict[str, Any]:
|
||||
def extract_request_metadata(request: Request, created_from: str = "audio_search", auth_result=None) -> Dict[str, Any]:
|
||||
"""Extract metadata from request for job tracking."""
|
||||
headers = dict(request.headers)
|
||||
|
||||
|
||||
client_ip = headers.get('x-forwarded-for', '').split(',')[0].strip()
|
||||
if not client_ip and request.client:
|
||||
client_ip = request.client.host
|
||||
|
||||
|
||||
user_agent = headers.get('user-agent', '')
|
||||
environment = headers.get('x-environment', '')
|
||||
client_id = headers.get('x-client-id', '')
|
||||
|
||||
|
||||
custom_headers = {}
|
||||
for key, value in headers.items():
|
||||
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
|
||||
custom_headers[key] = value
|
||||
|
||||
return {
|
||||
|
||||
metadata = {
|
||||
'client_ip': client_ip,
|
||||
'user_agent': user_agent,
|
||||
'environment': environment,
|
||||
@@ -266,6 +267,17 @@ def extract_request_metadata(request: Request, created_from: str = "audio_search
|
||||
'custom_headers': custom_headers,
|
||||
}
|
||||
|
||||
# Add auth context for abuse investigation and analytics
|
||||
if auth_result is not None:
|
||||
metadata['auth_method'] = getattr(auth_result, 'auth_method', None)
|
||||
user_type = getattr(auth_result, 'user_type', None)
|
||||
metadata['user_type'] = user_type.value if hasattr(user_type, 'value') else str(user_type) if user_type else None
|
||||
remaining = getattr(auth_result, 'remaining_uses', None)
|
||||
if remaining is not None:
|
||||
metadata['credits_at_creation'] = remaining
|
||||
|
||||
return metadata
|
||||
|
||||
|
||||
def _extract_gcs_path(filepath: str) -> str:
|
||||
"""
|
||||
@@ -632,8 +644,9 @@ async def search_audio(
|
||||
}
|
||||
)
|
||||
|
||||
# Extract request metadata
|
||||
request_metadata = extract_request_metadata(request, created_from="audio_search")
|
||||
# Extract request metadata (includes auth context + search query info)
|
||||
request_metadata = extract_request_metadata(request, created_from="audio_search", auth_result=auth_result)
|
||||
request_metadata['search_query'] = {'artist': body.artist, 'title': body.title}
|
||||
|
||||
# Apply default theme if none specified
|
||||
# This ensures all karaoke videos use the Nomad theme by default
|
||||
@@ -687,11 +700,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
|
||||
@@ -748,11 +766,11 @@ async def search_audio(
|
||||
|
||||
# Generate GCS path
|
||||
if file_info.file_type == 'style_params':
|
||||
gcs_path = f"uploads/{job_id}/style/style_params.json"
|
||||
gcs_path = f"jobs/{job_id}/style/style_params.json"
|
||||
else:
|
||||
# style_intro_background -> intro_background, etc.
|
||||
asset_key = file_info.file_type.replace('style_', '')
|
||||
gcs_path = f"uploads/{job_id}/style/{asset_key}{ext}"
|
||||
gcs_path = f"jobs/{job_id}/style/{asset_key}{ext}"
|
||||
|
||||
# Generate signed upload URL
|
||||
signed_url = storage_service.generate_signed_upload_url(
|
||||
@@ -833,13 +851,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",
|
||||
@@ -1030,7 +1047,9 @@ async def search_audio_standalone(
|
||||
)
|
||||
results_dicts.append(r.to_dict())
|
||||
|
||||
# Store session in Firestore (TTL: 30 minutes)
|
||||
# Store session in Firestore (TTL: 7 days)
|
||||
# Long TTL so users who leave a tab open mid-flow don't hit "Search expired".
|
||||
# Sessions are tiny docs (~2 KB) and cleaned up by Firestore TTL policy.
|
||||
session_id = str(uuid.uuid4())
|
||||
now = datetime.utcnow()
|
||||
session_data = {
|
||||
@@ -1042,7 +1061,7 @@ async def search_audio_standalone(
|
||||
'results': results_dicts,
|
||||
'remote_search_id': audio_search_service.last_remote_search_id,
|
||||
'created_at': now.isoformat(),
|
||||
'ttl_expiry': now + timedelta(minutes=30),
|
||||
'ttl_expiry': now + timedelta(days=7),
|
||||
}
|
||||
firestore_service = FirestoreService()
|
||||
firestore_service.create_search_session(session_data)
|
||||
@@ -1156,13 +1175,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",
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
Encoding worker lifecycle endpoints.
|
||||
|
||||
Provides warmup and heartbeat endpoints for the blue-green
|
||||
encoding worker VMs. Called by the frontend to ensure the
|
||||
primary VM is running before encoding requests.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/internal/encoding-worker", tags=["encoding-worker"])
|
||||
|
||||
# Lazy-loaded singleton
|
||||
_manager = None
|
||||
|
||||
|
||||
def get_worker_manager():
|
||||
global _manager
|
||||
if _manager is None:
|
||||
from google.cloud import compute_v1, firestore
|
||||
from backend.config import get_settings
|
||||
settings = get_settings()
|
||||
db = firestore.Client(project=settings.google_cloud_project)
|
||||
compute_client = compute_v1.InstancesClient()
|
||||
_manager = EncodingWorkerManager(
|
||||
db=db,
|
||||
compute_client=compute_client,
|
||||
project_id=settings.google_cloud_project,
|
||||
)
|
||||
return _manager
|
||||
|
||||
|
||||
@router.post("/warmup")
|
||||
async def warmup_encoding_worker(
|
||||
_admin=Depends(require_admin),
|
||||
manager=Depends(get_worker_manager),
|
||||
):
|
||||
"""Start the primary encoding worker VM if it's stopped."""
|
||||
try:
|
||||
result = manager.ensure_primary_running()
|
||||
if result["started"]:
|
||||
logger.info(f"Started encoding worker VM: {result['vm_name']}")
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to warm up encoding worker: {e}")
|
||||
return {"started": False, "error": str(e)}
|
||||
|
||||
|
||||
@router.post("/heartbeat")
|
||||
async def heartbeat_encoding_worker(
|
||||
_admin=Depends(require_admin),
|
||||
manager=Depends(get_worker_manager),
|
||||
):
|
||||
"""Update activity timestamp to prevent idle shutdown."""
|
||||
try:
|
||||
manager.update_activity()
|
||||
return {"status": "ok"}
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update encoding worker heartbeat: {e}")
|
||||
return {"status": "error", "error": str(e)}
|
||||
@@ -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
|
||||
# ============================================================================
|
||||
@@ -115,6 +162,9 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
# Audio editing
|
||||
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
|
||||
|
||||
|
||||
class CreateJobFromUrlResponse(BaseModel):
|
||||
"""Response from creating a job from URL."""
|
||||
@@ -218,10 +268,10 @@ storage_service = StorageService()
|
||||
worker_service = get_worker_service()
|
||||
|
||||
|
||||
def extract_request_metadata(request: Request, created_from: str = "upload") -> Dict[str, Any]:
|
||||
def extract_request_metadata(request: Request, created_from: str = "upload", auth_result=None) -> Dict[str, Any]:
|
||||
"""
|
||||
Extract metadata from a FastAPI Request for job tracking.
|
||||
|
||||
|
||||
Captures:
|
||||
- Client IP address (handles X-Forwarded-For for proxies)
|
||||
- User-Agent header
|
||||
@@ -230,34 +280,36 @@ def extract_request_metadata(request: Request, created_from: str = "upload") ->
|
||||
- All custom X-* headers
|
||||
- Server version
|
||||
- Creation source (upload/url)
|
||||
|
||||
- Auth context (method, user type) if auth_result provided
|
||||
|
||||
Args:
|
||||
request: FastAPI Request object
|
||||
created_from: How the job was created ("upload" or "url")
|
||||
|
||||
auth_result: Optional AuthResult from authentication
|
||||
|
||||
Returns:
|
||||
Dict with metadata fields for storage in job.request_metadata
|
||||
"""
|
||||
headers = dict(request.headers)
|
||||
|
||||
|
||||
# Extract client IP (check X-Forwarded-For for proxy scenarios)
|
||||
client_ip = headers.get('x-forwarded-for', '').split(',')[0].strip()
|
||||
if not client_ip and request.client:
|
||||
client_ip = request.client.host
|
||||
|
||||
|
||||
# Extract standard headers
|
||||
user_agent = headers.get('user-agent', '')
|
||||
environment = headers.get('x-environment', '') # test, production, development
|
||||
client_id = headers.get('x-client-id', '') # Customer/user identifier
|
||||
|
||||
|
||||
# Collect all X-* custom headers (excluding standard ones we already captured)
|
||||
custom_headers = {}
|
||||
for key, value in headers.items():
|
||||
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
|
||||
# Normalize header name to original casing if possible
|
||||
custom_headers[key] = value
|
||||
|
||||
return {
|
||||
|
||||
metadata = {
|
||||
'client_ip': client_ip,
|
||||
'user_agent': user_agent,
|
||||
'environment': environment,
|
||||
@@ -267,6 +319,17 @@ def extract_request_metadata(request: Request, created_from: str = "upload") ->
|
||||
'custom_headers': custom_headers,
|
||||
}
|
||||
|
||||
# Add auth context for abuse investigation and analytics
|
||||
if auth_result is not None:
|
||||
metadata['auth_method'] = getattr(auth_result, 'auth_method', None)
|
||||
user_type = getattr(auth_result, 'user_type', None)
|
||||
metadata['user_type'] = user_type.value if hasattr(user_type, 'value') else str(user_type) if user_type else None
|
||||
remaining = getattr(auth_result, 'remaining_uses', None)
|
||||
if remaining is not None:
|
||||
metadata['credits_at_creation'] = remaining
|
||||
|
||||
return metadata
|
||||
|
||||
|
||||
# File extension validation
|
||||
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.flac', '.m4a', '.ogg', '.aac'}
|
||||
@@ -381,6 +444,8 @@ async def upload_and_create_job(
|
||||
non_interactive: bool = Form(False, description="Skip interactive steps (lyrics review, instrumental selection)"),
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
|
||||
# Audio editing
|
||||
requires_audio_edit: bool = Form(False, description="Pause after download for user to edit input audio"),
|
||||
):
|
||||
"""
|
||||
Upload an audio file and create a karaoke generation job with full style configuration.
|
||||
@@ -510,9 +575,9 @@ 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")
|
||||
request_metadata = extract_request_metadata(request, created_from="upload", auth_result=auth_result)
|
||||
|
||||
# Parse color_overrides from JSON if provided
|
||||
parsed_color_overrides: Dict[str, str] = {}
|
||||
@@ -534,6 +599,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,16 +671,25 @@ 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")
|
||||
|
||||
logger.info(f"Created job {job_id} for {artist} - {title}")
|
||||
|
||||
# Store requires_audio_edit flag in state_data
|
||||
if requires_audio_edit:
|
||||
job_manager.update_state_data(job_id, 'requires_audio_edit', True)
|
||||
|
||||
# If theme is set and no custom style files are being uploaded, prepare theme style now
|
||||
# This copies the theme's style_params.json to the job folder so LyricsTranscriber
|
||||
# can access the style configuration for preview videos
|
||||
@@ -640,7 +722,7 @@ async def upload_and_create_job(
|
||||
|
||||
# Upload style files if provided
|
||||
if style_params:
|
||||
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
|
||||
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
|
||||
logger.info(f"Uploading style params to GCS: {style_gcs_path}")
|
||||
storage_service.upload_fileobj(
|
||||
style_params.file,
|
||||
@@ -659,7 +741,7 @@ async def upload_and_create_job(
|
||||
(style_cdg_outro_background, "cdg_outro_background"),
|
||||
]:
|
||||
if img_file:
|
||||
gcs_path = f"uploads/{job_id}/style/{asset_key}{Path(img_file.filename).suffix.lower()}"
|
||||
gcs_path = f"jobs/{job_id}/style/{asset_key}{Path(img_file.filename).suffix.lower()}"
|
||||
logger.info(f"Uploading {asset_key} to GCS: {gcs_path}")
|
||||
storage_service.upload_fileobj(
|
||||
img_file.file,
|
||||
@@ -670,7 +752,7 @@ async def upload_and_create_job(
|
||||
|
||||
# Upload font file
|
||||
if style_font:
|
||||
font_gcs_path = f"uploads/{job_id}/style/font{Path(style_font.filename).suffix.lower()}"
|
||||
font_gcs_path = f"jobs/{job_id}/style/font{Path(style_font.filename).suffix.lower()}"
|
||||
logger.info(f"Uploading font to GCS: {font_gcs_path}")
|
||||
storage_service.upload_fileobj(
|
||||
style_font.file,
|
||||
@@ -994,11 +1076,11 @@ def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
|
||||
if file_type == 'audio':
|
||||
return f"uploads/{job_id}/audio/{filename}"
|
||||
elif file_type == 'style_params':
|
||||
return f"uploads/{job_id}/style/style_params.json"
|
||||
return f"jobs/{job_id}/style/style_params.json"
|
||||
elif file_type.startswith('style_'):
|
||||
# Map style_intro_background -> intro_background, etc.
|
||||
asset_key = file_type.replace('style_', '')
|
||||
return f"uploads/{job_id}/style/{asset_key}{ext}"
|
||||
return f"jobs/{job_id}/style/{asset_key}{ext}"
|
||||
elif file_type == 'lyrics_file':
|
||||
return f"uploads/{job_id}/lyrics/user_lyrics{ext}"
|
||||
elif file_type == 'existing_instrumental':
|
||||
@@ -1077,12 +1159,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 +1191,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})")
|
||||
@@ -1109,20 +1208,11 @@ async def create_job_with_upload_urls(
|
||||
)
|
||||
|
||||
# Extract request metadata for tracking
|
||||
request_metadata = extract_request_metadata(request, created_from="signed_url_upload")
|
||||
request_metadata = extract_request_metadata(request, created_from="signed_url_upload", auth_result=auth_result)
|
||||
|
||||
# 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 +1251,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")
|
||||
|
||||
@@ -1278,10 +1373,10 @@ async def mark_uploads_complete(
|
||||
if file_type == 'audio':
|
||||
prefix = f"uploads/{job_id}/audio/"
|
||||
elif file_type == 'style_params':
|
||||
prefix = f"uploads/{job_id}/style/style_params"
|
||||
prefix = f"jobs/{job_id}/style/style_params"
|
||||
elif file_type.startswith('style_'):
|
||||
asset_key = file_type.replace('style_', '')
|
||||
prefix = f"uploads/{job_id}/style/{asset_key}"
|
||||
prefix = f"jobs/{job_id}/style/{asset_key}"
|
||||
elif file_type == 'lyrics_file':
|
||||
prefix = f"uploads/{job_id}/lyrics/user_lyrics"
|
||||
elif file_type == 'existing_instrumental':
|
||||
@@ -1510,6 +1605,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,
|
||||
@@ -1555,7 +1676,7 @@ async def create_job_from_url(
|
||||
)
|
||||
|
||||
# Extract request metadata for tracking
|
||||
request_metadata = extract_request_metadata(request, created_from="url")
|
||||
request_metadata = extract_request_metadata(request, created_from="url", auth_result=auth_result)
|
||||
|
||||
# Use provided artist/title or leave as None (will be auto-detected by audio worker)
|
||||
artist = body.artist
|
||||
@@ -1607,11 +1728,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")
|
||||
|
||||
@@ -1630,6 +1756,10 @@ async def create_job_from_url(
|
||||
job_manager.update_job(job_id, update_data)
|
||||
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
|
||||
|
||||
# Store requires_audio_edit flag in state_data
|
||||
if body.requires_audio_edit:
|
||||
job_manager.update_state_data(job_id, 'requires_audio_edit', True)
|
||||
|
||||
logger.info(f"Created URL-based job {job_id} for URL: {body.url}")
|
||||
if artist:
|
||||
logger.info(f" Artist: {artist}")
|
||||
@@ -1740,7 +1870,7 @@ def _get_gcs_path_for_finalise_file(job_id: str, file_type: str, filename: str)
|
||||
elif file_type == 'corrections':
|
||||
return f"jobs/{job_id}/lyrics/corrections.json"
|
||||
elif file_type == 'style_params':
|
||||
return f"uploads/{job_id}/style/style_params.json"
|
||||
return f"jobs/{job_id}/style/style_params.json"
|
||||
else:
|
||||
return f"uploads/{job_id}/other/{filename}"
|
||||
|
||||
@@ -1866,7 +1996,7 @@ async def create_finalise_only_job(
|
||||
)
|
||||
|
||||
# Extract request metadata
|
||||
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload")
|
||||
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload", auth_result=auth_result)
|
||||
|
||||
# Apply default theme if none specified
|
||||
# This ensures all karaoke videos use the Nomad theme by default
|
||||
@@ -1909,11 +2039,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")
|
||||
|
||||
@@ -2067,7 +2202,7 @@ async def mark_finalise_uploads_complete(
|
||||
elif file_type == 'corrections':
|
||||
prefix = f"jobs/{job_id}/lyrics/corrections"
|
||||
elif file_type == 'style_params':
|
||||
prefix = f"uploads/{job_id}/style/style_params"
|
||||
prefix = f"jobs/{job_id}/style/style_params"
|
||||
else:
|
||||
continue
|
||||
|
||||
@@ -2320,7 +2455,7 @@ async def complete_style_uploads(
|
||||
continue
|
||||
|
||||
asset_key = file_type.replace('style_', '')
|
||||
prefix = f"uploads/{job_id}/style/{asset_key}"
|
||||
prefix = f"jobs/{job_id}/style/{asset_key}"
|
||||
files = storage_service.list_files(prefix)
|
||||
if not files:
|
||||
raise HTTPException(
|
||||
@@ -2351,7 +2486,7 @@ async def complete_style_uploads(
|
||||
|
||||
# Overwrite background paths with custom uploads
|
||||
for asset_key, gcs_path in new_style_assets.items():
|
||||
bucket_name = storage_service.bucket_name
|
||||
bucket_name = storage_service.bucket.name
|
||||
gcs_uri = f"gs://{bucket_name}/{gcs_path}"
|
||||
if asset_key == "intro_background" and "intro" in style_params:
|
||||
style_params["intro"]["background_image"] = gcs_uri
|
||||
@@ -2361,7 +2496,7 @@ async def complete_style_uploads(
|
||||
style_params["end"]["background_image"] = gcs_uri
|
||||
|
||||
# Upload updated style_params.json
|
||||
style_params_path = f"uploads/{job_id}/style/style_params.json"
|
||||
style_params_path = f"jobs/{job_id}/style/style_params.json"
|
||||
storage_service.upload_json(style_params_path, style_params)
|
||||
update_data["style_params_gcs_path"] = style_params_path
|
||||
|
||||
|
||||
@@ -308,6 +308,39 @@ async def flacfetch_health() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
Return the installed audio-separator package version.
|
||||
|
||||
Does NOT call the remote GPU service — that would cold-start an expensive
|
||||
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
|
||||
installed package version, which matches what the audio worker uses.
|
||||
|
||||
No authentication required.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
except Exception:
|
||||
pkg_version = None
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": pkg_version,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/detailed")
|
||||
async def detailed_health_check() -> Dict[str, Any]:
|
||||
"""
|
||||
|
||||
@@ -25,7 +25,7 @@ from backend.workers.screens_worker import generate_screens
|
||||
from backend.workers.video_worker import generate_video
|
||||
from backend.workers.render_video_worker import process_render_video
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.tracing import (
|
||||
extract_trace_context,
|
||||
@@ -76,6 +76,18 @@ def _check_worker_idempotency(job_id: str, worker_name: str) -> Optional[WorkerR
|
||||
message=f"Job {job_id} not found"
|
||||
)
|
||||
|
||||
# Reject workers for jobs in terminal states (failed, cancelled, complete)
|
||||
# This prevents Cloud Tasks retries from triggering workers on dead jobs
|
||||
terminal_statuses = {'failed', 'cancelled', 'complete', 'prep_complete', 'error'}
|
||||
job_status = job.status.value if hasattr(job.status, 'value') else str(job.status)
|
||||
if job_status in terminal_statuses:
|
||||
logger.info(f"[job:{job_id}] Job in terminal state '{job_status}', skipping {worker_name} worker")
|
||||
return WorkerResponse(
|
||||
status="skipped",
|
||||
job_id=job_id,
|
||||
message=f"Job is in terminal state '{job_status}', {worker_name} worker not needed"
|
||||
)
|
||||
|
||||
# Check worker-specific progress in state_data
|
||||
progress_key = f"{worker_name}_progress"
|
||||
worker_progress = job.state_data.get(progress_key, {})
|
||||
@@ -102,6 +114,31 @@ def _check_worker_idempotency(job_id: str, worker_name: str) -> Optional[WorkerR
|
||||
return None
|
||||
|
||||
|
||||
@router.post("/sync-disposable-domains", response_model=WorkerResponse)
|
||||
async def sync_disposable_domains_endpoint(
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Sync external disposable domain blocklist. Called by Cloud Scheduler daily."""
|
||||
import asyncio
|
||||
from backend.services.disposable_domain_sync_service import (
|
||||
fetch_external_blocklist, sync_disposable_domains
|
||||
)
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
|
||||
domains = await fetch_external_blocklist()
|
||||
db = get_firestore_client()
|
||||
result = await asyncio.to_thread(sync_disposable_domains, db, domains)
|
||||
EmailValidationService._blocklist_cache = None
|
||||
|
||||
return WorkerResponse(
|
||||
status="completed",
|
||||
job_id="sync-disposable-domains",
|
||||
message=f"Synced {result['external_count']} domains"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workers/audio", response_model=WorkerResponse)
|
||||
async def trigger_audio_worker(
|
||||
request: WorkerRequest,
|
||||
@@ -468,6 +505,44 @@ async def process_youtube_upload_queue(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/process-stale-reviews")
|
||||
async def process_stale_reviews_endpoint(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Process stale review jobs — send reminders and expire old ones.
|
||||
|
||||
Called by Cloud Scheduler (hourly). Can also be triggered manually
|
||||
from the admin dashboard.
|
||||
|
||||
- Jobs in review for >= 24h get a reminder email
|
||||
- Jobs in review for >= 48h are auto-cancelled with credit refund
|
||||
"""
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info("STALE_REVIEW_PROCESS starting")
|
||||
add_span_attribute("operation", "stale_review_process")
|
||||
|
||||
async def _process():
|
||||
try:
|
||||
result = await process_stale_reviews()
|
||||
logger.info(f"STALE_REVIEW_PROCESS complete: {result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"STALE_REVIEW_PROCESS failed: {e}")
|
||||
|
||||
background_tasks.add_task(_process)
|
||||
|
||||
add_span_event("stale_review_processing_started")
|
||||
return {
|
||||
"status": "started",
|
||||
"message": "Stale review processing started in background"
|
||||
}
|
||||
|
||||
|
||||
@router.post("/trigger-gdrive-validation")
|
||||
async def trigger_gdrive_validation_endpoint(
|
||||
http_request: Request,
|
||||
@@ -501,6 +576,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)
|
||||
|
||||
+496
-139
@@ -18,6 +18,7 @@ from typing import List, Optional, Dict, Any
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
|
||||
|
||||
from datetime import datetime
|
||||
from backend.utils.request_helpers import get_client_ip
|
||||
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
|
||||
from backend.models.requests import (
|
||||
URLSubmissionRequest,
|
||||
@@ -33,13 +34,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
|
||||
|
||||
|
||||
@@ -68,6 +71,7 @@ async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
@router.post("", response_model=JobResponse)
|
||||
async def create_job(
|
||||
request: URLSubmissionRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> JobResponse:
|
||||
@@ -130,9 +134,19 @@ async def create_job(
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
|
||||
# Store client IP on job for anti-abuse correlation
|
||||
creation_ip = get_client_ip(http_request)
|
||||
if creation_ip:
|
||||
FirestoreService().update_job(job.job_id, {"creation_ip": creation_ip})
|
||||
|
||||
# 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 +215,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 +605,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 +623,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 +645,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
|
||||
)
|
||||
|
||||
@@ -970,6 +1284,26 @@ async def complete_review(
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
)
|
||||
|
||||
# Check for 0-segment lyrics — fail early with user-friendly message
|
||||
# Only check when lyrics pipeline has run (lyrics_metadata exists in state_data)
|
||||
state_data = job.state_data or {}
|
||||
lyrics_metadata = state_data.get('lyrics_metadata')
|
||||
if lyrics_metadata is not None:
|
||||
segment_count = lyrics_metadata.get('segment_count', 0)
|
||||
corrected_lyrics = state_data.get('corrected_lyrics', {})
|
||||
corrected_segments = corrected_lyrics.get('corrected_segments', [])
|
||||
|
||||
if segment_count == 0 and len(corrected_segments) == 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"Cannot complete review: no lyrics were detected in the audio. "
|
||||
"This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). "
|
||||
"You can go back and paste lyrics manually using 'Replace All', "
|
||||
"or cancel this job and try again with an audio file that contains vocals."
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
# Store instrumental selection if provided (combined review flow)
|
||||
instrumental_selection = body.instrumental_selection if body else None
|
||||
@@ -1127,7 +1461,8 @@ DOWNLOAD_FILENAME_SUFFIXES = {
|
||||
"lossy_720p_mp4": " (Final Karaoke Lossy 720p).mp4",
|
||||
"cdg_zip": " (Final Karaoke CDG).zip",
|
||||
"txt_zip": " (Final Karaoke TXT).zip",
|
||||
"with_vocals": " (With Vocals).mkv",
|
||||
"with_vocals_mp4": " (With Vocals).mp4",
|
||||
"with_vocals": " (With Vocals).mkv", # legacy: raw MKV from render step
|
||||
}
|
||||
|
||||
|
||||
@@ -1213,9 +1548,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 +1559,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:
|
||||
@@ -1347,11 +1693,14 @@ async def retry_job(
|
||||
"retry_stage": "video_generation"
|
||||
}
|
||||
|
||||
# If we have corrections and screens but no video, retry render
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
file_urls.get('screens', {}).get('title')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections and screens, retrying from render stage")
|
||||
# If we have corrections, screens, AND review was completed, retry render
|
||||
# Review completion is proven by instrumental_selection in state_data
|
||||
# (set only when user submits the review endpoint)
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
file_urls.get('screens', {}).get('title') and
|
||||
state_data.get('instrumental_selection')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
|
||||
|
||||
# Clear error state and reset worker progress for idempotency
|
||||
job_manager.update_job(job_id, {
|
||||
@@ -1371,16 +1720,48 @@ async def retry_job(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
|
||||
# Trigger render video worker
|
||||
background_tasks.add_task(worker_service.trigger_render_video_worker, job_id)
|
||||
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "review_complete",
|
||||
"message": "Job retry started from render stage",
|
||||
"retry_stage": "render_video"
|
||||
}
|
||||
|
||||
# If we have corrections and screens but review was NOT completed,
|
||||
# return to awaiting_review so the user can review lyrics
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
file_urls.get('screens', {}).get('title')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
|
||||
|
||||
# Clear error state
|
||||
job_manager.update_job(job_id, {
|
||||
'error_message': None,
|
||||
'error_details': None,
|
||||
})
|
||||
|
||||
# Transition to AWAITING_REVIEW so user can review lyrics
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_REVIEW,
|
||||
progress=55,
|
||||
message=f"Ready for review. Please review lyrics and select your instrumental."
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "awaiting_review",
|
||||
"message": "Job retry: returning to lyrics review (review was not completed before failure)",
|
||||
"retry_stage": "awaiting_review"
|
||||
}
|
||||
|
||||
# If we have stems and corrections, retry from screens generation
|
||||
elif (file_urls.get('stems', {}).get('instrumental_clean') and
|
||||
@@ -1460,16 +1841,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 +1859,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
|
||||
@@ -1861,6 +2148,7 @@ class CreateFromSearchRequest(BaseModel):
|
||||
display_artist: Optional[str] = Field(None, description="Display artist override for title screens/filenames")
|
||||
display_title: Optional[str] = Field(None, description="Display title override for title screens/filenames")
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only, no YouTube/GDrive")
|
||||
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
|
||||
|
||||
@validator('display_artist', 'display_title')
|
||||
def strip_whitespace(cls, v):
|
||||
@@ -1894,10 +2182,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 +2259,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")
|
||||
|
||||
@@ -2011,8 +2297,18 @@ async def create_job_from_search(
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Store client IP on job for anti-abuse correlation
|
||||
creation_ip = get_client_ip(request)
|
||||
if creation_ip:
|
||||
FirestoreService().update_job(job_id, {"creation_ip": creation_ip})
|
||||
|
||||
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)
|
||||
@@ -2040,6 +2336,8 @@ async def create_job_from_search(
|
||||
}
|
||||
if session.get('remote_search_id'):
|
||||
state_data_update['remote_search_id'] = session['remote_search_id']
|
||||
if body.requires_audio_edit:
|
||||
state_data_update['requires_audio_edit'] = True
|
||||
job_manager.update_job(job_id, {'state_data': state_data_update})
|
||||
|
||||
# Transition to DOWNLOADING_AUDIO (skips AWAITING_AUDIO_SELECTION entirely)
|
||||
@@ -2048,14 +2346,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 +2367,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:
|
||||
|
||||
@@ -49,12 +49,16 @@ class YouTubeQueueListResponse(BaseModel):
|
||||
|
||||
|
||||
class BlocklistsResponse(BaseModel):
|
||||
"""All blocklist data."""
|
||||
disposable_domains: List[str]
|
||||
"""All blocklist data with domain source separation."""
|
||||
external_domains: List[str]
|
||||
manual_domains: List[str]
|
||||
allowlisted_domains: List[str]
|
||||
blocked_emails: List[str]
|
||||
blocked_ips: List[str]
|
||||
updated_at: Optional[datetime]
|
||||
updated_by: Optional[str]
|
||||
last_sync_at: Optional[datetime] = None
|
||||
last_sync_count: Optional[int] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
updated_by: Optional[str] = None
|
||||
|
||||
|
||||
class DomainRequest(BaseModel):
|
||||
@@ -86,38 +90,10 @@ class SuccessResponse(BaseModel):
|
||||
async def get_blocklists(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Get all blocklist data.
|
||||
|
||||
Returns disposable domains, blocked emails, and blocked IPs.
|
||||
"""
|
||||
"""Get all blocklist data with domain source separation."""
|
||||
email_validation = get_email_validation_service()
|
||||
|
||||
# Force refresh to get latest data
|
||||
config = email_validation.get_blocklist_config(force_refresh=True)
|
||||
|
||||
# Get the raw document for metadata
|
||||
from google.cloud import firestore
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
from backend.services.email_validation_service import BLOCKLISTS_COLLECTION, BLOCKLIST_CONFIG_DOC
|
||||
|
||||
db = get_firestore_client()
|
||||
doc = db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC).get()
|
||||
|
||||
updated_at = None
|
||||
updated_by = None
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
updated_at = data.get("updated_at")
|
||||
updated_by = data.get("updated_by")
|
||||
|
||||
return BlocklistsResponse(
|
||||
disposable_domains=sorted(list(config["disposable_domains"])),
|
||||
blocked_emails=sorted(list(config["blocked_emails"])),
|
||||
blocked_ips=sorted(list(config["blocked_ips"])),
|
||||
updated_at=updated_at,
|
||||
updated_by=updated_by,
|
||||
)
|
||||
raw_data = email_validation.get_blocklist_raw_data()
|
||||
return BlocklistsResponse(**raw_data)
|
||||
|
||||
|
||||
@router.post("/blocklists/disposable-domains", response_model=SuccessResponse)
|
||||
@@ -158,6 +134,57 @@ async def remove_disposable_domain(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/blocklists/allowlisted-domains", response_model=SuccessResponse)
|
||||
async def add_allowlisted_domain(
|
||||
request: DomainRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Add a domain to the allowlist (overrides external blocklist)."""
|
||||
email_validation = get_email_validation_service()
|
||||
domain = request.domain.lower().strip()
|
||||
if not domain or "." not in domain:
|
||||
raise HTTPException(status_code=400, detail="Invalid domain format")
|
||||
email_validation.add_allowlisted_domain(domain, auth_result.user_email)
|
||||
return SuccessResponse(success=True, message=f"Domain '{domain}' added to allowlist")
|
||||
|
||||
|
||||
@router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse)
|
||||
async def remove_allowlisted_domain(
|
||||
domain: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Remove a domain from the allowlist."""
|
||||
email_validation = get_email_validation_service()
|
||||
domain = domain.lower().strip()
|
||||
if not email_validation.remove_allowlisted_domain(domain, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="Domain not found in allowlist")
|
||||
return SuccessResponse(success=True, message=f"Domain '{domain}' removed from allowlist")
|
||||
|
||||
|
||||
@router.post("/blocklists/sync", response_model=SuccessResponse)
|
||||
async def trigger_sync(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Manually trigger a sync of the external disposable domain blocklist."""
|
||||
import asyncio
|
||||
from backend.services.disposable_domain_sync_service import (
|
||||
fetch_external_blocklist, sync_disposable_domains
|
||||
)
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
|
||||
domains = await fetch_external_blocklist()
|
||||
db = get_firestore_client()
|
||||
result = await asyncio.to_thread(sync_disposable_domains, db, domains)
|
||||
|
||||
# Invalidate cache
|
||||
EmailValidationService._blocklist_cache = None
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Synced {result['external_count']} external domains ({result['added']} added, {result['removed']} removed)"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/blocklists/blocked-emails", response_model=SuccessResponse)
|
||||
async def add_blocked_email(
|
||||
request: EmailRequest,
|
||||
|
||||
@@ -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,867 @@ 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}
|
||||
|
||||
|
||||
# ============================================
|
||||
# Audio Edit Session Endpoints (backup/restore)
|
||||
# ============================================
|
||||
|
||||
|
||||
@router.post("/{job_id}/audio-edit-sessions")
|
||||
async def save_audio_edit_session(
|
||||
job_id: str,
|
||||
data: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""Save an audio edit session snapshot."""
|
||||
import hashlib
|
||||
import json as json_mod
|
||||
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
|
||||
|
||||
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_info[0] if isinstance(auth_info, tuple) else ""
|
||||
edit_data = data.get("edit_data", {})
|
||||
|
||||
# Compute hash for deduplication
|
||||
data_json = json_mod.dumps(edit_data, sort_keys=True, default=str)
|
||||
data_hash = hashlib.sha256(data_json.encode()).hexdigest()
|
||||
|
||||
# Skip if identical to most recent
|
||||
firestore_svc = FirestoreService()
|
||||
latest_hash = firestore_svc.get_latest_audio_edit_session_hash(job_id)
|
||||
if latest_hash == data_hash:
|
||||
return {"status": "skipped", "reason": "identical_data"}
|
||||
|
||||
# Build session
|
||||
summary_data = data.get("summary", {})
|
||||
session = AudioEditSession(
|
||||
job_id=job_id,
|
||||
user_email=user_email,
|
||||
edit_count=data.get("edit_count", 0),
|
||||
trigger=data.get("trigger", "auto"),
|
||||
audio_duration_seconds=summary_data.get("net_duration_seconds"),
|
||||
original_duration_seconds=data.get("original_duration_seconds"),
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
summary=AudioEditSessionSummary.from_dict(summary_data),
|
||||
data_hash=data_hash,
|
||||
)
|
||||
|
||||
# Upload edit_data to GCS
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/audio_edit_sessions/{session.session_id}.json"
|
||||
storage.upload_json(gcs_path, edit_data)
|
||||
session.edit_data_gcs_path = gcs_path
|
||||
|
||||
# Save metadata to Firestore
|
||||
firestore_svc.save_audio_edit_session(job_id, session)
|
||||
|
||||
return {
|
||||
"status": "saved",
|
||||
"session_id": session.session_id,
|
||||
"created_at": session.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio-edit-sessions")
|
||||
async def list_audio_edit_sessions(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""List all audio edit sessions for a job (metadata only)."""
|
||||
firestore_svc = FirestoreService()
|
||||
sessions = firestore_svc.list_audio_edit_sessions(job_id)
|
||||
return {
|
||||
"sessions": [s.to_dict() for s in sessions]
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio-edit-sessions/{session_id}")
|
||||
async def get_audio_edit_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""Get a single audio edit session with full edit_data loaded from GCS."""
|
||||
firestore_svc = FirestoreService()
|
||||
session = firestore_svc.get_audio_edit_session(job_id, session_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
result = session.to_dict()
|
||||
|
||||
# Load edit data from GCS
|
||||
if session.edit_data_gcs_path:
|
||||
try:
|
||||
storage = StorageService()
|
||||
result["edit_data"] = storage.download_json(session.edit_data_gcs_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not load audio edit data from GCS for session {session_id}: {e}")
|
||||
result["edit_data"] = None
|
||||
else:
|
||||
result["edit_data"] = None
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.delete("/{job_id}/audio-edit-sessions/{session_id}")
|
||||
async def delete_audio_edit_session(
|
||||
job_id: str,
|
||||
session_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""Delete an audio edit session (metadata + GCS data)."""
|
||||
firestore_svc = FirestoreService()
|
||||
session = firestore_svc.get_audio_edit_session(job_id, session_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
# Delete GCS data
|
||||
if session.edit_data_gcs_path:
|
||||
try:
|
||||
storage = StorageService()
|
||||
storage.delete_file(session.edit_data_gcs_path)
|
||||
except Exception:
|
||||
logger.warning(f"Could not delete GCS file for audio edit session {session_id}")
|
||||
|
||||
# Delete Firestore doc
|
||||
firestore_svc.delete_audio_edit_session(job_id, session_id)
|
||||
|
||||
return {"status": "deleted", "session_id": session_id}
|
||||
|
||||
|
||||
# ============================================
|
||||
# Audio Edit Endpoints
|
||||
# ============================================
|
||||
|
||||
|
||||
def _get_current_audio_gcs_path(job) -> str:
|
||||
"""Get the GCS path of the current audio (latest edit or original)."""
|
||||
state_data = job.state_data or {}
|
||||
edit_stack = state_data.get('audio_edit_stack', [])
|
||||
if edit_stack:
|
||||
return edit_stack[-1]['gcs_path']
|
||||
return job.input_media_gcs_path
|
||||
|
||||
|
||||
def _build_audio_edit_response(
|
||||
job_id: str,
|
||||
gcs_path: str,
|
||||
edit_stack: list,
|
||||
redo_stack: list,
|
||||
edit_id: str | None = None,
|
||||
) -> dict:
|
||||
"""Build a standard response for audio edit operations matching AudioEditResponse interface."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
analysis_service = AudioAnalysisService()
|
||||
transcoding_service = AudioTranscodingService()
|
||||
|
||||
# Get waveform data for current audio
|
||||
amplitudes, duration = analysis_service.get_waveform_data(
|
||||
gcs_audio_path=gcs_path,
|
||||
job_id=job_id,
|
||||
num_points=1000,
|
||||
)
|
||||
|
||||
# Get playback URL (OGG Opus)
|
||||
playback_url = transcoding_service.get_review_audio_url(gcs_path)
|
||||
|
||||
# Build flat response matching frontend AudioEditResponse interface
|
||||
response = {
|
||||
"status": "success",
|
||||
"duration_after": duration,
|
||||
"current_audio_url": playback_url,
|
||||
"waveform_data": {"amplitudes": list(amplitudes)},
|
||||
"edit_stack": [
|
||||
{
|
||||
"edit_id": entry.get("edit_id", ""),
|
||||
"operation": entry.get("operation", ""),
|
||||
"params": entry.get("params", {}),
|
||||
"duration_before": entry.get("duration_before", 0),
|
||||
"duration_after": entry.get("duration_after", entry.get("duration_seconds", 0)),
|
||||
"timestamp": entry.get("timestamp", ""),
|
||||
}
|
||||
for entry in edit_stack
|
||||
],
|
||||
"can_undo": len(edit_stack) > 0,
|
||||
"can_redo": len(redo_stack) > 0,
|
||||
}
|
||||
if edit_id is not None:
|
||||
response["edit_id"] = edit_id
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/{job_id}/input-audio-info")
|
||||
async def get_input_audio_info(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""
|
||||
Get metadata about the input audio for the audio editor UI.
|
||||
|
||||
Returns duration, waveform data, playback URL, and edit state.
|
||||
"""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
from backend.services.audio_edit_service import AudioEditService
|
||||
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if not job.input_media_gcs_path:
|
||||
raise HTTPException(status_code=404, detail="No input audio available")
|
||||
|
||||
try:
|
||||
edit_service = AudioEditService()
|
||||
analysis_service = AudioAnalysisService()
|
||||
transcoding_service = AudioTranscodingService()
|
||||
|
||||
state_data = job.state_data or {}
|
||||
edit_stack = state_data.get('audio_edit_stack', [])
|
||||
|
||||
# Try cached waveform first (pre-generated by download worker), fall back to on-demand
|
||||
waveform_cache_path = state_data.get('audio_edit_waveform_cache_path')
|
||||
cached = None
|
||||
if waveform_cache_path:
|
||||
cached = analysis_service.load_cached_waveform(waveform_cache_path)
|
||||
|
||||
if cached:
|
||||
orig_amplitudes, orig_duration = cached
|
||||
logger.info(f"Job {job_id}: Using cached waveform data")
|
||||
else:
|
||||
orig_amplitudes, orig_duration = analysis_service.get_waveform_data(
|
||||
gcs_audio_path=job.input_media_gcs_path,
|
||||
job_id=job_id,
|
||||
num_points=1000,
|
||||
)
|
||||
|
||||
original_playback_url = transcoding_service.get_review_audio_url(job.input_media_gcs_path)
|
||||
|
||||
# Determine current audio state
|
||||
current_duration = orig_duration
|
||||
current_audio_url = original_playback_url
|
||||
current_waveform = orig_amplitudes
|
||||
if edit_stack:
|
||||
current_gcs_path = edit_stack[-1]['gcs_path']
|
||||
current_waveform, current_duration = analysis_service.get_waveform_data(
|
||||
gcs_audio_path=current_gcs_path,
|
||||
job_id=job_id,
|
||||
num_points=1000,
|
||||
)
|
||||
current_audio_url = transcoding_service.get_review_audio_url(current_gcs_path)
|
||||
|
||||
# Return flat structure matching AudioEditInfo frontend interface
|
||||
result = {
|
||||
"job_id": job_id,
|
||||
"artist": job.artist,
|
||||
"title": job.title,
|
||||
"original_duration_seconds": orig_duration,
|
||||
"current_duration_seconds": current_duration,
|
||||
"original_audio_url": original_playback_url,
|
||||
"current_audio_url": current_audio_url,
|
||||
"waveform_data": {"amplitudes": list(current_waveform)},
|
||||
"original_waveform_data": {"amplitudes": list(orig_amplitudes)},
|
||||
"edit_stack": [
|
||||
{
|
||||
"edit_id": entry.get("edit_id", ""),
|
||||
"operation": entry.get("operation", ""),
|
||||
"params": entry.get("params", {}),
|
||||
"duration_before": entry.get("duration_before", 0),
|
||||
"duration_after": entry.get("duration_after", 0),
|
||||
"timestamp": entry.get("timestamp", ""),
|
||||
}
|
||||
for entry in edit_stack
|
||||
],
|
||||
"can_undo": len(edit_stack) > 0,
|
||||
"can_redo": len(state_data.get('audio_edit_redo_stack', [])) > 0,
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error getting input audio info: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error getting audio info: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{job_id}/audio-edit/apply")
|
||||
async def apply_audio_edit(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""
|
||||
Apply an edit operation to the input audio.
|
||||
|
||||
Supported operations: trim_start, trim_end, cut, mute, join_start, join_end.
|
||||
Returns updated waveform data and playback URL.
|
||||
"""
|
||||
import uuid
|
||||
from backend.services.audio_edit_service import AudioEditService
|
||||
|
||||
body = await request.json()
|
||||
operation = body.get("operation")
|
||||
params = body.get("params", {})
|
||||
edit_id = body.get("edit_id") or str(uuid.uuid4())
|
||||
|
||||
if not operation:
|
||||
raise HTTPException(status_code=400, detail="Missing 'operation' field")
|
||||
|
||||
valid_operations = {"trim_start", "trim_end", "cut", "mute", "join_start", "join_end"}
|
||||
if operation not in valid_operations:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid operation: {operation}. Valid: {valid_operations}")
|
||||
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
|
||||
# Transition to IN_AUDIO_EDIT if not already
|
||||
if job.status == JobStatus.AWAITING_AUDIO_EDIT:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.IN_AUDIO_EDIT,
|
||||
progress=15,
|
||||
message="Audio editing in progress"
|
||||
)
|
||||
|
||||
# Resolve upload_id to GCS path for join operations
|
||||
if operation in ("join_start", "join_end"):
|
||||
upload_id = params.get("upload_id")
|
||||
if not upload_id:
|
||||
raise HTTPException(status_code=400, detail="Missing 'upload_id' for join operation")
|
||||
state_data = job.state_data or {}
|
||||
uploads = state_data.get('audio_edit_uploads', {})
|
||||
upload_info = uploads.get(upload_id)
|
||||
if not upload_info:
|
||||
raise HTTPException(status_code=404, detail=f"Upload {upload_id} not found")
|
||||
params["upload_gcs_path"] = upload_info["gcs_path"]
|
||||
|
||||
try:
|
||||
edit_service = AudioEditService()
|
||||
|
||||
# Get current audio path and duration before edit
|
||||
state_data = job.state_data or {}
|
||||
existing_stack = state_data.get('audio_edit_stack', [])
|
||||
current_gcs_path = _get_current_audio_gcs_path(job)
|
||||
|
||||
# Determine duration before this edit
|
||||
if existing_stack:
|
||||
duration_before = existing_stack[-1].get('duration_seconds', 0)
|
||||
else:
|
||||
before_metadata = edit_service.get_metadata_from_gcs(current_gcs_path)
|
||||
duration_before = before_metadata.duration_seconds
|
||||
|
||||
output_gcs_path = f"jobs/{job_id}/audio_edit/edit_{edit_id}.flac"
|
||||
|
||||
# Apply the edit
|
||||
metadata, result_path = edit_service.apply_edit(
|
||||
input_gcs_path=current_gcs_path,
|
||||
operation=operation,
|
||||
params=params,
|
||||
output_gcs_path=output_gcs_path,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
# Update edit stack in state_data
|
||||
edit_stack = list(existing_stack)
|
||||
edit_stack.append({
|
||||
"edit_id": edit_id,
|
||||
"operation": operation,
|
||||
"params": {k: v for k, v in params.items() if k != "upload_gcs_path"},
|
||||
"gcs_path": result_path,
|
||||
"duration_before": duration_before,
|
||||
"duration_after": metadata.duration_seconds,
|
||||
"duration_seconds": metadata.duration_seconds,
|
||||
"timestamp": __import__("datetime").datetime.utcnow().isoformat(),
|
||||
})
|
||||
|
||||
# Clear redo stack on new edit
|
||||
updated_state_data = {
|
||||
**state_data,
|
||||
'audio_edit_stack': edit_stack,
|
||||
'audio_edit_redo_stack': [],
|
||||
}
|
||||
job_manager.update_job(job_id, {'state_data': updated_state_data})
|
||||
|
||||
return _build_audio_edit_response(
|
||||
job_id=job_id,
|
||||
gcs_path=result_path,
|
||||
edit_stack=edit_stack,
|
||||
redo_stack=[],
|
||||
edit_id=edit_id,
|
||||
)
|
||||
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error applying audio edit: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error applying edit: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{job_id}/audio-edit/undo")
|
||||
async def undo_audio_edit(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""Undo the last audio edit operation."""
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
|
||||
state_data = job.state_data or {}
|
||||
edit_stack = list(state_data.get('audio_edit_stack', []))
|
||||
redo_stack = list(state_data.get('audio_edit_redo_stack', []))
|
||||
|
||||
if not edit_stack:
|
||||
raise HTTPException(status_code=400, detail="Nothing to undo")
|
||||
|
||||
# Pop from edit stack, push to redo stack
|
||||
undone_edit = edit_stack.pop()
|
||||
redo_stack.append(undone_edit)
|
||||
|
||||
updated_state_data = {
|
||||
**state_data,
|
||||
'audio_edit_stack': edit_stack,
|
||||
'audio_edit_redo_stack': redo_stack,
|
||||
}
|
||||
job_manager.update_job(job_id, {'state_data': updated_state_data})
|
||||
|
||||
# Get the now-current audio (previous edit or original)
|
||||
current_gcs_path = edit_stack[-1]['gcs_path'] if edit_stack else job.input_media_gcs_path
|
||||
|
||||
try:
|
||||
return _build_audio_edit_response(
|
||||
job_id=job_id,
|
||||
gcs_path=current_gcs_path,
|
||||
edit_stack=edit_stack,
|
||||
redo_stack=redo_stack,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error building undo response: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error during undo: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{job_id}/audio-edit/redo")
|
||||
async def redo_audio_edit(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""Redo a previously undone audio edit."""
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
|
||||
state_data = job.state_data or {}
|
||||
edit_stack = list(state_data.get('audio_edit_stack', []))
|
||||
redo_stack = list(state_data.get('audio_edit_redo_stack', []))
|
||||
|
||||
if not redo_stack:
|
||||
raise HTTPException(status_code=400, detail="Nothing to redo")
|
||||
|
||||
# Pop from redo stack, push to edit stack
|
||||
redone_edit = redo_stack.pop()
|
||||
edit_stack.append(redone_edit)
|
||||
|
||||
updated_state_data = {
|
||||
**state_data,
|
||||
'audio_edit_stack': edit_stack,
|
||||
'audio_edit_redo_stack': redo_stack,
|
||||
}
|
||||
job_manager.update_job(job_id, {'state_data': updated_state_data})
|
||||
|
||||
current_gcs_path = edit_stack[-1]['gcs_path']
|
||||
|
||||
try:
|
||||
return _build_audio_edit_response(
|
||||
job_id=job_id,
|
||||
gcs_path=current_gcs_path,
|
||||
edit_stack=edit_stack,
|
||||
redo_stack=redo_stack,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error building redo response: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error during redo: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{job_id}/audio-edit/upload")
|
||||
async def upload_audio_for_join(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""
|
||||
Upload additional audio for join operations.
|
||||
|
||||
Accepts multipart form upload. Returns upload_id and metadata.
|
||||
"""
|
||||
import uuid
|
||||
from fastapi import UploadFile
|
||||
from backend.services.audio_edit_service import AudioEditService
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
|
||||
# Parse multipart form
|
||||
form = await request.form()
|
||||
file = form.get("file")
|
||||
if not file:
|
||||
raise HTTPException(status_code=400, detail="Missing 'file' in form data")
|
||||
|
||||
# Validate file extension
|
||||
filename = getattr(file, 'filename', 'unknown')
|
||||
valid_extensions = {'.flac', '.wav', '.mp3', '.m4a', '.ogg'}
|
||||
ext = os.path.splitext(filename)[1].lower()
|
||||
if ext not in valid_extensions:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid file type '{ext}'. Accepted: {', '.join(valid_extensions)}"
|
||||
)
|
||||
|
||||
upload_id = str(uuid.uuid4())
|
||||
gcs_path = f"jobs/{job_id}/audio_edit/upload_{upload_id}{ext}"
|
||||
|
||||
try:
|
||||
storage = StorageService()
|
||||
edit_service = AudioEditService()
|
||||
analysis_service = AudioAnalysisService()
|
||||
|
||||
# Save uploaded file to GCS
|
||||
content = await file.read()
|
||||
with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp:
|
||||
tmp.write(content)
|
||||
tmp_path = tmp.name
|
||||
|
||||
try:
|
||||
storage.upload_file(tmp_path, gcs_path)
|
||||
|
||||
# Get metadata
|
||||
metadata = edit_service.get_metadata(tmp_path)
|
||||
|
||||
# Get waveform data
|
||||
from karaoke_gen.instrumental_review import WaveformGenerator
|
||||
waveform_gen = WaveformGenerator()
|
||||
amplitudes, duration = waveform_gen.generate_data_only(
|
||||
audio_path=tmp_path,
|
||||
num_points=1000,
|
||||
)
|
||||
finally:
|
||||
os.unlink(tmp_path)
|
||||
|
||||
# Store upload info in state_data
|
||||
state_data = job.state_data or {}
|
||||
uploads = dict(state_data.get('audio_edit_uploads', {}))
|
||||
uploads[upload_id] = {
|
||||
"gcs_path": gcs_path,
|
||||
"duration_seconds": metadata.duration_seconds,
|
||||
"filename": filename,
|
||||
}
|
||||
updated_state_data = {**state_data, 'audio_edit_uploads': uploads}
|
||||
job_manager.update_job(job_id, {'state_data': updated_state_data})
|
||||
|
||||
return {
|
||||
"upload_id": upload_id,
|
||||
"duration_seconds": metadata.duration_seconds,
|
||||
"waveform_data": {
|
||||
"amplitudes": amplitudes,
|
||||
"duration": duration,
|
||||
},
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error uploading audio for join: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error uploading audio: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{job_id}/audio-edit/submit")
|
||||
async def submit_audio_edit(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""
|
||||
Finalize the audio edit and continue processing.
|
||||
|
||||
Copies the current edited audio to the job's input path,
|
||||
then triggers audio separation and lyrics transcription workers.
|
||||
"""
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
|
||||
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
|
||||
|
||||
state_data = job.state_data or {}
|
||||
edit_stack = state_data.get('audio_edit_stack', [])
|
||||
|
||||
storage = StorageService()
|
||||
|
||||
# Save edit log if provided
|
||||
body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
|
||||
edit_log = body.get("edit_log")
|
||||
if edit_log:
|
||||
edit_log_path = f"jobs/{job_id}/audio_edit/edit_log.json"
|
||||
storage.upload_json(edit_log_path, edit_log)
|
||||
logger.info(f"Job {job_id}: Saved audio edit log to {edit_log_path}")
|
||||
|
||||
if edit_stack:
|
||||
# Copy the latest edited audio to the canonical input path
|
||||
current_edited_path = edit_stack[-1]['gcs_path']
|
||||
edited_input_path = f"jobs/{job_id}/input/edited.flac"
|
||||
|
||||
# Download and re-upload to canonical path
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_path = os.path.join(temp_dir, "edited.flac")
|
||||
storage.download_file(current_edited_path, local_path)
|
||||
storage.upload_file(local_path, edited_input_path)
|
||||
|
||||
# Update job to use edited audio as input
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': edited_input_path,
|
||||
})
|
||||
logger.info(f"Job {job_id}: Audio edit submitted, using edited audio: {edited_input_path}")
|
||||
else:
|
||||
logger.info(f"Job {job_id}: Audio edit submitted with no edits, using original audio")
|
||||
|
||||
# Transition state
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AUDIO_EDIT_COMPLETE,
|
||||
progress=18,
|
||||
message="Audio edit complete, starting processing"
|
||||
)
|
||||
|
||||
# Trigger parallel workers in background so the HTTP response returns immediately.
|
||||
# The worker triggers involve Cloud Run Job calls that can take 30+ seconds;
|
||||
# waiting synchronously causes the browser request to time out.
|
||||
worker_service = get_worker_service()
|
||||
|
||||
async def _trigger_workers():
|
||||
try:
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to trigger workers after audio edit: {e}")
|
||||
|
||||
asyncio.create_task(_trigger_workers())
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Audio edit saved. Processing will continue with edited audio.",
|
||||
"job_id": job_id,
|
||||
"edits_applied": len(edit_stack),
|
||||
}
|
||||
+249
-39
@@ -10,6 +10,7 @@ Handles:
|
||||
"""
|
||||
import hashlib
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional, Tuple
|
||||
|
||||
@@ -34,6 +35,7 @@ def _mask_email(email: str) -> str:
|
||||
from fastapi import APIRouter, HTTPException, Depends, Request, Header
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
from backend.services.email_validation_service import get_email_validation_service
|
||||
from backend.models.user import (
|
||||
UserRole,
|
||||
UserPublic,
|
||||
@@ -57,6 +59,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 +68,8 @@ from backend.services.youtube_download_service import (
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
from backend.exceptions import InvalidStateTransitionError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.utils.request_helpers import get_client_ip
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -128,6 +133,32 @@ class LogoutResponse(BaseModel):
|
||||
# Magic Link Authentication
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def _precompute_credit_eval(token: str, email: str) -> None:
|
||||
"""Run credit evaluation in background and store result on magic link doc.
|
||||
|
||||
Called in a background thread after sending a magic link for new users.
|
||||
If the user clicks the link before this finishes, verify_magic_link falls
|
||||
back to inline evaluation (same as before this optimization).
|
||||
"""
|
||||
try:
|
||||
from backend.services.credit_evaluation_service import get_credit_evaluation_service
|
||||
from backend.services.user_service import get_user_service, MAGIC_LINKS_COLLECTION
|
||||
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(email, "welcome")
|
||||
|
||||
user_service = get_user_service()
|
||||
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
|
||||
"credit_eval_decision": evaluation.decision,
|
||||
"credit_eval_reasoning": evaluation.reasoning,
|
||||
"credit_eval_error": evaluation.error,
|
||||
})
|
||||
logger.info(f"Pre-computed credit eval for {_mask_email(email)}: {evaluation.decision}")
|
||||
except Exception:
|
||||
logger.exception(f"Background credit eval failed for {_mask_email(email)} — verify will compute inline")
|
||||
|
||||
|
||||
@router.post("/auth/magic-link", response_model=SendMagicLinkResponse)
|
||||
async def send_magic_link(
|
||||
request: SendMagicLinkRequest,
|
||||
@@ -145,6 +176,50 @@ async def send_magic_link(
|
||||
"""
|
||||
from backend.middleware.tenant import get_tenant_from_request, get_tenant_config_from_request
|
||||
|
||||
email = request.email.lower()
|
||||
|
||||
# Check for disposable email domains, blocked emails, and blocked IPs
|
||||
# (done before email service check so we can reject without needing email config)
|
||||
email_validation = get_email_validation_service()
|
||||
|
||||
if email_validation.is_disposable_domain(email):
|
||||
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="disposable_email_not_allowed"
|
||||
)
|
||||
|
||||
if email_validation.is_email_blocked(email):
|
||||
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
ip_address = get_client_ip(http_request)
|
||||
if ip_address and email_validation.is_ip_blocked(ip_address):
|
||||
logger.warning(f"Blocked IP signup attempt: {ip_address}")
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
# Per-IP and per-fingerprint signup rate limit (only for new users)
|
||||
device_fingerprint = request.device_fingerprint
|
||||
existing_user = user_service.get_user(email)
|
||||
if existing_user is None:
|
||||
if user_service.is_signup_rate_limited(
|
||||
ip_address=ip_address, device_fingerprint=device_fingerprint
|
||||
):
|
||||
logger.warning(
|
||||
f"Signup rate limit hit: IP={ip_address} for {_mask_email(email)}"
|
||||
)
|
||||
# Silent reject (anti-enumeration)
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
# Check if email service is configured
|
||||
if not email_service.is_configured():
|
||||
logger.error("Email service not configured - cannot send magic links")
|
||||
@@ -153,8 +228,6 @@ async def send_magic_link(
|
||||
detail="Email service is not available. Please contact support."
|
||||
)
|
||||
|
||||
email = request.email.lower()
|
||||
|
||||
# Get tenant context from middleware
|
||||
tenant_id = get_tenant_from_request(http_request)
|
||||
tenant_config = get_tenant_config_from_request(http_request)
|
||||
@@ -169,16 +242,16 @@ async def send_magic_link(
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
)
|
||||
|
||||
# Get client info for security logging
|
||||
ip_address = http_request.client.host if http_request.client else None
|
||||
# Get client info for security logging (ip_address already extracted above for blocklist check)
|
||||
user_agent = http_request.headers.get("user-agent")
|
||||
|
||||
# Create magic link token with tenant context
|
||||
# Create magic link token with tenant context and fingerprint
|
||||
magic_link = user_service.create_magic_link(
|
||||
email,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Get tenant-specific email configuration
|
||||
@@ -204,6 +277,17 @@ async def send_magic_link(
|
||||
# Don't reveal failure to prevent email enumeration
|
||||
# Still return success
|
||||
|
||||
# Pre-compute credit evaluation in background for new users.
|
||||
# By the time they check their email and click the link, the decision
|
||||
# will be ready and verification will be instant.
|
||||
if existing_user is None:
|
||||
thread = threading.Thread(
|
||||
target=_precompute_credit_eval,
|
||||
args=(magic_link.token, email),
|
||||
daemon=True,
|
||||
)
|
||||
thread.start()
|
||||
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
@@ -228,7 +312,7 @@ async def verify_magic_link(
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
|
||||
# Get client info
|
||||
ip_address = http_request.client.host if http_request.client else None
|
||||
ip_address = get_client_ip(http_request)
|
||||
user_agent = http_request.headers.get("user-agent")
|
||||
|
||||
# Check if this is a first login BEFORE verification (which sets last_login_at)
|
||||
@@ -251,12 +335,37 @@ async def verify_magic_link(
|
||||
if not success or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
# Create session with tenant context from the magic link
|
||||
# Grant welcome credits on first verification (with AI abuse evaluation)
|
||||
# Use pre-computed evaluation from magic link if available (computed at send time)
|
||||
precomputed_eval = None
|
||||
if magic_link_doc.exists:
|
||||
precomputed_eval = {
|
||||
k: magic_link_data.get(k)
|
||||
for k in ("credit_eval_decision", "credit_eval_reasoning", "credit_eval_error")
|
||||
if magic_link_data.get(k) is not None
|
||||
} or None
|
||||
|
||||
credits_granted = 0
|
||||
credit_status = "not_applicable" # returning user, not first login
|
||||
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
|
||||
user.email, precomputed_eval=precomputed_eval,
|
||||
)
|
||||
if granted:
|
||||
credits_granted = user_service.NEW_USER_FREE_CREDITS
|
||||
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
|
||||
# Refresh user to get updated credit balance
|
||||
user = user_service.get_user(user.email)
|
||||
elif credit_status == "denied":
|
||||
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
|
||||
|
||||
# Create session with tenant context and device fingerprint from the magic link
|
||||
magic_link_fingerprint = magic_link_data.get('device_fingerprint') if magic_link_doc.exists else None
|
||||
session = user_service.create_session(
|
||||
user.email,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=magic_link_tenant_id
|
||||
tenant_id=magic_link_tenant_id,
|
||||
device_fingerprint=magic_link_fingerprint,
|
||||
)
|
||||
|
||||
# Send welcome email to first-time users
|
||||
@@ -289,6 +398,8 @@ async def verify_magic_link(
|
||||
user=user_public,
|
||||
message="Successfully signed in",
|
||||
tenant_subdomain=tenant_subdomain,
|
||||
credits_granted=credits_granted,
|
||||
credit_status=credit_status,
|
||||
)
|
||||
|
||||
|
||||
@@ -577,6 +688,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)
|
||||
@@ -1059,7 +1175,7 @@ async def check_feedback_eligibility(
|
||||
eligible=eligible,
|
||||
has_submitted=user.has_submitted_feedback,
|
||||
jobs_completed=user.total_jobs_completed,
|
||||
credits_reward=2,
|
||||
credits_reward=1,
|
||||
)
|
||||
|
||||
|
||||
@@ -1070,7 +1186,7 @@ async def submit_user_feedback(
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Submit product feedback to earn 2 free credits.
|
||||
Submit product feedback to earn 1 free credit.
|
||||
|
||||
Requires authentication. Users must have completed 2+ jobs and
|
||||
not have already submitted feedback. At least one text field
|
||||
@@ -1148,8 +1264,59 @@ async def submit_user_feedback(
|
||||
has_submitted_feedback=True,
|
||||
)
|
||||
|
||||
# Grant 2 credits
|
||||
credits_granted = 2
|
||||
# AI evaluation before granting feedback credits
|
||||
credits_granted = 0
|
||||
feedback_content = {
|
||||
"overall_rating": request.overall_rating,
|
||||
"what_went_well": request.what_went_well,
|
||||
"what_could_improve": request.what_could_improve,
|
||||
"additional_comments": request.additional_comments,
|
||||
}
|
||||
try:
|
||||
from backend.services.credit_evaluation_service import get_credit_evaluation_service
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(user.email, "feedback", feedback_content)
|
||||
|
||||
if evaluation.decision == "deny":
|
||||
logger.info(f"Feedback credits denied for {_mask_email(user.email)}: {evaluation.reasoning}")
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_denied_email(user.email, "feedback")
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send credit denied email to {_mask_email(user.email)}")
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message="Thank you for your feedback! We appreciate your input.",
|
||||
credits_granted=0,
|
||||
)
|
||||
|
||||
if evaluation.decision == "pending_review":
|
||||
logger.info(f"Feedback credits pending review for {_mask_email(user.email)}: {evaluation.reasoning}")
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_review_needed_email(user.email, "feedback", evaluation.reasoning)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send review needed email for {_mask_email(user.email)}")
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message="Thank you for your feedback! Our team will review your account shortly.",
|
||||
credits_granted=0,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Credit evaluation failed for {_mask_email(user.email)} — pending review (fail-closed)")
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_review_needed_email(user.email, "feedback", "Evaluation error")
|
||||
except Exception:
|
||||
pass
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message="Thank you for your feedback! Our team will review your account shortly.",
|
||||
credits_granted=0,
|
||||
)
|
||||
|
||||
# Grant 1 credit (passed evaluation)
|
||||
credits_granted = 1
|
||||
user_service.add_credits(
|
||||
email=user.email,
|
||||
amount=credits_granted,
|
||||
@@ -1161,6 +1328,25 @@ async def submit_user_feedback(
|
||||
f"credits granted: {credits_granted}"
|
||||
)
|
||||
|
||||
# Send admin notification email (fire-and-forget)
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
email_service.send_feedback_notification(
|
||||
user_email=user.email,
|
||||
overall_rating=request.overall_rating,
|
||||
ease_of_use_rating=request.ease_of_use_rating,
|
||||
lyrics_accuracy_rating=request.lyrics_accuracy_rating,
|
||||
correction_experience_rating=request.correction_experience_rating,
|
||||
what_went_well=request.what_went_well,
|
||||
what_could_improve=request.what_could_improve,
|
||||
additional_comments=request.additional_comments,
|
||||
would_recommend=request.would_recommend,
|
||||
would_use_again=request.would_use_again,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to send feedback notification email: {e}")
|
||||
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message=f"Thank you for your feedback! You earned {credits_granted} free credits.",
|
||||
@@ -1194,9 +1380,17 @@ class UserDetailResponse(BaseModel):
|
||||
last_login_at: Optional[str] = None
|
||||
total_jobs_created: int = 0
|
||||
total_jobs_completed: int = 0
|
||||
total_spent: int = 0
|
||||
credit_transactions: list[dict] = []
|
||||
recent_jobs: list[dict] = []
|
||||
active_sessions_count: int = 0
|
||||
# Anti-abuse / identity info
|
||||
signup_ip: Optional[str] = None
|
||||
device_fingerprint: Optional[str] = None
|
||||
welcome_credits_granted: bool = False
|
||||
has_submitted_feedback: bool = False
|
||||
# Recent session details (IP, user agent, fingerprint)
|
||||
recent_sessions: list[dict] = []
|
||||
|
||||
|
||||
@router.get("/admin/users", response_model=UserListResponsePaginated)
|
||||
@@ -1237,6 +1431,7 @@ async def list_users(
|
||||
query = query.where(filter=FieldFilter('is_active', '==', True))
|
||||
|
||||
# Search by email prefix (case-insensitive via range query)
|
||||
search = search.strip() if search else None
|
||||
if search:
|
||||
search_lower = search.lower()
|
||||
# Use range query for prefix matching
|
||||
@@ -1244,16 +1439,23 @@ async def list_users(
|
||||
query = query.where(filter=FieldFilter('email', '<', search_lower + '\uffff'))
|
||||
|
||||
# Sorting
|
||||
direction = firestore.Query.DESCENDING if sort_order == "desc" else firestore.Query.ASCENDING
|
||||
if sort_by in ["created_at", "last_login_at", "credits", "email"]:
|
||||
query = query.order_by(sort_by, direction=direction)
|
||||
else:
|
||||
query = query.order_by("created_at", direction=direction)
|
||||
# When search is active, Firestore range filters on 'email' conflict with
|
||||
# order_by on a different field (requires composite index). Since we already
|
||||
# fetch all docs and paginate in Python, just sort in Python when searching.
|
||||
sort_field = sort_by if sort_by in ["created_at", "last_login_at", "credits", "email"] else "created_at"
|
||||
if not search:
|
||||
direction = firestore.Query.DESCENDING if sort_order == "desc" else firestore.Query.ASCENDING
|
||||
query = query.order_by(sort_field, direction=direction)
|
||||
|
||||
# Get all docs and filter in Python
|
||||
# Note: This is expensive for large datasets, consider caching
|
||||
all_docs = list(query.stream())
|
||||
|
||||
# Sort in Python when search is active (can't use Firestore order_by with range filter)
|
||||
if search:
|
||||
reverse = sort_order == "desc"
|
||||
all_docs.sort(key=lambda d: (d.to_dict().get(sort_field) is None, d.to_dict().get(sort_field)), reverse=reverse)
|
||||
|
||||
# Filter out test users if exclude_test is True
|
||||
if exclude_test:
|
||||
all_docs = [d for d in all_docs if not is_test_email(d.to_dict().get('email', ''))]
|
||||
@@ -1333,13 +1535,24 @@ async def get_user_detail(
|
||||
"created_at": created_at_str,
|
||||
})
|
||||
|
||||
# Count active sessions
|
||||
# Get active sessions with details
|
||||
sessions_query = db.collection("sessions").where(
|
||||
filter=FieldFilter("user_email", "==", email)
|
||||
).where(
|
||||
filter=FieldFilter("is_active", "==", True)
|
||||
)
|
||||
active_sessions_count = sum(1 for _ in sessions_query.stream())
|
||||
active_sessions = []
|
||||
for session_doc in sessions_query.stream():
|
||||
sd = session_doc.to_dict()
|
||||
created = sd.get("created_at")
|
||||
active_sessions.append({
|
||||
"ip_address": sd.get("ip_address"),
|
||||
"user_agent": sd.get("user_agent"),
|
||||
"device_fingerprint": sd.get("device_fingerprint"),
|
||||
"created_at": created.isoformat() if hasattr(created, 'isoformat') else str(created) if created else None,
|
||||
"last_activity_at": str(sd.get("last_activity_at", "")),
|
||||
})
|
||||
active_sessions_count = len(active_sessions)
|
||||
|
||||
# Format credit transactions
|
||||
credit_transactions = []
|
||||
@@ -1361,16 +1574,22 @@ async def get_user_detail(
|
||||
last_login_at=user.last_login_at.isoformat() if user.last_login_at else None,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
total_spent=user.total_spent,
|
||||
credit_transactions=credit_transactions,
|
||||
recent_jobs=recent_jobs,
|
||||
active_sessions_count=active_sessions_count,
|
||||
signup_ip=user.signup_ip,
|
||||
device_fingerprint=user.device_fingerprint,
|
||||
welcome_credits_granted=user.welcome_credits_granted,
|
||||
has_submitted_feedback=user.has_submitted_feedback,
|
||||
recent_sessions=active_sessions,
|
||||
)
|
||||
|
||||
|
||||
@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 +1598,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 +1626,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 +1645,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 +1664,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 +1672,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 +1689,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)
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Cloud Build config for GPU base image
|
||||
#
|
||||
# Builds the CUDA + PyTorch + models base image used by the audio worker.
|
||||
# This image is large (~10GB) so builds take 15-30 minutes.
|
||||
#
|
||||
# Trigger manually:
|
||||
# gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
|
||||
#
|
||||
# The app-layer Dockerfile uses this as its BASE_IMAGE for audio worker deploys.
|
||||
|
||||
steps:
|
||||
- name: 'gcr.io/cloud-builders/docker'
|
||||
args:
|
||||
- 'build'
|
||||
- '-f'
|
||||
- 'backend/Dockerfile.gpu-base'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- '--build-arg'
|
||||
- 'BUILD_DATE=$_BUILD_DATE'
|
||||
- '--build-arg'
|
||||
- 'BUILD_ID=$BUILD_ID'
|
||||
- '.'
|
||||
|
||||
images:
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
|
||||
timeout: '3600s'
|
||||
|
||||
options:
|
||||
machineType: 'E2_HIGHCPU_32'
|
||||
diskSizeGb: 100
|
||||
@@ -57,6 +57,12 @@ class Settings(BaseSettings):
|
||||
# use uncorrected transcription - human review will fix any issues.
|
||||
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
|
||||
|
||||
# AI Credit Evaluation (anti-abuse gating for free credits)
|
||||
# When enabled, welcome and feedback credit grants are evaluated by Gemini
|
||||
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
|
||||
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
|
||||
|
||||
# Cloud Tasks (for scalable worker coordination)
|
||||
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
|
||||
# When disabled (default), workers are triggered via direct HTTP (for development)
|
||||
|
||||
+2
-1
@@ -7,7 +7,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
@@ -153,6 +153,7 @@ app.include_router(health.router, prefix="/api")
|
||||
app.include_router(jobs.router, prefix="/api")
|
||||
app.include_router(file_upload.router, prefix="/api") # File upload endpoint
|
||||
app.include_router(internal.router, prefix="/api") # Internal worker endpoints
|
||||
app.include_router(encoding_worker.router, prefix="/api") # Encoding worker lifecycle
|
||||
app.include_router(review.router, prefix="/api") # Review UI compatibility endpoints
|
||||
app.include_router(auth.router, prefix="/api") # OAuth credential management
|
||||
app.include_router(audio_search.router, prefix="/api") # Audio search (artist+title mode)
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
Audio edit session model for persisting input audio editing progress.
|
||||
|
||||
Stored as a Firestore subcollection: jobs/{job_id}/audio_edit_sessions/{session_id}
|
||||
Full edit 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 AudioEditSessionSummary:
|
||||
"""Compact summary of operations in an audio edit session, for list views."""
|
||||
total_operations: int = 0
|
||||
operations_breakdown: Dict[str, int] = field(default_factory=dict)
|
||||
duration_change_seconds: float = 0.0
|
||||
net_duration_seconds: float = 0.0
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"total_operations": self.total_operations,
|
||||
"operations_breakdown": self.operations_breakdown,
|
||||
"duration_change_seconds": self.duration_change_seconds,
|
||||
"net_duration_seconds": self.net_duration_seconds,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "AudioEditSessionSummary":
|
||||
return cls(
|
||||
total_operations=data.get("total_operations", 0),
|
||||
operations_breakdown=data.get("operations_breakdown", {}),
|
||||
duration_change_seconds=data.get("duration_change_seconds", 0.0),
|
||||
net_duration_seconds=data.get("net_duration_seconds", 0.0),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AudioEditSession:
|
||||
"""
|
||||
A saved snapshot of an audio editing session.
|
||||
|
||||
Stored at: jobs/{job_id}/audio_edit_sessions/{session_id}
|
||||
Edit data stored at: jobs/{job_id}/audio_edit_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" | "manual" | "submit"
|
||||
audio_duration_seconds: Optional[float] = None
|
||||
original_duration_seconds: Optional[float] = None
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
summary: AudioEditSessionSummary = field(default_factory=AudioEditSessionSummary)
|
||||
edit_data_gcs_path: str = ""
|
||||
|
||||
# Hash of the edit 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,
|
||||
"original_duration_seconds": self.original_duration_seconds,
|
||||
"artist": self.artist,
|
||||
"title": self.title,
|
||||
"summary": self.summary.to_dict(),
|
||||
"edit_data_gcs_path": self.edit_data_gcs_path,
|
||||
"data_hash": self.data_hash,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "AudioEditSession":
|
||||
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 = AudioEditSessionSummary.from_dict(summary_data) if isinstance(summary_data, dict) else AudioEditSessionSummary()
|
||||
|
||||
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"),
|
||||
original_duration_seconds=data.get("original_duration_seconds"),
|
||||
artist=data.get("artist"),
|
||||
title=data.get("title"),
|
||||
summary=summary,
|
||||
edit_data_gcs_path=data.get("edit_data_gcs_path", ""),
|
||||
data_hash=data.get("data_hash", ""),
|
||||
)
|
||||
+69
-8
@@ -16,8 +16,9 @@ class JobStatus(str, Enum):
|
||||
"""
|
||||
Job status enumeration - Complete state machine.
|
||||
|
||||
The workflow has 7 main stages with 2 human interaction points:
|
||||
The workflow has 8 main stages with up to 3 human interaction points:
|
||||
1. Input & Setup (may include audio source selection)
|
||||
1b. Optional Audio Editing (BLOCKING) - trim/cut/mute/join input audio
|
||||
2. Parallel Processing (audio + lyrics)
|
||||
3. Title/End Screen Generation + Backing Vocals Analysis
|
||||
4. Countdown Padding Synchronization
|
||||
@@ -39,6 +40,11 @@ class JobStatus(str, Enum):
|
||||
|
||||
DOWNLOADING = "downloading" # Downloading from URL or processing upload
|
||||
|
||||
# Optional: Audio editing (before processing begins)
|
||||
AWAITING_AUDIO_EDIT = "awaiting_audio_edit" # ⚠️ WAITING FOR USER - edit input audio
|
||||
IN_AUDIO_EDIT = "in_audio_edit" # User is actively editing audio
|
||||
AUDIO_EDIT_COMPLETE = "audio_edit_complete" # User submitted edited audio
|
||||
|
||||
# Stage 2a: Audio separation (parallel track 1)
|
||||
SEPARATING_STAGE1 = "separating_stage1" # Clean instrumental separation (Modal API)
|
||||
SEPARATING_STAGE2 = "separating_stage2" # Backing vocals separation (Modal API)
|
||||
@@ -103,7 +109,13 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
|
||||
|
||||
# DOWNLOADING allows parallel processing (audio + lyrics) and then screens when both complete
|
||||
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
# Can also enter optional audio edit phase if requires_audio_edit flag is set
|
||||
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.FAILED],
|
||||
|
||||
# Optional audio edit phase (trim, cut, mute, join input audio before processing)
|
||||
JobStatus.AWAITING_AUDIO_EDIT: [JobStatus.IN_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.IN_AUDIO_EDIT: [JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
|
||||
# Audio separation flow
|
||||
JobStatus.SEPARATING_STAGE1: [JobStatus.SEPARATING_STAGE2, JobStatus.FAILED],
|
||||
@@ -142,13 +154,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 +169,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 +191,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 +238,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 +318,12 @@ 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)
|
||||
|
||||
# Anti-abuse: IP address at job creation time (for cross-account correlation)
|
||||
creation_ip: Optional[str] = None
|
||||
|
||||
# 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 +331,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
|
||||
@@ -400,6 +424,43 @@ class Job(BaseModel):
|
||||
}
|
||||
"""
|
||||
|
||||
# Processing metadata (immutable provenance data written by workers during processing)
|
||||
processing_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
Immutable processing provenance data. Written once by each worker during processing.
|
||||
Never modified after initial write. Used for analytics, debugging, and data export.
|
||||
|
||||
Structure:
|
||||
{
|
||||
"transcription": {
|
||||
"provider": "audioshake",
|
||||
"audioshake_task_id": "...",
|
||||
"audioshake_asset_id": "...",
|
||||
"language_detected": "en",
|
||||
"word_count": 358,
|
||||
"segment_count": 42,
|
||||
},
|
||||
"correction": {
|
||||
"handlers_applied": [...],
|
||||
"corrections_made": 12,
|
||||
"correction_ratio": 0.034,
|
||||
"reference_sources_found": ["genius", "spotify"],
|
||||
"agentic_routing": "rule-based",
|
||||
"duration_seconds": 33.2,
|
||||
},
|
||||
"separation": {
|
||||
"provider": "modal",
|
||||
"clean_model": "...",
|
||||
"duration_seconds": 420.5,
|
||||
},
|
||||
"timing": {
|
||||
"lyrics_worker_seconds": 125.3,
|
||||
"audio_worker_seconds": 420.5,
|
||||
...
|
||||
},
|
||||
}
|
||||
"""
|
||||
|
||||
# Request metadata (captured at job creation for tracking and filtering)
|
||||
request_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
@@ -528,8 +589,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"
|
||||
)
|
||||
|
||||
+24
-2
@@ -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
|
||||
|
||||
@@ -93,6 +98,13 @@ class User(BaseModel):
|
||||
# Feedback-for-credits program
|
||||
has_submitted_feedback: bool = False
|
||||
|
||||
# Anti-abuse: IP address and device fingerprint used during signup
|
||||
signup_ip: Optional[str] = None
|
||||
device_fingerprint: Optional[str] = None
|
||||
|
||||
# Flag to prevent duplicate welcome credit grants (idempotency)
|
||||
welcome_credits_granted: bool = False
|
||||
|
||||
|
||||
class MagicLinkToken(BaseModel):
|
||||
"""
|
||||
@@ -112,10 +124,16 @@ class MagicLinkToken(BaseModel):
|
||||
used_at: Optional[datetime] = None
|
||||
ip_address: Optional[str] = None
|
||||
user_agent: Optional[str] = None
|
||||
device_fingerprint: Optional[str] = None
|
||||
|
||||
# Multi-tenant support (None = default Nomad Karaoke)
|
||||
tenant_id: Optional[str] = None
|
||||
|
||||
# Pre-computed credit evaluation (set asynchronously after magic link is sent)
|
||||
credit_eval_decision: Optional[str] = None # "grant", "deny", "pending_review"
|
||||
credit_eval_reasoning: Optional[str] = None
|
||||
credit_eval_error: Optional[str] = None
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
"""
|
||||
@@ -133,6 +151,7 @@ class Session(BaseModel):
|
||||
last_activity_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
ip_address: Optional[str] = None
|
||||
user_agent: Optional[str] = None
|
||||
device_fingerprint: Optional[str] = None
|
||||
is_active: bool = True
|
||||
|
||||
# Multi-tenant support (None = default Nomad Karaoke)
|
||||
@@ -144,6 +163,7 @@ class Session(BaseModel):
|
||||
class SendMagicLinkRequest(BaseModel):
|
||||
"""Request to send a magic link email."""
|
||||
email: str
|
||||
device_fingerprint: Optional[str] = None
|
||||
|
||||
|
||||
class SendMagicLinkResponse(BaseModel):
|
||||
@@ -164,6 +184,8 @@ class VerifyMagicLinkResponse(BaseModel):
|
||||
user: "UserPublic"
|
||||
message: str
|
||||
tenant_subdomain: Optional[str] = None
|
||||
credits_granted: int = 0
|
||||
credit_status: str = "not_applicable" # "granted", "denied", "pending_review", "already_granted", "not_applicable"
|
||||
|
||||
|
||||
class UserPublic(BaseModel):
|
||||
@@ -212,7 +234,7 @@ class UserFeedback(BaseModel):
|
||||
Feedback from any user (not just beta testers).
|
||||
|
||||
Stored in Firestore 'user_feedback' collection.
|
||||
Users earn 2 free credits for submitting detailed feedback.
|
||||
Users earn 1 free credit for submitting detailed feedback.
|
||||
"""
|
||||
id: str
|
||||
user_email: str
|
||||
@@ -267,4 +289,4 @@ class FeedbackEligibilityResponse(BaseModel):
|
||||
eligible: bool
|
||||
has_submitted: bool
|
||||
jobs_completed: int
|
||||
credits_reward: int = 2
|
||||
credits_reward: int = 1
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Download ensemble preset models at Docker build time.
|
||||
|
||||
Bakes models into the image so they're available immediately at runtime,
|
||||
avoiding cold-start model download latency in Cloud Run Jobs.
|
||||
|
||||
Usage: python backend/scripts/download_models.py /models
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import logging
|
||||
import importlib.resources as resources
|
||||
from audio_separator.separator import Separator
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Presets to bake into the GPU image
|
||||
PRESETS_TO_DOWNLOAD = ["instrumental_clean", "karaoke"]
|
||||
|
||||
|
||||
def download_preset_models(model_dir: str) -> None:
|
||||
"""Download all models for the configured presets individually.
|
||||
|
||||
Ensemble presets resolve to multiple model filenames. We must download
|
||||
each model individually via load_model(model_filename) — calling
|
||||
load_model() with no args on an ensemble preset doesn't trigger downloads.
|
||||
"""
|
||||
with resources.open_text("audio_separator", "ensemble_presets.json") as f:
|
||||
presets = json.load(f)["presets"]
|
||||
|
||||
models_to_download = set()
|
||||
for preset_name in PRESETS_TO_DOWNLOAD:
|
||||
models_to_download.update(presets[preset_name]["models"])
|
||||
|
||||
logger.info(f"Downloading {len(models_to_download)} models for presets: {PRESETS_TO_DOWNLOAD}")
|
||||
for model in sorted(models_to_download):
|
||||
logger.info(f" Downloading: {model}")
|
||||
sep = Separator(model_file_dir=model_dir)
|
||||
sep.load_model(model)
|
||||
logger.info(f" Done: {model}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
model_dir = sys.argv[1] if len(sys.argv) > 1 else "/models"
|
||||
download_preset_models(model_dir)
|
||||
logger.info(f"All preset models downloaded to {model_dir}")
|
||||
@@ -5,6 +5,7 @@ This service wraps the shared karaoke_gen.instrumental_review module
|
||||
to provide GCS-integrated audio analysis capabilities.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
@@ -187,7 +188,78 @@ class AudioAnalysisService:
|
||||
)
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
|
||||
def cache_waveform_data(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
cache_gcs_path: str,
|
||||
num_points: int = 1000,
|
||||
) -> tuple[list[float], float]:
|
||||
"""
|
||||
Generate waveform data and cache it as JSON in GCS.
|
||||
|
||||
Args:
|
||||
gcs_audio_path: Path to the audio file in GCS
|
||||
job_id: Job ID for logging
|
||||
cache_gcs_path: GCS path to store the cached waveform JSON
|
||||
num_points: Number of data points to generate
|
||||
|
||||
Returns:
|
||||
Tuple of (amplitude_values, duration_seconds)
|
||||
"""
|
||||
logger.info(f"[{job_id}] Generating and caching waveform data: {gcs_audio_path}")
|
||||
|
||||
amplitudes, duration = self.get_waveform_data(
|
||||
gcs_audio_path=gcs_audio_path,
|
||||
job_id=job_id,
|
||||
num_points=num_points,
|
||||
)
|
||||
|
||||
cache_data = {
|
||||
"amplitudes": list(amplitudes),
|
||||
"duration_seconds": duration,
|
||||
"num_points": num_points,
|
||||
"source_gcs_path": gcs_audio_path,
|
||||
}
|
||||
self.storage_service.upload_json(cache_gcs_path, cache_data)
|
||||
logger.info(f"[{job_id}] Waveform data cached at {cache_gcs_path}")
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
def load_cached_waveform(
|
||||
self,
|
||||
cache_gcs_path: str,
|
||||
) -> Optional[tuple[list[float], float]]:
|
||||
"""
|
||||
Load cached waveform data from GCS.
|
||||
|
||||
Args:
|
||||
cache_gcs_path: GCS path to the cached waveform JSON
|
||||
|
||||
Returns:
|
||||
Tuple of (amplitude_values, duration_seconds) or None if not found
|
||||
"""
|
||||
try:
|
||||
if not self.storage_service.file_exists(cache_gcs_path):
|
||||
return None
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_path = os.path.join(temp_dir, "waveform.json")
|
||||
self.storage_service.download_file(cache_gcs_path, local_path)
|
||||
with open(local_path) as f:
|
||||
data = json.load(f)
|
||||
|
||||
amplitudes = data.get("amplitudes", [])
|
||||
duration = data.get("duration_seconds", 0.0)
|
||||
if not amplitudes:
|
||||
return None
|
||||
|
||||
return amplitudes, duration
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to load cached waveform from {cache_gcs_path}: {e}")
|
||||
return None
|
||||
|
||||
def generate_waveform_with_mutes(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
"""
|
||||
Audio editing service — server-side FFmpeg operations for trim, cut, mute, join.
|
||||
|
||||
All operations are lossless (FLAC in, FLAC out). Playback URLs use OGG Opus
|
||||
via the existing AudioTranscodingService.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
from dataclasses import dataclass, asdict
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AudioMetadata:
|
||||
duration_seconds: float
|
||||
sample_rate: int
|
||||
channels: int
|
||||
format: str
|
||||
file_size_bytes: int
|
||||
|
||||
|
||||
class AudioEditService:
|
||||
"""Server-side audio editing via FFmpeg."""
|
||||
|
||||
def __init__(self, storage_service: StorageService | None = None):
|
||||
self.storage = storage_service or StorageService()
|
||||
|
||||
def get_metadata(self, audio_path: str) -> AudioMetadata:
|
||||
"""Get audio metadata from a local file using ffprobe."""
|
||||
cmd = [
|
||||
"ffprobe", "-v", "quiet", "-print_format", "json",
|
||||
"-show_format", "-show_streams", audio_path,
|
||||
]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"ffprobe failed: {result.stderr}")
|
||||
|
||||
info = json.loads(result.stdout)
|
||||
fmt = info.get("format", {})
|
||||
streams = info.get("streams", [])
|
||||
audio_stream = next((s for s in streams if s.get("codec_type") == "audio"), {})
|
||||
|
||||
return AudioMetadata(
|
||||
duration_seconds=float(fmt.get("duration", 0)),
|
||||
sample_rate=int(audio_stream.get("sample_rate", 44100)),
|
||||
channels=int(audio_stream.get("channels", 2)),
|
||||
format=fmt.get("format_name", "unknown"),
|
||||
file_size_bytes=int(fmt.get("size", 0)),
|
||||
)
|
||||
|
||||
def get_metadata_from_gcs(self, gcs_path: str) -> AudioMetadata:
|
||||
"""Download from GCS and get metadata."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_path = os.path.join(temp_dir, "audio")
|
||||
self.storage.download_file(gcs_path, local_path)
|
||||
return self.get_metadata(local_path)
|
||||
|
||||
def trim_start(self, input_path: str, end_seconds: float, output_path: str) -> AudioMetadata:
|
||||
"""Remove audio from 0 to end_seconds (skip the first N seconds)."""
|
||||
self._run_ffmpeg([
|
||||
"-ss", str(end_seconds),
|
||||
"-i", input_path,
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
def trim_end(self, input_path: str, start_seconds: float, output_path: str) -> AudioMetadata:
|
||||
"""Keep audio from 0 to start_seconds (remove from start_seconds to end)."""
|
||||
self._run_ffmpeg([
|
||||
"-i", input_path,
|
||||
"-t", str(start_seconds),
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
def cut_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
|
||||
"""Remove a region from start to end, joining the remaining parts."""
|
||||
self._run_ffmpeg([
|
||||
"-i", input_path,
|
||||
"-filter_complex",
|
||||
f"[0]atrim=0:{start},asetpts=PTS-STARTPTS[a];"
|
||||
f"[0]atrim={end},asetpts=PTS-STARTPTS[b];"
|
||||
f"[a][b]concat=n=2:v=0:a=1[out]",
|
||||
"-map", "[out]",
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
def mute_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
|
||||
"""Silence a region (preserve duration)."""
|
||||
self._run_ffmpeg([
|
||||
"-i", input_path,
|
||||
"-af", f"volume=enable='between(t,{start},{end})':volume=0",
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
|
||||
"""Join two audio files. position: 'start' (prepend other) or 'end' (append other)."""
|
||||
if position == "start":
|
||||
first, second = other_path, input_path
|
||||
else:
|
||||
first, second = input_path, other_path
|
||||
|
||||
self._run_ffmpeg([
|
||||
"-i", first,
|
||||
"-i", second,
|
||||
"-filter_complex", "[0:a][1:a]concat=n=2:v=0:a=1[out]",
|
||||
"-map", "[out]",
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
def apply_edit(
|
||||
self,
|
||||
input_gcs_path: str,
|
||||
operation: str,
|
||||
params: dict,
|
||||
output_gcs_path: str,
|
||||
job_id: str,
|
||||
) -> tuple[AudioMetadata, str]:
|
||||
"""
|
||||
Apply an edit operation to an audio file in GCS.
|
||||
|
||||
Returns (metadata, output_gcs_path).
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_input = os.path.join(temp_dir, "input.flac")
|
||||
local_output = os.path.join(temp_dir, "output.flac")
|
||||
|
||||
# Download current audio
|
||||
self.storage.download_file(input_gcs_path, local_input)
|
||||
|
||||
# Apply the operation
|
||||
if operation == "trim_start":
|
||||
metadata = self.trim_start(local_input, params["end_seconds"], local_output)
|
||||
elif operation == "trim_end":
|
||||
metadata = self.trim_end(local_input, params["start_seconds"], local_output)
|
||||
elif operation == "cut":
|
||||
metadata = self.cut_region(
|
||||
local_input, params["start_seconds"], params["end_seconds"], local_output
|
||||
)
|
||||
elif operation == "mute":
|
||||
metadata = self.mute_region(
|
||||
local_input, params["start_seconds"], params["end_seconds"], local_output
|
||||
)
|
||||
elif operation in ("join_start", "join_end"):
|
||||
# Download the upload file
|
||||
upload_gcs_path = params["upload_gcs_path"]
|
||||
local_other = os.path.join(temp_dir, "other.flac")
|
||||
self.storage.download_file(upload_gcs_path, local_other)
|
||||
position = "start" if operation == "join_start" else "end"
|
||||
metadata = self.join_audio(local_input, local_other, position, local_output)
|
||||
else:
|
||||
raise ValueError(f"Unknown operation: {operation}")
|
||||
|
||||
# Upload edited audio
|
||||
self.storage.upload_file(local_output, output_gcs_path)
|
||||
logger.info(f"[{job_id}] Applied {operation}, uploaded to {output_gcs_path}")
|
||||
|
||||
return metadata, output_gcs_path
|
||||
|
||||
def _run_ffmpeg(self, args: list[str]) -> None:
|
||||
"""Run an ffmpeg command with standard options."""
|
||||
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y"] + args
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"ffmpeg failed (exit {result.returncode}): {result.stderr}")
|
||||
@@ -0,0 +1,441 @@
|
||||
"""
|
||||
AI-powered credit evaluation service.
|
||||
|
||||
Evaluates whether to grant free credits (welcome or feedback) by collecting
|
||||
abuse signals and asking Gemini for a grant/deny decision. Fail-open: if
|
||||
the AI call fails for any reason, credits are granted.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CREDIT_EVALUATIONS_COLLECTION = "credit_evaluations"
|
||||
|
||||
|
||||
@dataclass
|
||||
class CreditEvaluation:
|
||||
"""Result of an AI credit evaluation."""
|
||||
decision: str # "grant" or "deny"
|
||||
reasoning: str
|
||||
confidence: float
|
||||
error: Optional[str] = None # Set if evaluation failed (decision defaults to "grant")
|
||||
signals: Optional[dict] = None # Collected abuse signals (for admin review emails)
|
||||
|
||||
|
||||
SYSTEM_PROMPT = """You are an anti-abuse evaluator for Nomad Karaoke, a web service that creates professional karaoke videos. Each job costs the service real money in API credits and cloud compute.
|
||||
|
||||
New users get 1 free welcome credit to try the service. Users who complete 2 jobs and submit feedback get 1 more credit. Some users abuse this by creating multiple accounts to get unlimited free karaoke generation.
|
||||
|
||||
Your job: Given the signals below, decide whether to GRANT or DENY free credits to this user.
|
||||
|
||||
## Decision Guidelines
|
||||
|
||||
**DENY if any of these are true:**
|
||||
- The user's device fingerprint matches other accounts (strong signal of multi-accounting)
|
||||
- The user's signup IP matches other accounts AND those accounts also have suspicious patterns (e.g., no spend, same user agent)
|
||||
- There's a clear pattern of account creation from the same device/network to farm free credits
|
||||
|
||||
**GRANT if:**
|
||||
- This appears to be a genuine new user with no suspicious correlations
|
||||
- The IP match is explainable (e.g., different fingerprints suggest different actual users on a shared network like a school or office)
|
||||
- There's insufficient evidence to confidently flag abuse
|
||||
|
||||
**When in doubt, GRANT.** False positives (blocking real users) are worse than false negatives (letting an occasional abuser through). We'd rather lose a few dollars than alienate a real customer.
|
||||
|
||||
## Response Format
|
||||
|
||||
Respond with ONLY a JSON object, no other text:
|
||||
{"decision": "grant" or "deny", "reasoning": "Brief explanation", "confidence": 0.0 to 1.0}
|
||||
"""
|
||||
|
||||
|
||||
def _build_user_prompt(
|
||||
email: str,
|
||||
grant_type: str,
|
||||
user_data: dict,
|
||||
fingerprint_matches: list,
|
||||
ip_matches: list,
|
||||
ip_geo: Optional[dict],
|
||||
recent_signups_ip: int,
|
||||
recent_signups_fp: int,
|
||||
user_agent: Optional[str],
|
||||
feedback_content: Optional[dict] = None,
|
||||
) -> str:
|
||||
"""Build the user prompt with all abuse signals."""
|
||||
lines = [
|
||||
f"## Credit Grant Request",
|
||||
f"- **Email:** {email}",
|
||||
f"- **Grant type:** {grant_type} credits",
|
||||
f"- **User's device fingerprint:** {user_data.get('device_fingerprint', 'unknown')}",
|
||||
f"- **User's signup IP:** {user_data.get('signup_ip', 'unknown')}",
|
||||
f"- **User agent:** {user_agent or 'unknown'}",
|
||||
f"- **Account created:** {user_data.get('created_at', 'unknown')}",
|
||||
f"- **Jobs created:** {user_data.get('total_jobs_created', 0)}",
|
||||
f"- **Jobs completed:** {user_data.get('total_jobs_completed', 0)}",
|
||||
f"- **Total spent (real money):** ${user_data.get('total_spent', 0) / 100:.2f}",
|
||||
f"- **Current credits:** {user_data.get('credits', 0)}",
|
||||
"",
|
||||
]
|
||||
|
||||
# IP geolocation
|
||||
if ip_geo and ip_geo.get("status") == "success":
|
||||
lines.extend([
|
||||
f"## IP Geolocation",
|
||||
f"- **Country:** {ip_geo.get('country', 'unknown')} ({ip_geo.get('country_code', '')})",
|
||||
f"- **City/Region:** {ip_geo.get('city', '')}, {ip_geo.get('region', '')}",
|
||||
f"- **ISP:** {ip_geo.get('isp', 'unknown')}",
|
||||
f"- **Organization:** {ip_geo.get('org', 'unknown')}",
|
||||
f"- **ASN:** {ip_geo.get('as_number', '')} {ip_geo.get('as_name', '')}",
|
||||
"",
|
||||
])
|
||||
|
||||
# Recent signup patterns
|
||||
lines.extend([
|
||||
f"## Recent Signup Patterns (last 24 hours)",
|
||||
f"- **New accounts from same IP:** {recent_signups_ip}",
|
||||
f"- **New accounts from same fingerprint:** {recent_signups_fp}",
|
||||
"",
|
||||
])
|
||||
|
||||
# Fingerprint correlations
|
||||
if fingerprint_matches:
|
||||
lines.append("## Other Accounts with Same Device Fingerprint (RED FLAG)")
|
||||
for match in fingerprint_matches:
|
||||
lines.append(
|
||||
f"- {match.get('email', '?')} | "
|
||||
f"Jobs: {match.get('total_jobs_created', 0)} | "
|
||||
f"Spent: ${match.get('total_spent', 0) / 100:.2f} | "
|
||||
f"Created: {match.get('created_at', '?')}"
|
||||
)
|
||||
lines.append("")
|
||||
else:
|
||||
lines.extend(["## Other Accounts with Same Device Fingerprint", "None found.", ""])
|
||||
|
||||
# IP correlations
|
||||
if ip_matches:
|
||||
lines.append("## Other Accounts from Same Signup IP")
|
||||
for match in ip_matches:
|
||||
lines.append(
|
||||
f"- {match.get('email', '?')} | "
|
||||
f"Fingerprint: {match.get('device_fingerprint', 'unknown')} | "
|
||||
f"Jobs: {match.get('total_jobs_created', 0)} | "
|
||||
f"Spent: ${match.get('total_spent', 0) / 100:.2f} | "
|
||||
f"Created: {match.get('created_at', '?')}"
|
||||
)
|
||||
lines.append("")
|
||||
else:
|
||||
lines.extend(["## Other Accounts from Same Signup IP", "None found.", ""])
|
||||
|
||||
# Feedback content (if applicable)
|
||||
if feedback_content:
|
||||
lines.extend([
|
||||
"## Feedback Submitted",
|
||||
f"- **Overall rating:** {feedback_content.get('overall_rating', '?')}/5",
|
||||
f"- **What went well:** {feedback_content.get('what_went_well', 'N/A')[:200]}",
|
||||
f"- **What could improve:** {feedback_content.get('what_could_improve', 'N/A')[:200]}",
|
||||
f"- **Additional comments:** {feedback_content.get('additional_comments', 'N/A')[:200]}",
|
||||
"",
|
||||
])
|
||||
|
||||
lines.append("Based on these signals, should we GRANT or DENY free credits to this user?")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _parse_gemini_response(response_text: str) -> CreditEvaluation:
|
||||
"""Parse Gemini's JSON response into a CreditEvaluation."""
|
||||
try:
|
||||
# Strip markdown code fences if present
|
||||
text = response_text.strip()
|
||||
if text.startswith("```"):
|
||||
text = text.split("\n", 1)[1] if "\n" in text else text[3:]
|
||||
if text.endswith("```"):
|
||||
text = text.rsplit("```", 1)[0]
|
||||
text = text.strip()
|
||||
if text.startswith("json"):
|
||||
text = text[4:].strip()
|
||||
|
||||
data = json.loads(text)
|
||||
decision = data.get("decision", "").lower()
|
||||
if decision not in ("grant", "deny"):
|
||||
decision = "pending_review" # fail-closed: unknown decision → manual review
|
||||
|
||||
return CreditEvaluation(
|
||||
decision=decision,
|
||||
reasoning=str(data.get("reasoning", "No reasoning provided")),
|
||||
confidence=float(data.get("confidence", 0.5)),
|
||||
)
|
||||
except (json.JSONDecodeError, ValueError, TypeError) as e:
|
||||
logger.warning(f"Failed to parse Gemini response: {e}. Response: {response_text[:200]}")
|
||||
return CreditEvaluation(
|
||||
decision="pending_review",
|
||||
reasoning="Failed to parse AI response — pending manual review",
|
||||
confidence=0.0,
|
||||
error=f"Parse error: {e}",
|
||||
)
|
||||
|
||||
|
||||
class CreditEvaluationService:
|
||||
"""Evaluates credit grant requests using Gemini AI."""
|
||||
|
||||
def __init__(self):
|
||||
self.settings = get_settings()
|
||||
|
||||
def _collect_signals(self, email: str) -> dict:
|
||||
"""Collect all abuse signals for evaluation."""
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.ip_geolocation_service import get_ip_geolocation_service
|
||||
|
||||
user_service = get_user_service()
|
||||
user = user_service.get_user(email)
|
||||
|
||||
if not user:
|
||||
return {
|
||||
"user_data": {},
|
||||
"fingerprint_matches": [],
|
||||
"ip_matches": [],
|
||||
"ip_geo": None,
|
||||
"recent_signups_ip": 0,
|
||||
"recent_signups_fp": 0,
|
||||
"user_agent": None,
|
||||
}
|
||||
|
||||
user_data = {
|
||||
"email": user.email,
|
||||
"device_fingerprint": user.device_fingerprint,
|
||||
"signup_ip": user.signup_ip,
|
||||
"credits": user.credits,
|
||||
"total_jobs_created": user.total_jobs_created,
|
||||
"total_jobs_completed": user.total_jobs_completed,
|
||||
"total_spent": user.total_spent,
|
||||
"created_at": str(user.created_at),
|
||||
}
|
||||
|
||||
# Find other accounts with same fingerprint
|
||||
fingerprint_matches = []
|
||||
if user.device_fingerprint:
|
||||
fp_users = user_service.find_users_by_fingerprint(user.device_fingerprint)
|
||||
fingerprint_matches = [
|
||||
{
|
||||
"email": u.email,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in fp_users if u.email != email
|
||||
]
|
||||
|
||||
# Find other accounts from same IP
|
||||
ip_matches = []
|
||||
if user.signup_ip:
|
||||
ip_users = user_service.find_users_by_signup_ip(user.signup_ip)
|
||||
ip_matches = [
|
||||
{
|
||||
"email": u.email,
|
||||
"device_fingerprint": u.device_fingerprint,
|
||||
"total_jobs_created": u.total_jobs_created,
|
||||
"total_spent": u.total_spent,
|
||||
"created_at": str(u.created_at),
|
||||
}
|
||||
for u in ip_users if u.email != email
|
||||
]
|
||||
|
||||
# IP geolocation
|
||||
ip_geo = None
|
||||
if user.signup_ip:
|
||||
try:
|
||||
geo_service = get_ip_geolocation_service()
|
||||
ip_geo = geo_service.lookup_ip(user.signup_ip)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Recent signup counts
|
||||
recent_signups_ip = 0
|
||||
recent_signups_fp = 0
|
||||
if user.signup_ip:
|
||||
recent_signups_ip = user_service.count_recent_signups_from_ip(user.signup_ip)
|
||||
if user.device_fingerprint:
|
||||
recent_signups_fp = user_service.count_recent_signups_from_fingerprint(user.device_fingerprint)
|
||||
|
||||
# User agent from latest session
|
||||
user_agent = None
|
||||
try:
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from google.cloud import firestore as fs
|
||||
sessions = (
|
||||
user_service.db.collection("sessions")
|
||||
.where(filter=FieldFilter("user_email", "==", email))
|
||||
.order_by("created_at", direction=fs.Query.DESCENDING)
|
||||
.limit(1)
|
||||
.stream()
|
||||
)
|
||||
for session_doc in sessions:
|
||||
user_agent = session_doc.to_dict().get("user_agent")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"user_data": user_data,
|
||||
"fingerprint_matches": fingerprint_matches,
|
||||
"ip_matches": ip_matches,
|
||||
"ip_geo": ip_geo,
|
||||
"recent_signups_ip": recent_signups_ip,
|
||||
"recent_signups_fp": recent_signups_fp,
|
||||
"user_agent": user_agent,
|
||||
}
|
||||
|
||||
def _call_gemini(self, prompt: str) -> str:
|
||||
"""Call Gemini and return the response text."""
|
||||
from google import genai
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.credit_eval_model,
|
||||
contents=prompt,
|
||||
config=genai.types.GenerateContentConfig(
|
||||
system_instruction=SYSTEM_PROMPT,
|
||||
),
|
||||
)
|
||||
return response.text
|
||||
|
||||
def _log_evaluation(
|
||||
self,
|
||||
email: str,
|
||||
grant_type: str,
|
||||
evaluation: CreditEvaluation,
|
||||
signals: dict,
|
||||
):
|
||||
"""Log the evaluation decision to Firestore for audit trail."""
|
||||
try:
|
||||
from google.cloud import firestore as fs
|
||||
db = fs.Client(project=self.settings.google_cloud_project)
|
||||
doc_id = str(uuid.uuid4())
|
||||
db.collection(CREDIT_EVALUATIONS_COLLECTION).document(doc_id).set({
|
||||
"id": doc_id,
|
||||
"email": email,
|
||||
"grant_type": grant_type,
|
||||
"decision": evaluation.decision,
|
||||
"reasoning": evaluation.reasoning,
|
||||
"confidence": evaluation.confidence,
|
||||
"error": evaluation.error,
|
||||
"model": self.settings.credit_eval_model,
|
||||
"signals_snapshot": {
|
||||
"fingerprint_match_count": len(signals.get("fingerprint_matches", [])),
|
||||
"ip_match_count": len(signals.get("ip_matches", [])),
|
||||
"recent_signups_ip": signals.get("recent_signups_ip", 0),
|
||||
"recent_signups_fp": signals.get("recent_signups_fp", 0),
|
||||
"user_ip": signals.get("user_data", {}).get("signup_ip"),
|
||||
"user_fingerprint": signals.get("user_data", {}).get("device_fingerprint"),
|
||||
},
|
||||
"evaluated_at": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
except Exception:
|
||||
logger.exception(f"Failed to log credit evaluation for {email}")
|
||||
|
||||
def evaluate(
|
||||
self,
|
||||
email: str,
|
||||
grant_type: str,
|
||||
feedback_content: Optional[dict] = None,
|
||||
) -> CreditEvaluation:
|
||||
"""
|
||||
Evaluate whether to grant free credits.
|
||||
|
||||
Args:
|
||||
email: User's email
|
||||
grant_type: "welcome" or "feedback"
|
||||
feedback_content: Feedback form data (for feedback grants only)
|
||||
|
||||
Returns:
|
||||
CreditEvaluation with decision, reasoning, confidence.
|
||||
Fail-closed: returns "pending_review" on any error (admin notified).
|
||||
"""
|
||||
if not self.settings.credit_eval_enabled:
|
||||
return CreditEvaluation(
|
||||
decision="grant",
|
||||
reasoning="Credit evaluation disabled — auto-granting",
|
||||
confidence=1.0,
|
||||
)
|
||||
|
||||
try:
|
||||
# Collect signals
|
||||
signals = self._collect_signals(email)
|
||||
|
||||
# Quick-grant: if no correlations found at all, skip AI call
|
||||
if (
|
||||
not signals["fingerprint_matches"]
|
||||
and not signals["ip_matches"]
|
||||
and signals["recent_signups_ip"] <= 1
|
||||
and signals["recent_signups_fp"] <= 1
|
||||
):
|
||||
evaluation = CreditEvaluation(
|
||||
decision="grant",
|
||||
reasoning="No suspicious correlations found — clean user",
|
||||
confidence=1.0,
|
||||
signals=signals,
|
||||
)
|
||||
self._log_evaluation(email, grant_type, evaluation, signals)
|
||||
return evaluation
|
||||
|
||||
# Build prompt and call Gemini
|
||||
prompt = _build_user_prompt(
|
||||
email=email,
|
||||
grant_type=grant_type,
|
||||
user_data=signals["user_data"],
|
||||
fingerprint_matches=signals["fingerprint_matches"],
|
||||
ip_matches=signals["ip_matches"],
|
||||
ip_geo=signals["ip_geo"],
|
||||
recent_signups_ip=signals["recent_signups_ip"],
|
||||
recent_signups_fp=signals["recent_signups_fp"],
|
||||
user_agent=signals["user_agent"],
|
||||
feedback_content=feedback_content,
|
||||
)
|
||||
|
||||
response_text = self._call_gemini(prompt)
|
||||
evaluation = _parse_gemini_response(response_text)
|
||||
evaluation.signals = signals
|
||||
|
||||
self._log_evaluation(email, grant_type, evaluation, signals)
|
||||
logger.info(
|
||||
f"Credit evaluation for {email} ({grant_type}): "
|
||||
f"{evaluation.decision} (confidence={evaluation.confidence:.2f})"
|
||||
)
|
||||
return evaluation
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Credit evaluation failed for {email} — pending manual review (fail-closed)")
|
||||
# Include whatever signals were collected before the failure
|
||||
collected_signals = locals().get("signals")
|
||||
evaluation = CreditEvaluation(
|
||||
decision="pending_review",
|
||||
reasoning="Evaluation failed — pending manual review",
|
||||
confidence=0.0,
|
||||
error=str(e),
|
||||
signals=collected_signals,
|
||||
)
|
||||
try:
|
||||
self._log_evaluation(email, grant_type, evaluation, collected_signals or {})
|
||||
except Exception:
|
||||
pass
|
||||
return evaluation
|
||||
|
||||
|
||||
_service_instance: Optional[CreditEvaluationService] = None
|
||||
|
||||
|
||||
def get_credit_evaluation_service() -> CreditEvaluationService:
|
||||
"""Get or create the singleton credit evaluation service."""
|
||||
global _service_instance
|
||||
if _service_instance is None:
|
||||
_service_instance = CreditEvaluationService()
|
||||
return _service_instance
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
Disposable Domain Sync Service.
|
||||
|
||||
Fetches and syncs disposable email domain blocklists from external sources.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Set
|
||||
|
||||
import httpx
|
||||
|
||||
from backend.services.email_validation_service import (
|
||||
BLOCKLISTS_COLLECTION,
|
||||
BLOCKLIST_CONFIG_DOC,
|
||||
DEFAULT_DISPOSABLE_DOMAINS,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
EXTERNAL_BLOCKLIST_URL = (
|
||||
"https://raw.githubusercontent.com/disposable-email-domains/"
|
||||
"disposable-email-domains/refs/heads/main/disposable_email_blocklist.conf"
|
||||
)
|
||||
FETCH_TIMEOUT_SECONDS = 30
|
||||
MAX_RESPONSE_BYTES = 2 * 1024 * 1024 # 2 MB
|
||||
MAX_DOMAIN_COUNT = 50_000
|
||||
|
||||
|
||||
def parse_blocklist_text(text: str) -> Set[str]:
|
||||
"""Parse newline-delimited blocklist text into a set of lowercase domains."""
|
||||
domains = set()
|
||||
for line in text.splitlines():
|
||||
domain = line.strip().lower()
|
||||
if domain:
|
||||
domains.add(domain)
|
||||
return domains
|
||||
|
||||
|
||||
async def fetch_external_blocklist() -> Set[str]:
|
||||
"""Fetch the external disposable domain blocklist from GitHub.
|
||||
|
||||
Checks Content-Length header and response body size against safety limits.
|
||||
"""
|
||||
async with httpx.AsyncClient(timeout=FETCH_TIMEOUT_SECONDS) as client:
|
||||
response = await client.get(EXTERNAL_BLOCKLIST_URL)
|
||||
response.raise_for_status()
|
||||
|
||||
content_length = response.headers.get("content-length")
|
||||
if content_length and int(content_length) > MAX_RESPONSE_BYTES:
|
||||
raise ValueError(
|
||||
f"Response size {content_length} exceeds maximum {MAX_RESPONSE_BYTES}"
|
||||
)
|
||||
|
||||
text = response.text
|
||||
if len(text.encode()) > MAX_RESPONSE_BYTES:
|
||||
raise ValueError(
|
||||
f"Response body size exceeds maximum {MAX_RESPONSE_BYTES}"
|
||||
)
|
||||
|
||||
domains = parse_blocklist_text(text)
|
||||
|
||||
if len(domains) > MAX_DOMAIN_COUNT:
|
||||
raise ValueError(
|
||||
f"Domain count {len(domains)} exceeds maximum {MAX_DOMAIN_COUNT}"
|
||||
)
|
||||
|
||||
logger.info(f"Fetched {len(domains)} domains from external blocklist")
|
||||
return domains
|
||||
|
||||
|
||||
def sync_disposable_domains(db, external_domains: Set[str]) -> dict:
|
||||
"""
|
||||
Sync external domains into Firestore.
|
||||
|
||||
Handles first-run migration from old disposable_domains field,
|
||||
and cleans up redundant manual domains on subsequent runs.
|
||||
|
||||
Note: This is a synchronous function (Firestore SDK is sync).
|
||||
Call from async code with `await asyncio.to_thread(sync_disposable_domains, db, domains)`.
|
||||
|
||||
Returns a summary dict with counts.
|
||||
"""
|
||||
doc_ref = db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
doc = doc_ref.get()
|
||||
|
||||
data = doc.to_dict() if doc.exists else {}
|
||||
result = {"external_count": len(external_domains), "added": 0, "removed": 0, "migrated_to_manual": []}
|
||||
|
||||
is_migration = "external_domains" not in data
|
||||
|
||||
if is_migration:
|
||||
old_domains = set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS
|
||||
manual_only = old_domains - external_domains
|
||||
result["migrated_to_manual"] = sorted(manual_only)
|
||||
|
||||
new_data = {
|
||||
**data, # preserve all existing fields
|
||||
"external_domains": sorted(external_domains),
|
||||
"manual_domains": sorted(manual_only),
|
||||
"allowlisted_domains": data.get("allowlisted_domains", []),
|
||||
"last_sync_at": datetime.now(timezone.utc),
|
||||
"last_sync_count": len(external_domains),
|
||||
}
|
||||
new_data.pop("disposable_domains", None) # remove legacy field
|
||||
doc_ref.set(new_data)
|
||||
else:
|
||||
old_external = set(data.get("external_domains", []))
|
||||
manual_domains = set(data.get("manual_domains", []))
|
||||
|
||||
result["added"] = len(external_domains - old_external)
|
||||
result["removed"] = len(old_external - external_domains)
|
||||
|
||||
cleaned_manual = manual_domains - external_domains
|
||||
|
||||
new_data = {
|
||||
**data,
|
||||
"external_domains": sorted(external_domains),
|
||||
"manual_domains": sorted(cleaned_manual),
|
||||
"last_sync_at": datetime.now(timezone.utc),
|
||||
"last_sync_count": len(external_domains),
|
||||
}
|
||||
doc_ref.set(new_data)
|
||||
|
||||
logger.info(
|
||||
f"Sync complete: {result['external_count']} external domains, "
|
||||
f"{result['added']} added, {result['removed']} removed"
|
||||
)
|
||||
return result
|
||||
@@ -981,6 +981,194 @@ Get started: {self.frontend_url}
|
||||
text_content=message_content,
|
||||
)
|
||||
|
||||
def send_review_reminder(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
job_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send 24h review reminder email with expiry warning.
|
||||
|
||||
Sent when a job has been awaiting review for 24 hours.
|
||||
Offers help and warns that the job will expire in another 24 hours.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
job_id: Job ID for constructing the review link
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
song_info = f" — {artist} - {title}" if artist and title else ""
|
||||
subject = f"Reminder: Your karaoke video is waiting for review{song_info}"
|
||||
|
||||
review_url = f"{self.frontend_url}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}/app"
|
||||
|
||||
extra_styles = """
|
||||
.alert {
|
||||
background-color: #fef3c7;
|
||||
border: 1px solid #fcd34d;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.expiry-warning {
|
||||
background-color: #fef2f2;
|
||||
border: 1px solid #fca5a5;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
color: #991b1b;
|
||||
}
|
||||
.review-btn {
|
||||
display: inline-block;
|
||||
background-color: #ff7acc;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
font-weight: bold;
|
||||
margin: 16px 0;
|
||||
}
|
||||
"""
|
||||
|
||||
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
|
||||
|
||||
content = f"""
|
||||
<div class="alert">
|
||||
⏰ Your karaoke video is waiting for you!
|
||||
</div>
|
||||
|
||||
<p>Hi there! Just a friendly reminder that your karaoke video{song_name} is ready for review.</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(review_url)}" class="review-btn">Review Your Video</a>
|
||||
</p>
|
||||
|
||||
<p>During the review, you can check the lyrics are correct and choose your preferred instrumental track. It usually only takes a few minutes!</p>
|
||||
|
||||
<p>If you're having any trouble with the review process, just reply to this email and I'll be happy to help you out.</p>
|
||||
|
||||
<div class="expiry-warning">
|
||||
⚠️ Please note: if the review isn't completed within the next <strong>24 hours</strong>,
|
||||
the job will automatically expire and your credit will be refunded.
|
||||
</div>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
text_content = (
|
||||
f"Reminder: Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} is ready for review.\n\n"
|
||||
f"Review it here: {review_url}\n\n"
|
||||
"If you're having trouble with the review process, just reply to this email and I'll help you out.\n\n"
|
||||
"Please note: if the review isn't completed within the next 24 hours, "
|
||||
"the job will automatically expire and your credit will be refunded."
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_review_expired(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
credits_balance: int = 0,
|
||||
) -> bool:
|
||||
"""
|
||||
Send review expiry notification email.
|
||||
|
||||
Sent when a job is auto-cancelled after 48 hours in review.
|
||||
Informs the user their credit has been refunded.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
credits_balance: User's current credit balance after refund
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
song_info = f" — {artist} - {title}" if artist and title else ""
|
||||
subject = f"Your karaoke video has expired{song_info}"
|
||||
|
||||
extra_styles = """
|
||||
.info-box {
|
||||
background-color: #f0f9ff;
|
||||
border: 1px solid #93c5fd;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.credit-badge {
|
||||
display: inline-block;
|
||||
background-color: #22c55e;
|
||||
color: #ffffff;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.create-btn {
|
||||
display: inline-block;
|
||||
background-color: #ff7acc;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
font-weight: bold;
|
||||
margin: 16px 0;
|
||||
}
|
||||
"""
|
||||
|
||||
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
|
||||
|
||||
content = f"""
|
||||
<div class="info-box">
|
||||
Your karaoke video{song_name} has been automatically cancelled because the review
|
||||
wasn't completed within 48 hours.
|
||||
</div>
|
||||
|
||||
<p>Don't worry — your credit has been refunded! Your current balance is
|
||||
<span class="credit-badge">{credits_balance} credit{'s' if credits_balance != 1 else ''}</span>.</p>
|
||||
|
||||
<p>You can create a new karaoke video anytime using your credits:</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(self.frontend_url)}/app" class="create-btn">Create New Video</a>
|
||||
</p>
|
||||
|
||||
<p>If you had any trouble with the review process or need help, just reply to this email — I'd love to help!</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
text_content = (
|
||||
f"Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} has been "
|
||||
"automatically cancelled because the review wasn't completed within 48 hours.\n\n"
|
||||
f"Your credit has been refunded. Current balance: {credits_balance} credit{'s' if credits_balance != 1 else ''}.\n\n"
|
||||
f"Create a new video anytime: {self.frontend_url}/app\n\n"
|
||||
"If you had any trouble or need help, just reply to this email."
|
||||
)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_youtube_upload_complete(
|
||||
self,
|
||||
to_email: str,
|
||||
@@ -1228,6 +1416,315 @@ Open Job: {app_url}
|
||||
)
|
||||
|
||||
|
||||
def send_feedback_notification(
|
||||
self,
|
||||
user_email: str,
|
||||
overall_rating: int,
|
||||
ease_of_use_rating: int,
|
||||
lyrics_accuracy_rating: int,
|
||||
correction_experience_rating: int,
|
||||
what_went_well: Optional[str] = None,
|
||||
what_could_improve: Optional[str] = None,
|
||||
additional_comments: Optional[str] = None,
|
||||
would_recommend: bool = True,
|
||||
would_use_again: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
Send admin notification when a user submits product feedback.
|
||||
|
||||
Args:
|
||||
user_email: Email of the user who submitted feedback
|
||||
overall_rating: 1-5 star rating
|
||||
ease_of_use_rating: 1-5 star rating
|
||||
lyrics_accuracy_rating: 1-5 star rating
|
||||
correction_experience_rating: 1-5 star rating
|
||||
what_went_well: Optional text feedback
|
||||
what_could_improve: Optional text feedback
|
||||
additional_comments: Optional text feedback
|
||||
would_recommend: Whether user would recommend
|
||||
would_use_again: Whether user would use again
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
admin_email = os.getenv("ADMIN_NOTIFICATION_EMAIL", "admin@nomadkaraoke.com")
|
||||
subject = f"New Feedback from {user_email} — {overall_rating}/5 overall"
|
||||
|
||||
def stars(rating: int) -> str:
|
||||
return "★" * rating + "☆" * (5 - rating)
|
||||
|
||||
def text_block(label: str, value: Optional[str]) -> str:
|
||||
if not value:
|
||||
return ""
|
||||
escaped = html.escape(value).replace("\n", "<br>")
|
||||
return f"""
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold; vertical-align: top; white-space: nowrap;">{label}</td>
|
||||
<td style="padding: 8px 12px;">{escaped}</td>
|
||||
</tr>"""
|
||||
|
||||
recommend_badge = "Yes ✓" if would_recommend else "No ✗"
|
||||
use_again_badge = "Yes ✓" if would_use_again else "No ✗"
|
||||
|
||||
admin_url = f"{self.frontend_url}/admin/feedback"
|
||||
|
||||
extra_styles = """
|
||||
.feedback-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.feedback-table td {
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
.stars {
|
||||
color: #eab308;
|
||||
font-size: 18px;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>New product feedback submitted by <strong>{html.escape(user_email)}</strong>:</p>
|
||||
|
||||
<table class="feedback-table">
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Overall</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(overall_rating)}</span> ({overall_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Ease of Use</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(ease_of_use_rating)}</span> ({ease_of_use_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Lyrics Accuracy</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(lyrics_accuracy_rating)}</span> ({lyrics_accuracy_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Correction Experience</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(correction_experience_rating)}</span> ({correction_experience_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Would Recommend</td>
|
||||
<td style="padding: 8px 12px;">{recommend_badge}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Would Use Again</td>
|
||||
<td style="padding: 8px 12px;">{use_again_badge}</td>
|
||||
</tr>
|
||||
{text_block("What went well", what_went_well)}
|
||||
{text_block("What could improve", what_could_improve)}
|
||||
{text_block("Additional comments", additional_comments)}
|
||||
</table>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{admin_url}" class="button">View All Feedback</a>
|
||||
</p>
|
||||
"""
|
||||
|
||||
text_content = f"""New Feedback from {user_email}
|
||||
|
||||
Overall: {overall_rating}/5
|
||||
Ease of Use: {ease_of_use_rating}/5
|
||||
Lyrics Accuracy: {lyrics_accuracy_rating}/5
|
||||
Correction Experience: {correction_experience_rating}/5
|
||||
Would Recommend: {recommend_badge}
|
||||
Would Use Again: {use_again_badge}
|
||||
|
||||
What went well: {what_went_well or '(empty)'}
|
||||
What could improve: {what_could_improve or '(empty)'}
|
||||
Additional comments: {additional_comments or '(empty)'}
|
||||
|
||||
View all feedback: {admin_url}
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=admin_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
|
||||
def send_credit_review_needed_email(
|
||||
self,
|
||||
user_email: str,
|
||||
grant_type: str,
|
||||
reason: str,
|
||||
signals: dict | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Notify Andrew that a credit grant needs manual review.
|
||||
|
||||
Sent when AI evaluation fails, is uncertain, or encounters an error.
|
||||
Includes abuse signals and a direct link to the user's admin page.
|
||||
"""
|
||||
admin_user_url = f"{self.frontend_url}/admin/users/detail?email={user_email}"
|
||||
subject = f"Credit review needed: {user_email} ({grant_type})"
|
||||
|
||||
# Build signals summary for the email
|
||||
signals_html = ""
|
||||
signals_text = ""
|
||||
if signals:
|
||||
user_data = signals.get("user_data", {})
|
||||
ip_geo = signals.get("ip_geo")
|
||||
fp_matches = signals.get("fingerprint_matches", [])
|
||||
ip_matches = signals.get("ip_matches", [])
|
||||
|
||||
rows = []
|
||||
text_rows = []
|
||||
|
||||
if user_data.get("signup_ip"):
|
||||
rows.append(("IP Address", user_data["signup_ip"]))
|
||||
text_rows.append(f"IP Address: {user_data['signup_ip']}")
|
||||
|
||||
if ip_geo:
|
||||
geo_str = ", ".join(
|
||||
str(v) for v in [
|
||||
ip_geo.get("city"), ip_geo.get("region"), ip_geo.get("country"),
|
||||
] if v
|
||||
)
|
||||
if ip_geo.get("org"):
|
||||
geo_str += f" ({ip_geo['org']})"
|
||||
if geo_str:
|
||||
rows.append(("Location", geo_str))
|
||||
text_rows.append(f"Location: {geo_str}")
|
||||
|
||||
if signals.get("user_agent"):
|
||||
rows.append(("User Agent", signals["user_agent"]))
|
||||
text_rows.append(f"User Agent: {signals['user_agent']}")
|
||||
|
||||
if user_data.get("device_fingerprint"):
|
||||
fp = user_data["device_fingerprint"]
|
||||
rows.append(("Fingerprint", f"{fp[:12]}..."))
|
||||
text_rows.append(f"Fingerprint: {fp[:12]}...")
|
||||
|
||||
rows.append(("Recent signups (IP)", str(signals.get("recent_signups_ip", 0))))
|
||||
rows.append(("Recent signups (fingerprint)", str(signals.get("recent_signups_fp", 0))))
|
||||
text_rows.append(f"Recent signups from IP: {signals.get('recent_signups_ip', 0)}")
|
||||
text_rows.append(f"Recent signups from fingerprint: {signals.get('recent_signups_fp', 0)}")
|
||||
|
||||
if fp_matches:
|
||||
match_emails = ", ".join(m.get("email", "?") for m in fp_matches)
|
||||
rows.append(("Fingerprint matches", match_emails))
|
||||
text_rows.append(f"Fingerprint matches: {match_emails}")
|
||||
|
||||
if ip_matches:
|
||||
match_emails = ", ".join(m.get("email", "?") for m in ip_matches)
|
||||
rows.append(("IP matches", match_emails))
|
||||
text_rows.append(f"IP matches: {match_emails}")
|
||||
|
||||
table_rows = "".join(
|
||||
f'<tr><td style="padding:4px 12px 4px 0;color:#999;white-space:nowrap;">{html.escape(label)}</td>'
|
||||
f'<td style="padding:4px 0;">{html.escape(value or "")}</td></tr>'
|
||||
for label, value in rows
|
||||
)
|
||||
signals_html = f"""
|
||||
<table style="margin:12px 0;font-size:14px;border-collapse:collapse;">{table_rows}</table>"""
|
||||
signals_text = "\n".join(text_rows)
|
||||
|
||||
content = f"""
|
||||
<p>A {grant_type} credit grant for <strong>{user_email}</strong> needs your review.</p>
|
||||
|
||||
<p><strong>Reason:</strong> {reason}</p>
|
||||
{signals_html}
|
||||
<p>The user has been told that their signup is being reviewed and credits will be
|
||||
assigned shortly if everything checks out.</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{admin_user_url}" class="button">Review User</a>
|
||||
</p>
|
||||
|
||||
<p style="color: #999; font-size: 14px;">
|
||||
If the user looks legitimate, grant them credits from their admin page.
|
||||
If not, no action needed — they already have 0 credits.
|
||||
</p>
|
||||
"""
|
||||
|
||||
signals_section = f"\n{signals_text}\n" if signals_text else ""
|
||||
text_content = f"""Credit review needed: {user_email} ({grant_type})
|
||||
|
||||
Reason: {reason}
|
||||
{signals_section}
|
||||
Review user: {admin_user_url}
|
||||
|
||||
If the user looks legitimate, grant them credits from their admin page.
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email="andrew@beveridge.uk",
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_credit_denied_email(self, email: str, grant_type: str = "welcome") -> bool:
|
||||
"""
|
||||
Send a friendly-but-firm email when free credits are denied due to abuse signals.
|
||||
|
||||
CC'd to andrew@beveridge.uk so he can intervene if it's a false positive.
|
||||
The tone invites the user to reply if it's a mistake.
|
||||
"""
|
||||
subject = "About your Nomad Karaoke free credits"
|
||||
|
||||
credit_type = "welcome credits" if grant_type == "welcome" else "feedback bonus credits"
|
||||
|
||||
content = f"""
|
||||
<p>Hi there,</p>
|
||||
|
||||
<p>Thanks for signing up for Nomad Karaoke!</p>
|
||||
|
||||
<p>Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected
|
||||
patterns that suggest this may not be your first account with us, and each karaoke generation job
|
||||
costs us real money in cloud computing and API fees.</p>
|
||||
|
||||
<p>We totally understand if this is a mistake! If you're a genuine new user, please just
|
||||
<strong>reply to this email</strong> and let Andrew (the founder) know. He built this service and is
|
||||
happy to grant you some free credits to try it out — he just asks that you provide honest feedback
|
||||
on the experience in return.</p>
|
||||
|
||||
<p>If you'd like to get started right away, you can also purchase credits:</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{self.buy_url}" class="button">Buy Credits</a>
|
||||
</p>
|
||||
|
||||
<p style="color: #999; font-size: 14px;">We keep costs low so we can offer the service affordably,
|
||||
which means we need to be careful about free credit abuse. Thanks for understanding!</p>
|
||||
|
||||
{self._get_email_signature()}
|
||||
"""
|
||||
|
||||
text_content = f"""Hi there,
|
||||
|
||||
Thanks for signing up for Nomad Karaoke!
|
||||
|
||||
Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected patterns that suggest this may not be your first account with us, and each karaoke generation job costs us real money in cloud computing and API fees.
|
||||
|
||||
We totally understand if this is a mistake! If you're a genuine new user, please just reply to this email and let Andrew (the founder) know. He built this service and is happy to grant you some free credits to try it out - he just asks that you provide honest feedback on the experience in return.
|
||||
|
||||
If you'd like to get started right away, you can also purchase credits:
|
||||
{self.buy_url}
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
cc_emails=["andrew@beveridge.uk"],
|
||||
)
|
||||
|
||||
|
||||
# Global instance
|
||||
_email_service = None
|
||||
|
||||
|
||||
@@ -3,20 +3,42 @@ Email Validation Service.
|
||||
|
||||
Provides email validation, normalization, and blocklist checking
|
||||
to prevent abuse during enrollment and other flows.
|
||||
|
||||
Uses a tiered disposable domain detection strategy:
|
||||
1. Static blocklist (instant, from Firestore)
|
||||
2. Verified-clean domain cache (skip API calls for 7 days)
|
||||
3. DeBounce API (free, <50ms)
|
||||
4. verifymail.io API (paid, only if DeBounce says clean)
|
||||
|
||||
Auto-learns: flagged domains are persisted to manual_domains,
|
||||
clean domains are cached for 7 days in verified_clean_domains.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, Tuple, Set
|
||||
|
||||
import httpx
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Module-level HTTP client for connection pooling (external API checks)
|
||||
_http_client: Optional[httpx.Client] = None
|
||||
_HTTP_TIMEOUT = 2.0 # seconds per external API call
|
||||
|
||||
|
||||
def _get_http_client() -> httpx.Client:
|
||||
"""Get or create the module-level HTTP client."""
|
||||
global _http_client
|
||||
if _http_client is None or _http_client.is_closed:
|
||||
_http_client = httpx.Client(timeout=_HTTP_TIMEOUT)
|
||||
return _http_client
|
||||
|
||||
|
||||
def _mask_email(email: str) -> str:
|
||||
"""Mask an email address for privacy-safe logging."""
|
||||
@@ -34,164 +56,12 @@ def _mask_email(email: str) -> str:
|
||||
BLOCKLISTS_COLLECTION = "blocklists"
|
||||
BLOCKLIST_CONFIG_DOC = "config"
|
||||
|
||||
# Default disposable email domains (can be extended via admin UI)
|
||||
DEFAULT_DISPOSABLE_DOMAINS = {
|
||||
# Popular temporary email services
|
||||
"10minutemail.com",
|
||||
"10minutemail.net",
|
||||
"guerrillamail.com",
|
||||
"guerrillamail.org",
|
||||
"guerrillamail.net",
|
||||
"guerrillamail.biz",
|
||||
"guerrillamailblock.com",
|
||||
"tempmail.com",
|
||||
"tempmail.net",
|
||||
"temp-mail.org",
|
||||
"temp-mail.io",
|
||||
"throwawaymail.com",
|
||||
"mailinator.com",
|
||||
"mailinator.net",
|
||||
"mailinator.org",
|
||||
"mailinator.info",
|
||||
"maildrop.cc",
|
||||
"yopmail.com",
|
||||
"yopmail.fr",
|
||||
"yopmail.net",
|
||||
"fakeinbox.com",
|
||||
"fakemailgenerator.com",
|
||||
"dispostable.com",
|
||||
"getairmail.com",
|
||||
"getnada.com",
|
||||
"mohmal.com",
|
||||
"trashmail.com",
|
||||
"trashmail.net",
|
||||
"trashmail.org",
|
||||
"sharklasers.com",
|
||||
"grr.la",
|
||||
"guerrillamail.de",
|
||||
"pokemail.net",
|
||||
"spam4.me",
|
||||
"spamgourmet.com",
|
||||
"mytrashmail.com",
|
||||
"mailnesia.com",
|
||||
"mailcatch.com",
|
||||
"mintemail.com",
|
||||
"tempr.email",
|
||||
"tempail.com",
|
||||
"emailondeck.com",
|
||||
"incognitomail.com",
|
||||
"inboxalias.com",
|
||||
"33mail.com",
|
||||
"spamex.com",
|
||||
"spamfree24.org",
|
||||
"spamspot.com",
|
||||
"mailnull.com",
|
||||
"mailsac.com",
|
||||
"emailfake.com",
|
||||
"fakemail.fr",
|
||||
"tempinbox.com",
|
||||
"throwaway.email",
|
||||
"burnermail.io",
|
||||
"anonbox.net",
|
||||
"anonymbox.com",
|
||||
"discard.email",
|
||||
"discardmail.com",
|
||||
"discardmail.de",
|
||||
"mailexpire.com",
|
||||
"mailforspam.com",
|
||||
"meltmail.com",
|
||||
"mt2009.com",
|
||||
"mt2014.com",
|
||||
"nospam.ze.tc",
|
||||
"nospamfor.us",
|
||||
"nowmymail.com",
|
||||
"receiveee.com",
|
||||
"safe-mail.net",
|
||||
"spamavert.com",
|
||||
"spambob.com",
|
||||
"spambog.com",
|
||||
"spambox.us",
|
||||
"spamcannon.com",
|
||||
"spamcannon.net",
|
||||
"spamcon.org",
|
||||
"spamcorptastic.com",
|
||||
"spamday.com",
|
||||
"spamfree.eu",
|
||||
"spamherelots.com",
|
||||
"spamhereplease.com",
|
||||
"spamhole.com",
|
||||
"spamify.com",
|
||||
"spaminator.de",
|
||||
"spamkill.info",
|
||||
"spaml.com",
|
||||
"spaml.de",
|
||||
"spamoff.de",
|
||||
"spamobox.com",
|
||||
"spamslicer.com",
|
||||
"spamstack.net",
|
||||
"spamthis.co.uk",
|
||||
"spamthisplease.com",
|
||||
"supergreatmail.com",
|
||||
"suremail.info",
|
||||
"teleworm.us",
|
||||
"tempemail.co.za",
|
||||
"tempemail.net",
|
||||
"tempmailaddress.com",
|
||||
"tempmailo.com",
|
||||
"thankyou2010.com",
|
||||
"thisisnotmyrealemail.com",
|
||||
"tm.slsrs.ru",
|
||||
"tmpeml.info",
|
||||
"trash-mail.at",
|
||||
"trash-mail.de",
|
||||
"trash2009.com",
|
||||
"trashemail.de",
|
||||
"trashmail.at",
|
||||
"trashmailer.com",
|
||||
"wegwerfmail.de",
|
||||
"wegwerfmail.net",
|
||||
"wegwerfmail.org",
|
||||
"wh4f.org",
|
||||
"willhackforfood.biz",
|
||||
"willselfdestruct.com",
|
||||
"xmaily.com",
|
||||
"xyzfree.net",
|
||||
"yep.it",
|
||||
"yogamaven.com",
|
||||
"yuurok.com",
|
||||
"zehnminutenmail.de",
|
||||
"zippymail.info",
|
||||
# Additional common ones
|
||||
"mailnator.com",
|
||||
"bugmenot.com",
|
||||
"dodgeit.com",
|
||||
"dodgit.com",
|
||||
"e4ward.com",
|
||||
"emailsensei.com",
|
||||
"hushmail.com",
|
||||
"jetable.org",
|
||||
"kasmail.com",
|
||||
"mailblock.net",
|
||||
"mailcatch.com",
|
||||
"mymailoasis.com",
|
||||
"nervmich.net",
|
||||
"nervtmansen.de",
|
||||
"oneoffemail.com",
|
||||
"pookmail.com",
|
||||
"shortmail.net",
|
||||
"sneakemail.com",
|
||||
"sogetthis.com",
|
||||
"tempemailaddress.com",
|
||||
"tempomail.fr",
|
||||
"temporaryemail.net",
|
||||
"temporaryforwarding.com",
|
||||
"temporaryinbox.com",
|
||||
"thankyou2010.com",
|
||||
"tyldd.com",
|
||||
"uggsrock.com",
|
||||
"veryrealemail.com",
|
||||
"yourewronghereswhy.com",
|
||||
}
|
||||
# Legacy default set — kept as empty set for import compatibility.
|
||||
# The external sync (disposable_domain_sync_service) replaces this with ~4,800
|
||||
# domains from the community-curated disposable-email-domains repo.
|
||||
# The migration path in sync_disposable_domains() references this set to ensure
|
||||
# no domains are lost during the transition.
|
||||
DEFAULT_DISPOSABLE_DOMAINS: Set[str] = set()
|
||||
|
||||
# Gmail-like domains that support alias normalization
|
||||
GMAIL_LIKE_DOMAINS = {
|
||||
@@ -199,6 +69,47 @@ GMAIL_LIKE_DOMAINS = {
|
||||
"googlemail.com",
|
||||
}
|
||||
|
||||
# Well-known email providers that are never disposable.
|
||||
# These skip all external API checks for zero-latency validation.
|
||||
WELL_KNOWN_PROVIDERS = {
|
||||
"gmail.com",
|
||||
"googlemail.com",
|
||||
"yahoo.com",
|
||||
"yahoo.co.uk",
|
||||
"yahoo.co.jp",
|
||||
"yahoo.fr",
|
||||
"hotmail.com",
|
||||
"hotmail.co.uk",
|
||||
"outlook.com",
|
||||
"outlook.fr",
|
||||
"live.com",
|
||||
"live.co.uk",
|
||||
"msn.com",
|
||||
"icloud.com",
|
||||
"me.com",
|
||||
"mac.com",
|
||||
"aol.com",
|
||||
"protonmail.com",
|
||||
"proton.me",
|
||||
"zoho.com",
|
||||
"yandex.com",
|
||||
"yandex.ru",
|
||||
"mail.com",
|
||||
"gmx.com",
|
||||
"gmx.de",
|
||||
"fastmail.com",
|
||||
"hey.com",
|
||||
"tutanota.com",
|
||||
"tuta.io",
|
||||
}
|
||||
|
||||
# How long a verified-clean domain result is trusted before re-checking
|
||||
VERIFIED_CLEAN_TTL = timedelta(days=7)
|
||||
|
||||
# External API URLs
|
||||
DEBOUNCE_API_URL = "https://disposable.debounce.io/"
|
||||
VERIFYMAIL_API_URL = "https://verifymail.io/api"
|
||||
|
||||
|
||||
class EmailValidationService:
|
||||
"""
|
||||
@@ -293,17 +204,27 @@ class EmailValidationService:
|
||||
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
if "external_domains" in data:
|
||||
# New data model: effective = (external + manual) - allowlisted
|
||||
external = set(data.get("external_domains", []))
|
||||
manual = set(data.get("manual_domains", []))
|
||||
allowlisted = set(data.get("allowlisted_domains", []))
|
||||
effective_domains = (external | manual) - allowlisted
|
||||
else:
|
||||
# Old data model (pre-migration): use disposable_domains + defaults
|
||||
effective_domains = set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS
|
||||
config = {
|
||||
"disposable_domains": set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS,
|
||||
"disposable_domains": effective_domains,
|
||||
"blocked_emails": set(data.get("blocked_emails", [])),
|
||||
"blocked_ips": set(data.get("blocked_ips", [])),
|
||||
"verified_clean_domains": data.get("verified_clean_domains", {}),
|
||||
}
|
||||
else:
|
||||
# Use defaults if no config exists
|
||||
config = {
|
||||
"disposable_domains": DEFAULT_DISPOSABLE_DOMAINS.copy(),
|
||||
"blocked_emails": set(),
|
||||
"blocked_ips": set(),
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
|
||||
# Update cache
|
||||
@@ -316,6 +237,16 @@ class EmailValidationService:
|
||||
"""
|
||||
Check if an email uses a disposable domain.
|
||||
|
||||
Uses a tiered checking strategy:
|
||||
0. Well-known providers (gmail, yahoo, etc.) → instant False
|
||||
1. Static blocklist from Firestore → instant
|
||||
2. Verified-clean cache (7-day TTL) → skip API calls
|
||||
3. DeBounce API (free) → fast external check
|
||||
4. verifymail.io API (paid) → only if DeBounce says clean
|
||||
|
||||
Flagged domains are auto-learned to manual_domains.
|
||||
Clean domains are cached for 7 days.
|
||||
|
||||
Args:
|
||||
email: Email address to check
|
||||
|
||||
@@ -326,8 +257,188 @@ class EmailValidationService:
|
||||
return False
|
||||
|
||||
domain = email.lower().split("@")[-1]
|
||||
|
||||
# Tier 0: Well-known providers — skip everything
|
||||
if domain in WELL_KNOWN_PROVIDERS:
|
||||
return False
|
||||
|
||||
# Tier 1: Static blocklist (instant, always available)
|
||||
config = self.get_blocklist_config()
|
||||
return domain in config["disposable_domains"]
|
||||
if domain in config["disposable_domains"]:
|
||||
return True
|
||||
|
||||
# Tier 2: Recently verified clean? Skip API calls
|
||||
if self._is_domain_verified_clean(domain, config):
|
||||
return False
|
||||
|
||||
# Tier 3: DeBounce API (free, fast)
|
||||
debounce_result = self._check_debounce(email)
|
||||
if debounce_result is True:
|
||||
self._auto_learn_domain(domain)
|
||||
return True
|
||||
|
||||
# Tier 4: verifymail.io (paid, only if DeBounce gave definitive clean)
|
||||
if debounce_result is False:
|
||||
verifymail_result = self._check_verifymail(email)
|
||||
if verifymail_result is True:
|
||||
self._auto_learn_domain(domain)
|
||||
return True
|
||||
|
||||
# Both APIs say clean (or errored) — cache clean result
|
||||
if debounce_result is False:
|
||||
self._mark_domain_clean(domain)
|
||||
|
||||
return False
|
||||
|
||||
def _check_debounce(self, email: str) -> Optional[bool]:
|
||||
"""
|
||||
Check email against DeBounce disposable email API.
|
||||
|
||||
Returns:
|
||||
True if disposable, False if clean, None if error/timeout.
|
||||
"""
|
||||
try:
|
||||
client = _get_http_client()
|
||||
response = client.get(DEBOUNCE_API_URL, params={"email": email})
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
result = str(data.get("disposable", "")).lower() == "true"
|
||||
logger.info(
|
||||
f"DeBounce check for {_mask_email(email)}: "
|
||||
f"disposable={result}"
|
||||
)
|
||||
return result
|
||||
except httpx.TimeoutException:
|
||||
logger.warning(f"DeBounce API timeout for {_mask_email(email)}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(f"DeBounce API error for {_mask_email(email)}: {e}")
|
||||
return None
|
||||
|
||||
def _check_verifymail(self, email: str) -> Optional[bool]:
|
||||
"""
|
||||
Check email against verifymail.io API.
|
||||
|
||||
Only called when DeBounce says clean (to minimize paid API usage).
|
||||
|
||||
Returns:
|
||||
True if disposable/blocked, False if clean, None if error/timeout
|
||||
or API key not configured.
|
||||
"""
|
||||
api_key = settings.get_secret("verifymail-api-key")
|
||||
if not api_key:
|
||||
logger.debug("verifymail.io API key not configured, skipping")
|
||||
return None
|
||||
|
||||
try:
|
||||
client = _get_http_client()
|
||||
response = client.get(
|
||||
f"{VERIFYMAIL_API_URL}/{email}",
|
||||
params={"key": api_key},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
# verifymail.io returns both "disposable" and "block" flags
|
||||
is_disposable = data.get("disposable") is True
|
||||
is_blocked = data.get("block") is True
|
||||
result = is_disposable or is_blocked
|
||||
logger.info(
|
||||
f"verifymail.io check for {_mask_email(email)}: "
|
||||
f"disposable={is_disposable}, block={is_blocked}"
|
||||
)
|
||||
return result
|
||||
except httpx.TimeoutException:
|
||||
logger.warning(f"verifymail.io API timeout for {_mask_email(email)}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(f"verifymail.io API error for {_mask_email(email)}: {e}")
|
||||
return None
|
||||
|
||||
def _is_domain_verified_clean(self, domain: str, config: dict) -> bool:
|
||||
"""Check if a domain was verified clean within the TTL period."""
|
||||
verified = config.get("verified_clean_domains", {})
|
||||
entry = verified.get(domain)
|
||||
if not entry:
|
||||
return False
|
||||
|
||||
checked_at = entry.get("checked_at")
|
||||
if not checked_at:
|
||||
return False
|
||||
|
||||
# Handle both datetime objects and ISO strings
|
||||
if isinstance(checked_at, str):
|
||||
try:
|
||||
checked_at = datetime.fromisoformat(checked_at)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
# Make timezone-aware if naive
|
||||
if checked_at.tzinfo is None:
|
||||
checked_at = checked_at.replace(tzinfo=timezone.utc)
|
||||
|
||||
return (datetime.now(timezone.utc) - checked_at) < VERIFIED_CLEAN_TTL
|
||||
|
||||
def _auto_learn_domain(self, domain: str) -> None:
|
||||
"""
|
||||
Add a domain flagged by external API to manual_domains in Firestore.
|
||||
|
||||
This persists the result so future checks don't need the API call.
|
||||
Fire-and-forget: errors are logged but don't affect the caller.
|
||||
"""
|
||||
try:
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(
|
||||
BLOCKLIST_CONFIG_DOC
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
manual = set(data.get("manual_domains", []))
|
||||
else:
|
||||
manual = set()
|
||||
|
||||
if domain not in manual:
|
||||
manual.add(domain)
|
||||
doc_ref.set(
|
||||
{
|
||||
"manual_domains": list(manual),
|
||||
"updated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"updated_by": "auto-learn",
|
||||
},
|
||||
merge=True,
|
||||
)
|
||||
logger.info(f"Auto-learned disposable domain: {domain}")
|
||||
|
||||
# Invalidate cache so the domain is blocked immediately
|
||||
EmailValidationService._blocklist_cache = None
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to auto-learn domain {domain}: {e}")
|
||||
|
||||
def _mark_domain_clean(self, domain: str) -> None:
|
||||
"""
|
||||
Record that a domain was verified clean by external APIs.
|
||||
|
||||
Stored in verified_clean_domains dict keyed by domain.
|
||||
Future checks within VERIFIED_CLEAN_TTL will skip API calls.
|
||||
|
||||
Note: Uses read-modify-write instead of dot notation because
|
||||
domain names contain dots which Firestore interprets as nested paths.
|
||||
"""
|
||||
try:
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(
|
||||
BLOCKLIST_CONFIG_DOC
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
verified = doc.to_dict().get("verified_clean_domains", {}) if doc.exists else {}
|
||||
verified[domain] = {
|
||||
"checked_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
doc_ref.set({"verified_clean_domains": verified}, merge=True)
|
||||
logger.debug(f"Marked domain as verified clean: {domain}")
|
||||
|
||||
# Invalidate cache so new data is picked up
|
||||
EmailValidationService._blocklist_cache = None
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to mark domain clean {domain}: {e}")
|
||||
|
||||
def is_email_blocked(self, email: str) -> bool:
|
||||
"""
|
||||
@@ -398,13 +509,13 @@ class EmailValidationService:
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
domains = set(data.get("disposable_domains", []))
|
||||
domains = set(data.get("manual_domains", []))
|
||||
else:
|
||||
data = {}
|
||||
domains = set()
|
||||
|
||||
domains.add(domain)
|
||||
data["disposable_domains"] = list(domains)
|
||||
data["manual_domains"] = list(domains)
|
||||
data["updated_at"] = datetime.now(timezone.utc)
|
||||
data["updated_by"] = admin_email
|
||||
transaction.set(doc_ref, data, merge=True)
|
||||
@@ -432,14 +543,22 @@ class EmailValidationService:
|
||||
return
|
||||
|
||||
data = doc.to_dict()
|
||||
domains = set(data.get("disposable_domains", []))
|
||||
|
||||
if domain not in domains:
|
||||
manual = set(data.get("manual_domains", []))
|
||||
external = set(data.get("external_domains", []))
|
||||
|
||||
if domain in manual:
|
||||
result["found"] = True
|
||||
manual.discard(domain)
|
||||
data["manual_domains"] = list(manual)
|
||||
elif domain in external:
|
||||
result["found"] = True
|
||||
allowlisted = set(data.get("allowlisted_domains", []))
|
||||
allowlisted.add(domain)
|
||||
data["allowlisted_domains"] = list(allowlisted)
|
||||
else:
|
||||
return
|
||||
|
||||
result["found"] = True
|
||||
domains.discard(domain)
|
||||
data["disposable_domains"] = list(domains)
|
||||
data["updated_at"] = datetime.now(timezone.utc)
|
||||
data["updated_by"] = admin_email
|
||||
transaction.set(doc_ref, data, merge=True)
|
||||
@@ -598,14 +717,126 @@ class EmailValidationService:
|
||||
logger.info(f"Removed blocked IP: {ip_address} by {admin_email}")
|
||||
return True
|
||||
|
||||
def add_allowlisted_domain(self, domain: str, admin_email: str) -> bool:
|
||||
"""Add a domain to the allowlisted domains list."""
|
||||
domain = domain.lower().strip()
|
||||
if not domain:
|
||||
return False
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
|
||||
@firestore.transactional
|
||||
def update_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
domains = set(data.get("allowlisted_domains", []))
|
||||
else:
|
||||
data = {}
|
||||
domains = set()
|
||||
|
||||
domains.add(domain)
|
||||
data["allowlisted_domains"] = list(domains)
|
||||
data["updated_at"] = datetime.now(timezone.utc)
|
||||
data["updated_by"] = admin_email
|
||||
transaction.set(doc_ref, data, merge=True)
|
||||
|
||||
transaction = self.db.transaction()
|
||||
update_in_transaction(transaction, doc_ref)
|
||||
|
||||
# Invalidate cache
|
||||
EmailValidationService._blocklist_cache = None
|
||||
|
||||
logger.info(f"Added allowlisted domain: {domain} by {admin_email}")
|
||||
return True
|
||||
|
||||
def remove_allowlisted_domain(self, domain: str, admin_email: str) -> bool:
|
||||
"""Remove a domain from the allowlisted domains list."""
|
||||
domain = domain.lower().strip()
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
result = {"found": False}
|
||||
|
||||
@firestore.transactional
|
||||
def remove_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if not doc.exists:
|
||||
return
|
||||
|
||||
data = doc.to_dict()
|
||||
domains = set(data.get("allowlisted_domains", []))
|
||||
|
||||
if domain not in domains:
|
||||
return
|
||||
|
||||
result["found"] = True
|
||||
domains.discard(domain)
|
||||
data["allowlisted_domains"] = list(domains)
|
||||
data["updated_at"] = datetime.now(timezone.utc)
|
||||
data["updated_by"] = admin_email
|
||||
transaction.set(doc_ref, data, merge=True)
|
||||
|
||||
transaction = self.db.transaction()
|
||||
remove_in_transaction(transaction, doc_ref)
|
||||
|
||||
if not result["found"]:
|
||||
return False
|
||||
|
||||
# Invalidate cache
|
||||
EmailValidationService._blocklist_cache = None
|
||||
|
||||
logger.info(f"Removed allowlisted domain: {domain} by {admin_email}")
|
||||
return True
|
||||
|
||||
def get_blocklist_raw_data(self) -> dict:
|
||||
"""Get raw blocklist data for admin display (not the effective set)."""
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return {
|
||||
"external_domains": [], "manual_domains": [], "allowlisted_domains": [],
|
||||
"blocked_emails": [], "blocked_ips": [],
|
||||
"last_sync_at": None, "last_sync_count": None,
|
||||
"updated_at": None, "updated_by": None,
|
||||
}
|
||||
data = doc.to_dict()
|
||||
return {
|
||||
"external_domains": sorted(data.get("external_domains", [])),
|
||||
"manual_domains": sorted(data.get("manual_domains", [])),
|
||||
"allowlisted_domains": sorted(data.get("allowlisted_domains", [])),
|
||||
"blocked_emails": sorted(data.get("blocked_emails", [])),
|
||||
"blocked_ips": sorted(data.get("blocked_ips", [])),
|
||||
"last_sync_at": data.get("last_sync_at"),
|
||||
"last_sync_count": data.get("last_sync_count"),
|
||||
"updated_at": data.get("updated_at"),
|
||||
"updated_by": data.get("updated_by"),
|
||||
}
|
||||
|
||||
def get_blocklist_stats(self) -> dict:
|
||||
"""Get statistics about current blocklists."""
|
||||
config = self.get_blocklist_config(force_refresh=True)
|
||||
|
||||
# Also get raw data for detailed counts
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
|
||||
doc = doc_ref.get()
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
external_count = len(data.get("external_domains", []))
|
||||
manual_count = len(data.get("manual_domains", []))
|
||||
allowlisted_count = len(data.get("allowlisted_domains", []))
|
||||
else:
|
||||
external_count = 0
|
||||
manual_count = 0
|
||||
allowlisted_count = 0
|
||||
|
||||
return {
|
||||
"disposable_domains_count": len(config["disposable_domains"]),
|
||||
"blocked_emails_count": len(config["blocked_emails"]),
|
||||
"blocked_ips_count": len(config["blocked_ips"]),
|
||||
"default_disposable_domains_count": len(DEFAULT_DISPOSABLE_DOMAINS),
|
||||
"external_domains_count": external_count,
|
||||
"manual_domains_count": manual_count,
|
||||
"allowlisted_domains_count": allowlisted_count,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -383,6 +383,8 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
output_files["mp4_4k_lossy"] = path
|
||||
elif "720p" in filename_lower:
|
||||
output_files["mp4_720p"] = path
|
||||
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
|
||||
output_files["with_vocals_mp4"] = path
|
||||
self.logger.info(f"Converted output_files list to dict: {output_files}")
|
||||
else:
|
||||
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
|
||||
@@ -393,6 +395,7 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
lossy_4k_mp4_path=output_files.get("mp4_4k_lossy"),
|
||||
lossless_mkv_path=output_files.get("mkv_4k"),
|
||||
lossy_720p_mp4_path=output_files.get("mp4_720p"),
|
||||
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
|
||||
output_files=output_files,
|
||||
encoding_time_seconds=encoding_time,
|
||||
encoding_backend=self.name
|
||||
|
||||
@@ -17,6 +17,7 @@ Usage:
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
import aiohttp
|
||||
@@ -52,6 +53,34 @@ class EncodingService:
|
||||
self._url = None
|
||||
self._api_key = None
|
||||
self._initialized = False
|
||||
self._worker_manager = None
|
||||
self._cached_url = None
|
||||
self._url_cached_at = 0
|
||||
self._URL_CACHE_TTL = 30 # seconds
|
||||
|
||||
def set_worker_manager(self, manager):
|
||||
"""Set the worker manager for dynamic URL resolution from Firestore."""
|
||||
self._worker_manager = manager
|
||||
|
||||
def _get_worker_url(self) -> str:
|
||||
"""Get the current primary worker URL from Firestore (with TTL cache).
|
||||
|
||||
Falls back to static URL from config if worker_manager is not set.
|
||||
"""
|
||||
now = time.time()
|
||||
if self._cached_url and (now - self._url_cached_at) < self._URL_CACHE_TTL:
|
||||
return self._cached_url
|
||||
|
||||
if self._worker_manager:
|
||||
config = self._worker_manager.get_config()
|
||||
self._cached_url = config.primary_url
|
||||
self._url_cached_at = now
|
||||
return self._cached_url
|
||||
|
||||
# Fallback to static URL
|
||||
if not self._initialized:
|
||||
self._load_credentials()
|
||||
return self._url
|
||||
|
||||
def _load_credentials(self):
|
||||
"""Load encoding worker URL and API key from config/secrets."""
|
||||
@@ -188,7 +217,7 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
url = f"{self._url}/encode"
|
||||
url = f"{self._get_worker_url()}/encode"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {
|
||||
"job_id": job_id,
|
||||
@@ -249,7 +278,7 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
url = f"{self._url}/status/{job_id}"
|
||||
url = f"{self._get_worker_url()}/status/{job_id}"
|
||||
headers = {"X-API-Key": self._api_key}
|
||||
|
||||
resp = await self._request_with_retry(
|
||||
@@ -437,7 +466,7 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
url = f"{self._url}/encode-preview"
|
||||
url = f"{self._get_worker_url()}/encode-preview"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {
|
||||
"job_id": job_id,
|
||||
@@ -543,7 +572,7 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
return {"status": "not_configured"}
|
||||
|
||||
url = f"{self._url}/health"
|
||||
url = f"{self._get_worker_url()}/health"
|
||||
headers = {"X-API-Key": self._api_key}
|
||||
|
||||
try:
|
||||
@@ -565,4 +594,20 @@ def get_encoding_service() -> EncodingService:
|
||||
global _encoding_service
|
||||
if _encoding_service is None:
|
||||
_encoding_service = EncodingService()
|
||||
# Wire up worker manager for dynamic URL resolution
|
||||
try:
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from google.cloud import compute_v1, firestore
|
||||
settings = get_settings()
|
||||
db = firestore.Client(project=settings.google_cloud_project)
|
||||
compute_client = compute_v1.InstancesClient()
|
||||
manager = EncodingWorkerManager(
|
||||
db=db,
|
||||
compute_client=compute_client,
|
||||
project_id=settings.google_cloud_project,
|
||||
)
|
||||
_encoding_service.set_worker_manager(manager)
|
||||
except Exception:
|
||||
# Fallback to static URL if worker manager setup fails
|
||||
pass
|
||||
return _encoding_service
|
||||
@@ -0,0 +1,239 @@
|
||||
"""
|
||||
Blue-Green Encoding Worker Manager.
|
||||
|
||||
Manages the lifecycle and role assignment of two GCE encoding worker VMs
|
||||
(blue/green) via a Firestore config document as the single source of truth.
|
||||
|
||||
The config document at `config/encoding-worker` tracks which VM is primary
|
||||
(actively serving encoding requests) and which is secondary (idle or being
|
||||
deployed to). This enables zero-downtime deployments by swapping roles
|
||||
after deploying new code to the secondary.
|
||||
|
||||
Usage:
|
||||
from google.cloud import firestore
|
||||
from google.cloud.compute_v1 import InstancesClient
|
||||
|
||||
db = firestore.Client()
|
||||
compute = InstancesClient()
|
||||
manager = EncodingWorkerManager(db, compute)
|
||||
|
||||
# Get current config
|
||||
config = manager.get_config()
|
||||
print(f"Primary: {config.primary_vm} at {config.primary_url}")
|
||||
|
||||
# Ensure primary VM is running before dispatching work
|
||||
result = manager.ensure_primary_running()
|
||||
"""
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, UTC
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CONFIG_COLLECTION = "config"
|
||||
CONFIG_DOCUMENT = "encoding-worker"
|
||||
ENCODING_WORKER_PORT = 8080
|
||||
|
||||
|
||||
@dataclass
|
||||
class EncodingWorkerConfig:
|
||||
"""Represents the Firestore config/encoding-worker document."""
|
||||
|
||||
primary_vm: str
|
||||
primary_ip: str
|
||||
primary_version: str
|
||||
primary_deployed_at: Optional[str]
|
||||
secondary_vm: str
|
||||
secondary_ip: str
|
||||
secondary_version: Optional[str]
|
||||
secondary_deployed_at: Optional[str]
|
||||
last_swap_at: Optional[str]
|
||||
last_activity_at: Optional[str]
|
||||
deploy_in_progress: bool
|
||||
deploy_in_progress_since: Optional[str]
|
||||
|
||||
@property
|
||||
def primary_url(self) -> str:
|
||||
return f"http://{self.primary_ip}:{ENCODING_WORKER_PORT}"
|
||||
|
||||
@property
|
||||
def secondary_url(self) -> str:
|
||||
return f"http://{self.secondary_ip}:{ENCODING_WORKER_PORT}"
|
||||
|
||||
|
||||
class EncodingWorkerManager:
|
||||
"""Manages blue-green encoding worker VMs via Firestore config and Compute API."""
|
||||
|
||||
def __init__(self, db, compute_client=None, project_id="nomadkaraoke", zone="us-central1-c"):
|
||||
self._db = db
|
||||
self._compute = compute_client
|
||||
self._project_id = project_id
|
||||
self._zone = zone
|
||||
|
||||
def _doc_ref(self):
|
||||
"""Return a reference to the config/encoding-worker document."""
|
||||
return self._db.collection(CONFIG_COLLECTION).document(CONFIG_DOCUMENT)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Firestore config operations (Task 1)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_config(self) -> EncodingWorkerConfig:
|
||||
"""Read config/encoding-worker from Firestore and return as dataclass."""
|
||||
snapshot = self._doc_ref().get()
|
||||
if not snapshot.exists:
|
||||
raise ValueError(
|
||||
f"Encoding worker config document not found at "
|
||||
f"{CONFIG_COLLECTION}/{CONFIG_DOCUMENT}"
|
||||
)
|
||||
data = snapshot.to_dict()
|
||||
return EncodingWorkerConfig(
|
||||
primary_vm=data["primary_vm"],
|
||||
primary_ip=data["primary_ip"],
|
||||
primary_version=data["primary_version"],
|
||||
primary_deployed_at=data.get("primary_deployed_at"),
|
||||
secondary_vm=data["secondary_vm"],
|
||||
secondary_ip=data["secondary_ip"],
|
||||
secondary_version=data.get("secondary_version"),
|
||||
secondary_deployed_at=data.get("secondary_deployed_at"),
|
||||
last_swap_at=data.get("last_swap_at"),
|
||||
last_activity_at=data.get("last_activity_at"),
|
||||
deploy_in_progress=data.get("deploy_in_progress", False),
|
||||
deploy_in_progress_since=data.get("deploy_in_progress_since"),
|
||||
)
|
||||
|
||||
def update_activity(self) -> None:
|
||||
"""Update last_activity_at timestamp to record recent usage."""
|
||||
now = datetime.now(UTC).isoformat()
|
||||
self._doc_ref().update({"last_activity_at": now})
|
||||
logger.info("Updated encoding worker last_activity_at to %s", now)
|
||||
|
||||
def swap_roles(
|
||||
self,
|
||||
new_primary_vm: str,
|
||||
new_primary_ip: str,
|
||||
new_primary_version: str,
|
||||
old_primary_vm: str,
|
||||
old_primary_ip: str,
|
||||
old_primary_version: str,
|
||||
) -> None:
|
||||
"""Atomically swap primary and secondary roles using a Firestore transaction.
|
||||
|
||||
Args:
|
||||
new_primary_vm: VM name that will become the new primary.
|
||||
new_primary_ip: Internal IP of the new primary.
|
||||
new_primary_version: Version deployed on the new primary.
|
||||
old_primary_vm: Current primary VM name (becomes secondary).
|
||||
old_primary_ip: Internal IP of the old primary.
|
||||
old_primary_version: Version on the old primary.
|
||||
"""
|
||||
transaction = self._db.transaction()
|
||||
doc_ref = self._doc_ref()
|
||||
now = datetime.now(UTC).isoformat()
|
||||
|
||||
@firestore.transactional
|
||||
def _swap_in_transaction(txn, ref):
|
||||
txn.update(ref, {
|
||||
"primary_vm": new_primary_vm,
|
||||
"primary_ip": new_primary_ip,
|
||||
"primary_version": new_primary_version,
|
||||
"primary_deployed_at": now,
|
||||
"secondary_vm": old_primary_vm,
|
||||
"secondary_ip": old_primary_ip,
|
||||
"secondary_version": old_primary_version,
|
||||
"secondary_deployed_at": None,
|
||||
"last_swap_at": now,
|
||||
"deploy_in_progress": False,
|
||||
"deploy_in_progress_since": None,
|
||||
})
|
||||
|
||||
_swap_in_transaction(transaction, doc_ref)
|
||||
logger.info(
|
||||
"Swapped encoding worker roles: %s -> primary, %s -> secondary",
|
||||
new_primary_vm, old_primary_vm,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# VM lifecycle operations (Task 2)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_vm_status(self, vm_name: str) -> str:
|
||||
"""Get the current status of a GCE VM (e.g. RUNNING, TERMINATED, STAGING)."""
|
||||
instance = self._compute.get(
|
||||
project=self._project_id,
|
||||
zone=self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
return instance.status
|
||||
|
||||
def start_vm(self, vm_name: str) -> None:
|
||||
"""Start a VM if it is not already running or starting.
|
||||
|
||||
Fire-and-forget: returns immediately. Caller should poll get_vm_status
|
||||
if they need to wait for the VM to be fully RUNNING.
|
||||
"""
|
||||
status = self.get_vm_status(vm_name)
|
||||
if status in ("RUNNING", "STAGING"):
|
||||
logger.info("VM %s is already %s, skipping start", vm_name, status)
|
||||
return
|
||||
logger.info("Starting VM %s (current status: %s)", vm_name, status)
|
||||
self._compute.start(
|
||||
project=self._project_id,
|
||||
zone=self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
|
||||
def stop_vm(self, vm_name: str) -> None:
|
||||
"""Stop a VM if it is not already stopped or stopping."""
|
||||
status = self.get_vm_status(vm_name)
|
||||
if status in ("TERMINATED", "STOPPING"):
|
||||
logger.info("VM %s is already %s, skipping stop", vm_name, status)
|
||||
return
|
||||
logger.info("Stopping VM %s (current status: %s)", vm_name, status)
|
||||
self._compute.stop(
|
||||
project=self._project_id,
|
||||
zone=self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
|
||||
def ensure_primary_running(self) -> dict:
|
||||
"""Ensure the primary encoding worker VM is running.
|
||||
|
||||
Reads config, starts primary VM if stopped, and updates activity timestamp.
|
||||
|
||||
Returns:
|
||||
dict with keys:
|
||||
- started (bool): True if VM was started, False if already running
|
||||
- vm_name (str): Name of the primary VM
|
||||
- primary_url (str): URL of the primary encoding worker
|
||||
"""
|
||||
config = self.get_config()
|
||||
vm_name = config.primary_vm
|
||||
|
||||
status = self.get_vm_status(vm_name)
|
||||
started = False
|
||||
|
||||
if status not in ("RUNNING", "STAGING"):
|
||||
logger.info("Primary VM %s is %s, starting it", vm_name, status)
|
||||
self._compute.start(
|
||||
project=self._project_id,
|
||||
zone=self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
started = True
|
||||
else:
|
||||
logger.info("Primary VM %s is already %s", vm_name, status)
|
||||
|
||||
self.update_activity()
|
||||
|
||||
return {
|
||||
"started": started,
|
||||
"vm_name": vm_name,
|
||||
"primary_url": config.primary_url,
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ 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
|
||||
from backend.models.audio_edit_session import AudioEditSession
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -75,18 +77,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 +157,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,12 +181,15 @@ 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',
|
||||
'url', 'filename', 'audio_search_artist', 'audio_search_title',
|
||||
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url',
|
||||
'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',
|
||||
'processing_metadata',
|
||||
]
|
||||
|
||||
def list_jobs_summary(
|
||||
@@ -225,7 +233,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 +680,331 @@ 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")
|
||||
|
||||
if query_text:
|
||||
# Over-fetch since we filter in Python (Firestore doesn't support LIKE/contains)
|
||||
fetch_limit = max(limit * 25, 500)
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(fetch_limit)
|
||||
docs = query.stream()
|
||||
results = [doc.to_dict() for doc in docs]
|
||||
|
||||
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[:limit]
|
||||
else:
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
|
||||
docs = query.stream()
|
||||
return [doc.to_dict() for doc in docs]
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error searching review sessions: {e}")
|
||||
return []
|
||||
|
||||
# ---- Audio Edit Sessions ----
|
||||
|
||||
def save_audio_edit_session(self, job_id: str, session: AudioEditSession) -> str:
|
||||
"""Save an audio edit session to the subcollection."""
|
||||
try:
|
||||
session.job_id = job_id
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
|
||||
doc_ref = sessions_ref.document(session.session_id)
|
||||
doc_ref.set(session.to_dict())
|
||||
logger.info(f"Saved audio edit session {session.session_id} for job {job_id}")
|
||||
return session.session_id
|
||||
except Exception as e:
|
||||
logger.error(f"Error saving audio edit session for job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
def list_audio_edit_sessions(self, job_id: str) -> List[AudioEditSession]:
|
||||
"""List all audio edit sessions for a job, ordered by updated_at descending."""
|
||||
try:
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
|
||||
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING)
|
||||
docs = query.stream()
|
||||
return [AudioEditSession.from_dict(doc.to_dict()) for doc in docs]
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing audio edit sessions for job {job_id}: {e}")
|
||||
return []
|
||||
|
||||
def get_audio_edit_session(self, job_id: str, session_id: str) -> Optional[AudioEditSession]:
|
||||
"""Get a single audio edit session by ID."""
|
||||
try:
|
||||
doc_ref = (
|
||||
self.db.collection(self.collection)
|
||||
.document(job_id)
|
||||
.collection("audio_edit_sessions")
|
||||
.document(session_id)
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
return AudioEditSession.from_dict(doc.to_dict())
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting audio edit session {session_id} for job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
def delete_audio_edit_session(self, job_id: str, session_id: str) -> None:
|
||||
"""Delete a single audio edit session."""
|
||||
try:
|
||||
doc_ref = (
|
||||
self.db.collection(self.collection)
|
||||
.document(job_id)
|
||||
.collection("audio_edit_sessions")
|
||||
.document(session_id)
|
||||
)
|
||||
doc_ref.delete()
|
||||
logger.info(f"Deleted audio edit session {session_id} for job {job_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting audio edit session {session_id} for job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
def delete_audio_edit_sessions_subcollection(self, job_id: str, batch_size: int = 500) -> int:
|
||||
"""Delete all audio edit sessions for a job (used when deleting a job)."""
|
||||
try:
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_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} audio edit sessions for job {job_id}")
|
||||
|
||||
return deleted_count
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting audio edit sessions subcollection for job {job_id}: {e}")
|
||||
return 0
|
||||
|
||||
def get_latest_audio_edit_session_hash(self, job_id: str) -> Optional[str]:
|
||||
"""Get the data_hash of the most recent audio edit session for deduplication."""
|
||||
try:
|
||||
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_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 audio edit session hash for job {job_id}: {e}")
|
||||
return None
|
||||
|
||||
def delete_search_session(self, session_id: str) -> None:
|
||||
"""Delete a search session after it has been consumed by job creation.
|
||||
|
||||
@@ -708,3 +1042,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.
|
||||
|
||||
@@ -329,7 +329,10 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
# Get artist/title from config for proper naming
|
||||
artist = config.get("artist", "Unknown Artist")
|
||||
title = config.get("title", "Unknown Title")
|
||||
base_name = f"{artist} - {title}"
|
||||
# Sanitize for use in file paths (e.g., title "PORTRAIT/WALK/BORN" → "PORTRAIT_WALK_BORN")
|
||||
safe_artist = re.sub(r'[<>:"/\\|?*]', '_', artist)
|
||||
safe_title = re.sub(r'[<>:"/\\|?*]', '_', title)
|
||||
base_name = f"{safe_artist} - {safe_title}"
|
||||
logger.info(f"Encoding for: {base_name}")
|
||||
|
||||
# Find input files in work_dir
|
||||
@@ -370,10 +373,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 +505,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(
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
"""
|
||||
IP geolocation service with Firestore caching.
|
||||
|
||||
Looks up IP addresses via ip-api.com (free, no key needed) and caches
|
||||
results in Firestore to avoid repeated lookups. Used by admin UI to
|
||||
enrich IP displays with country, city, ISP, and ASN info.
|
||||
"""
|
||||
import ipaddress
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, List
|
||||
|
||||
import httpx
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
IP_GEOLOCATION_COLLECTION = "ip_geolocation"
|
||||
CACHE_TTL_DAYS = 90 # Cache results for 90 days
|
||||
IP_API_URL = "http://ip-api.com/json"
|
||||
IP_API_BATCH_URL = "http://ip-api.com/batch"
|
||||
IP_API_FIELDS = "status,country,countryCode,regionName,city,isp,org,as,timezone,query"
|
||||
RATE_LIMIT_PER_MINUTE = 45
|
||||
|
||||
|
||||
def _is_private_ip(ip: str) -> bool:
|
||||
"""Check if an IP is private/reserved (not routable on the internet)."""
|
||||
try:
|
||||
addr = ipaddress.ip_address(ip)
|
||||
return addr.is_private or addr.is_reserved or addr.is_loopback or addr.is_link_local
|
||||
except ValueError:
|
||||
return True # Invalid IP
|
||||
|
||||
|
||||
def _parse_ip_api_response(data: dict) -> dict:
|
||||
"""Parse ip-api.com response into our standard format."""
|
||||
if data.get("status") != "success":
|
||||
return {
|
||||
"status": "fail",
|
||||
"ip": data.get("query", ""),
|
||||
"cached_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
|
||||
# Parse AS field: "AS14615 Comporium Inc" -> number + name
|
||||
as_field = data.get("as", "")
|
||||
as_number = ""
|
||||
as_name = ""
|
||||
if as_field:
|
||||
parts = as_field.split(" ", 1)
|
||||
as_number = parts[0] if parts else ""
|
||||
as_name = parts[1] if len(parts) > 1 else ""
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"ip": data.get("query", ""),
|
||||
"country": data.get("country", ""),
|
||||
"country_code": data.get("countryCode", ""),
|
||||
"region": data.get("regionName", ""),
|
||||
"city": data.get("city", ""),
|
||||
"isp": data.get("isp", ""),
|
||||
"org": data.get("org", ""),
|
||||
"as_number": as_number,
|
||||
"as_name": as_name,
|
||||
"timezone": data.get("timezone", ""),
|
||||
"cached_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
|
||||
|
||||
class IpGeolocationService:
|
||||
"""IP geolocation lookup with Firestore caching."""
|
||||
|
||||
def __init__(self):
|
||||
settings = get_settings()
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
self._last_request_times: List[float] = []
|
||||
|
||||
def _check_rate_limit(self):
|
||||
"""Simple rate limiter — sleep if approaching 45 req/min."""
|
||||
now = time.time()
|
||||
# Remove entries older than 60 seconds
|
||||
self._last_request_times = [
|
||||
t for t in self._last_request_times if now - t < 60
|
||||
]
|
||||
if len(self._last_request_times) >= RATE_LIMIT_PER_MINUTE - 5:
|
||||
# Getting close to limit, wait
|
||||
sleep_time = 60 - (now - self._last_request_times[0])
|
||||
if sleep_time > 0:
|
||||
logger.info(f"IP geolocation rate limit: sleeping {sleep_time:.1f}s")
|
||||
time.sleep(sleep_time)
|
||||
self._last_request_times.append(time.time())
|
||||
|
||||
def _get_cached(self, ip: str) -> Optional[dict]:
|
||||
"""Get cached geolocation data for an IP."""
|
||||
try:
|
||||
# Firestore doc IDs can't contain '/' so IPv6 with :: is fine,
|
||||
# but we need to sanitize for doc ID
|
||||
doc_id = ip.replace("/", "_")
|
||||
doc = self.db.collection(IP_GEOLOCATION_COLLECTION).document(doc_id).get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
|
||||
data = doc.to_dict()
|
||||
|
||||
# Check TTL
|
||||
cached_at = data.get("cached_at", "")
|
||||
if cached_at:
|
||||
try:
|
||||
cached_dt = datetime.fromisoformat(cached_at)
|
||||
if datetime.utcnow() - cached_dt > timedelta(days=CACHE_TTL_DAYS):
|
||||
return None # Expired
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
return data
|
||||
except Exception:
|
||||
logger.exception(f"Error reading IP geo cache for {ip}")
|
||||
return None
|
||||
|
||||
def _cache_result(self, ip: str, data: dict):
|
||||
"""Store geolocation result in Firestore cache."""
|
||||
try:
|
||||
doc_id = ip.replace("/", "_")
|
||||
self.db.collection(IP_GEOLOCATION_COLLECTION).document(doc_id).set(data)
|
||||
except Exception:
|
||||
logger.exception(f"Error caching IP geo for {ip}")
|
||||
|
||||
def lookup_ip(self, ip: str) -> dict:
|
||||
"""
|
||||
Look up geolocation for a single IP address.
|
||||
|
||||
Returns cached result if available, otherwise queries ip-api.com.
|
||||
"""
|
||||
if not ip or _is_private_ip(ip):
|
||||
return {"status": "private", "ip": ip or ""}
|
||||
|
||||
# Check cache
|
||||
cached = self._get_cached(ip)
|
||||
if cached:
|
||||
return cached
|
||||
|
||||
# Query ip-api.com
|
||||
try:
|
||||
self._check_rate_limit()
|
||||
with httpx.Client(timeout=10) as client:
|
||||
response = client.get(
|
||||
f"{IP_API_URL}/{ip}",
|
||||
params={"fields": IP_API_FIELDS},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
result = _parse_ip_api_response(data)
|
||||
self._cache_result(ip, result)
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error looking up IP {ip}")
|
||||
return {"status": "error", "ip": ip}
|
||||
|
||||
def lookup_ips_batch(self, ips: List[str]) -> Dict[str, dict]:
|
||||
"""
|
||||
Look up geolocation for multiple IPs.
|
||||
|
||||
Returns dict of ip -> geo data. Uses cache for known IPs,
|
||||
batches uncached lookups to ip-api.com.
|
||||
"""
|
||||
results = {}
|
||||
uncached = []
|
||||
|
||||
for ip in set(ips): # Deduplicate
|
||||
if not ip or _is_private_ip(ip):
|
||||
results[ip] = {"status": "private", "ip": ip or ""}
|
||||
continue
|
||||
|
||||
cached = self._get_cached(ip)
|
||||
if cached:
|
||||
results[ip] = cached
|
||||
else:
|
||||
uncached.append(ip)
|
||||
|
||||
if not uncached:
|
||||
return results
|
||||
|
||||
# ip-api.com batch endpoint accepts up to 100 IPs per request
|
||||
for i in range(0, len(uncached), 100):
|
||||
batch = uncached[i:i + 100]
|
||||
try:
|
||||
self._check_rate_limit()
|
||||
# Batch endpoint takes a JSON array of IPs
|
||||
payload = [
|
||||
{"query": ip, "fields": IP_API_FIELDS}
|
||||
for ip in batch
|
||||
]
|
||||
with httpx.Client(timeout=15) as client:
|
||||
response = client.post(IP_API_BATCH_URL, json=payload)
|
||||
response.raise_for_status()
|
||||
batch_results = response.json()
|
||||
|
||||
for data in batch_results:
|
||||
result = _parse_ip_api_response(data)
|
||||
ip = result.get("ip", data.get("query", ""))
|
||||
if ip:
|
||||
results[ip] = result
|
||||
self._cache_result(ip, result)
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error in batch IP lookup ({len(batch)} IPs)")
|
||||
# Mark failed IPs
|
||||
for ip in batch:
|
||||
if ip not in results:
|
||||
results[ip] = {"status": "error", "ip": ip}
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# Global instance
|
||||
_service = None
|
||||
|
||||
|
||||
def get_ip_geolocation_service() -> IpGeolocationService:
|
||||
"""Get the global IP geolocation service instance."""
|
||||
global _service
|
||||
if _service is None:
|
||||
_service = IpGeolocationService()
|
||||
return _service
|
||||
@@ -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,
|
||||
|
||||
@@ -22,6 +22,9 @@ STATUSES_BEFORE_AUDIO_START = {
|
||||
JobStatus.PENDING,
|
||||
JobStatus.SEARCHING_AUDIO,
|
||||
JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
JobStatus.AWAITING_AUDIO_EDIT,
|
||||
JobStatus.IN_AUDIO_EDIT,
|
||||
JobStatus.AUDIO_EDIT_COMPLETE,
|
||||
}
|
||||
|
||||
# Jobs in these statuses should NOT have lyrics_complete flag set
|
||||
@@ -29,6 +32,9 @@ STATUSES_BEFORE_LYRICS_START = {
|
||||
JobStatus.PENDING,
|
||||
JobStatus.SEARCHING_AUDIO,
|
||||
JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
JobStatus.AWAITING_AUDIO_EDIT,
|
||||
JobStatus.IN_AUDIO_EDIT,
|
||||
JobStatus.AUDIO_EDIT_COMPLETE,
|
||||
}
|
||||
|
||||
# Statuses where screens_progress.stage='complete' is valid
|
||||
@@ -120,6 +126,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
|
||||
|
||||
|
||||
@@ -170,11 +191,13 @@ def get_worker_valid_statuses() -> Dict[str, List[JobStatus]]:
|
||||
"audio_worker": [
|
||||
JobStatus.DOWNLOADING,
|
||||
JobStatus.DOWNLOADING_AUDIO,
|
||||
JobStatus.AUDIO_EDIT_COMPLETE,
|
||||
JobStatus.SEPARATING_STAGE1,
|
||||
JobStatus.SEPARATING_STAGE2,
|
||||
],
|
||||
"lyrics_worker": [
|
||||
JobStatus.DOWNLOADING,
|
||||
JobStatus.AUDIO_EDIT_COMPLETE,
|
||||
JobStatus.TRANSCRIBING,
|
||||
JobStatus.CORRECTING,
|
||||
],
|
||||
|
||||
+105
-46
@@ -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")
|
||||
|
||||
@@ -344,6 +350,14 @@ class JobManager:
|
||||
except Exception as e:
|
||||
logger.warning(f"Error deleting logs subcollection for job {job_id}: {e}")
|
||||
|
||||
# Delete audio edit sessions subcollection
|
||||
try:
|
||||
deleted_sessions = self.firestore.delete_audio_edit_sessions_subcollection(job_id)
|
||||
if deleted_sessions > 0:
|
||||
logger.info(f"Deleted {deleted_sessions} audio edit sessions for job {job_id}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Error deleting audio edit sessions for job {job_id}: {e}")
|
||||
|
||||
self.firestore.delete_job(job_id)
|
||||
logger.info(f"Deleted job {job_id}")
|
||||
|
||||
@@ -407,7 +421,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 +435,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,31 +445,31 @@ 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
|
||||
|
||||
# Generate review token when entering blocking states that need user action
|
||||
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
|
||||
if new_status == JobStatus.AWAITING_REVIEW:
|
||||
if new_status in (JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_AUDIO_EDIT):
|
||||
from backend.api.dependencies import generate_review_token
|
||||
review_token = generate_review_token()
|
||||
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 +477,7 @@ class JobManager:
|
||||
status=new_status,
|
||||
progress=progress,
|
||||
message=message,
|
||||
timeline_metadata=timeline_metadata,
|
||||
state_data=merged_state_data
|
||||
)
|
||||
else:
|
||||
@@ -468,7 +485,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
|
||||
@@ -521,10 +539,15 @@ class JobManager:
|
||||
self._send_push_notification(job, "complete")
|
||||
|
||||
# Idle reminder scheduling for blocking states
|
||||
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION]:
|
||||
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.AWAITING_AUDIO_EDIT]:
|
||||
self._schedule_idle_reminder(job, new_status)
|
||||
# Send push notification for blocking states
|
||||
action_type = "lyrics" if new_status == JobStatus.AWAITING_REVIEW else "instrumental"
|
||||
if new_status == JobStatus.AWAITING_AUDIO_EDIT:
|
||||
action_type = "audio_edit"
|
||||
elif new_status == JobStatus.AWAITING_REVIEW:
|
||||
action_type = "lyrics"
|
||||
else:
|
||||
action_type = "instrumental"
|
||||
self._send_push_notification(job, action_type)
|
||||
|
||||
except Exception as e:
|
||||
@@ -611,7 +634,12 @@ class JobManager:
|
||||
# Record when we entered blocking state (for idle detection)
|
||||
blocking_entered_at = datetime.utcnow().isoformat()
|
||||
|
||||
action_type = "lyrics" if new_status == JobStatus.AWAITING_REVIEW else "instrumental"
|
||||
if new_status == JobStatus.AWAITING_AUDIO_EDIT:
|
||||
action_type = "audio_edit"
|
||||
elif new_status == JobStatus.AWAITING_REVIEW:
|
||||
action_type = "lyrics"
|
||||
else:
|
||||
action_type = "instrumental"
|
||||
|
||||
# Update state_data with blocking state info (handle None state_data)
|
||||
existing_state_data = job.state_data or {}
|
||||
@@ -678,6 +706,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():
|
||||
@@ -719,6 +748,31 @@ class JobManager:
|
||||
self.update_job(job_id, {'state_data': state_data})
|
||||
logger.debug(f"Job {job_id} state_data updated: {key} = {value}")
|
||||
|
||||
def update_processing_metadata(self, job_id: str, section: str, data) -> None:
|
||||
"""
|
||||
Write data into processing_metadata[section] using Firestore dot-notation.
|
||||
|
||||
Each worker writes its own section once. This uses Firestore's nested
|
||||
field update to avoid overwriting other workers' sections.
|
||||
|
||||
The section can use dot-notation for deeper nesting, e.g.
|
||||
'timing.lyrics_worker_seconds' writes to processing_metadata.timing.lyrics_worker_seconds
|
||||
without overwriting other timing entries.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
section: Metadata section path (e.g., 'transcription', 'timing.audio_worker_seconds')
|
||||
data: Value to store (dict for sections, scalar for individual fields)
|
||||
"""
|
||||
try:
|
||||
self.firestore.update_job(job_id, {
|
||||
f"processing_metadata.{section}": data,
|
||||
})
|
||||
logger.debug(f"Job {job_id} processing_metadata.{section} updated")
|
||||
except Exception as e:
|
||||
# Log but don't raise - metadata storage should never fail a job
|
||||
logger.warning(f"Job {job_id}: Failed to update processing_metadata.{section}: {e}")
|
||||
|
||||
def delete_state_data_key(self, job_id: str, key: str) -> bool:
|
||||
"""
|
||||
Delete a specific key from the job's state_data field.
|
||||
@@ -877,22 +931,22 @@ class JobManager:
|
||||
|
||||
def check_parallel_processing_complete(self, job_id: str) -> bool:
|
||||
"""
|
||||
Check if both parallel tracks (audio + lyrics) are complete.
|
||||
|
||||
This is called after audio_complete or lyrics_complete to determine
|
||||
if we can proceed to screen generation.
|
||||
|
||||
Check if lyrics processing is complete (sufficient for screen generation).
|
||||
|
||||
Audio separation is decoupled from the critical path — users can start
|
||||
reviewing lyrics while separation continues in the background. The
|
||||
instrumental review page handles the case where separation isn't done yet.
|
||||
|
||||
Returns:
|
||||
True if both tracks complete, False otherwise
|
||||
True if lyrics are complete, False otherwise
|
||||
"""
|
||||
job = self.get_job(job_id)
|
||||
if not job:
|
||||
return False
|
||||
|
||||
audio_complete = job.state_data.get('audio_complete', False)
|
||||
|
||||
lyrics_complete = job.state_data.get('lyrics_complete', False)
|
||||
|
||||
return audio_complete and lyrics_complete
|
||||
|
||||
return lyrics_complete
|
||||
|
||||
async def start_job_processing(
|
||||
self,
|
||||
@@ -947,41 +1001,46 @@ 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:
|
||||
"""
|
||||
Mark audio processing as complete and check if can proceed.
|
||||
|
||||
If lyrics are also complete, automatically triggers screens worker.
|
||||
Mark audio processing as complete.
|
||||
|
||||
Audio completion is decoupled from the lyrics review path — it no longer
|
||||
triggers screens. The instrumental review page polls for this flag.
|
||||
"""
|
||||
self.update_state_data(job_id, 'audio_complete', True)
|
||||
|
||||
if self.check_parallel_processing_complete(job_id):
|
||||
logger.info(f"Job {job_id}: Both audio and lyrics complete, triggering screens worker")
|
||||
# Transition happens in screens worker
|
||||
# We just trigger it here
|
||||
self._trigger_screens_worker(job_id)
|
||||
|
||||
logger.info(f"Job {job_id}: Audio processing complete (separation finished)")
|
||||
|
||||
def mark_lyrics_complete(self, job_id: str) -> None:
|
||||
"""
|
||||
Mark lyrics processing as complete and check if can proceed.
|
||||
|
||||
If audio is also complete, automatically triggers screens worker.
|
||||
Mark lyrics processing as complete and trigger screens if ready.
|
||||
|
||||
Lyrics completion is the sole gate for screen generation and review.
|
||||
Audio separation runs independently in the background.
|
||||
"""
|
||||
self.update_state_data(job_id, 'lyrics_complete', True)
|
||||
|
||||
|
||||
if self.check_parallel_processing_complete(job_id):
|
||||
logger.info(f"Job {job_id}: Both audio and lyrics complete, triggering screens worker")
|
||||
# Transition happens in screens worker
|
||||
# We just trigger it here
|
||||
logger.info(f"Job {job_id}: Lyrics complete, triggering screens worker")
|
||||
self._trigger_screens_worker(job_id)
|
||||
|
||||
def _trigger_screens_worker(self, job_id: str) -> None:
|
||||
|
||||
@@ -61,6 +61,10 @@ class JobNotificationService:
|
||||
# Use hash-based routing for static hosting compatibility
|
||||
return f"{self.frontend_url}/app/jobs#/{job_id}/instrumental"
|
||||
|
||||
def _build_audio_edit_url(self, job_id: str) -> str:
|
||||
"""Build the audio edit URL for a job."""
|
||||
return f"{self.frontend_url}/app/jobs#/{job_id}/audio-edit"
|
||||
|
||||
async def send_job_completion_email(
|
||||
self,
|
||||
job_id: str,
|
||||
@@ -213,6 +217,7 @@ class JobNotificationService:
|
||||
action_type: Type of action needed:
|
||||
- "lyrics": Combined review (lyrics + instrumental selection) for normal jobs
|
||||
- "instrumental": Instrumental-only selection for finalise-only jobs
|
||||
- "audio_edit": Audio editing before processing begins
|
||||
user_name: User's display name
|
||||
artist: Artist name
|
||||
title: Song title
|
||||
@@ -249,6 +254,15 @@ class JobNotificationService:
|
||||
title=title,
|
||||
instrumental_url=instrumental_url,
|
||||
)
|
||||
elif action_type == "audio_edit":
|
||||
audio_edit_url = self._build_audio_edit_url(job_id)
|
||||
# Reuse the lyrics template but with the audio edit URL and different subject
|
||||
message_content = self.template_service.render_action_needed_lyrics(
|
||||
name=user_name,
|
||||
artist=artist,
|
||||
title=title,
|
||||
review_url=audio_edit_url,
|
||||
)
|
||||
else:
|
||||
logger.error(f"Unknown action type: {action_type}")
|
||||
return False
|
||||
|
||||
@@ -545,7 +545,10 @@ class LocalEncodingService:
|
||||
)
|
||||
output_files["with_vocals_mp4"] = config.output_with_vocals_mp4
|
||||
else:
|
||||
self.logger.info("[Step 2/6] Skipped - video already MP4")
|
||||
self.logger.info("[Step 2/6] Skipped - video already MP4, copying as-is")
|
||||
import shutil
|
||||
shutil.copy2(config.karaoke_video, config.output_with_vocals_mp4)
|
||||
output_files["with_vocals_mp4"] = config.output_with_vocals_mp4
|
||||
|
||||
# Step 3: Encode lossless 4K MP4
|
||||
if config.output_lossless_4k_mp4:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -334,7 +334,8 @@ class ThemeService:
|
||||
style_params = self._update_asset_paths_in_style(theme_id, style_params)
|
||||
|
||||
# Upload modified style_params.json to job's style folder
|
||||
job_style_path = f"uploads/{job_id}/style/style_params.json"
|
||||
# Uses jobs/ prefix (not uploads/) to avoid GCS lifecycle deletion rule
|
||||
job_style_path = f"jobs/{job_id}/style/style_params.json"
|
||||
self.storage.upload_json(job_style_path, style_params)
|
||||
|
||||
logger.info(f"Prepared job {job_id} style from theme {theme_id}")
|
||||
|
||||
@@ -48,7 +48,7 @@ class UserService:
|
||||
"""Service for user management and authentication."""
|
||||
|
||||
# Number of free credits granted to new users
|
||||
NEW_USER_FREE_CREDITS = 2
|
||||
NEW_USER_FREE_CREDITS = 1
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize user service with Firestore client."""
|
||||
@@ -107,15 +107,23 @@ class UserService:
|
||||
logger.exception(f"Error getting user {email}")
|
||||
return None
|
||||
|
||||
def get_or_create_user(self, email: str, tenant_id: Optional[str] = None) -> User:
|
||||
def get_or_create_user(
|
||||
self,
|
||||
email: str,
|
||||
tenant_id: Optional[str] = None,
|
||||
signup_ip: Optional[str] = None,
|
||||
device_fingerprint: Optional[str] = None,
|
||||
) -> User:
|
||||
"""
|
||||
Get existing user or create a new one.
|
||||
|
||||
New users receive a welcome credit to try the service.
|
||||
Welcome credits are granted on first magic link verification, not here.
|
||||
|
||||
Args:
|
||||
email: User's email address
|
||||
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
|
||||
signup_ip: Client IP address at signup (for rate limiting)
|
||||
device_fingerprint: Browser fingerprint at signup (for rate limiting)
|
||||
|
||||
Note: If user exists but has a different tenant_id, the existing user is returned.
|
||||
Users are uniquely identified by email, not email+tenant.
|
||||
@@ -129,22 +137,17 @@ class UserService:
|
||||
# (though features may be restricted per-tenant)
|
||||
return user
|
||||
|
||||
# Create new user with welcome credit
|
||||
welcome_credit = self.NEW_USER_FREE_CREDITS
|
||||
welcome_transaction = CreditTransaction(
|
||||
id=str(uuid.uuid4()),
|
||||
amount=welcome_credit,
|
||||
reason="welcome_credit",
|
||||
)
|
||||
|
||||
# Create new user with zero credits (welcome credits granted on first verification)
|
||||
user = User(
|
||||
email=email,
|
||||
credits=welcome_credit,
|
||||
credit_transactions=[welcome_transaction],
|
||||
credits=0,
|
||||
credit_transactions=[],
|
||||
tenant_id=tenant_id, # Associate with tenant on creation
|
||||
signup_ip=signup_ip,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
self._save_user(user)
|
||||
logger.info(f"Created new user: {email} with {welcome_credit} welcome credit(s) (tenant: {tenant_id or 'default'})")
|
||||
logger.info(f"Created new user: {email} (tenant: {tenant_id or 'default'}) — credits pending verification")
|
||||
return user
|
||||
|
||||
def _save_user(self, user: User) -> None:
|
||||
@@ -213,7 +216,8 @@ class UserService:
|
||||
email: str,
|
||||
ip_address: Optional[str] = None,
|
||||
user_agent: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
tenant_id: Optional[str] = None,
|
||||
device_fingerprint: Optional[str] = None,
|
||||
) -> MagicLinkToken:
|
||||
"""
|
||||
Create a magic link token for email authentication.
|
||||
@@ -226,11 +230,17 @@ class UserService:
|
||||
ip_address: Client IP for auditing
|
||||
user_agent: Client user agent for auditing
|
||||
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
|
||||
device_fingerprint: Browser fingerprint for anti-abuse
|
||||
"""
|
||||
email = email.lower()
|
||||
|
||||
# Ensure user exists (with tenant association)
|
||||
self.get_or_create_user(email, tenant_id=tenant_id)
|
||||
# Ensure user exists (with tenant association, signup IP, and fingerprint)
|
||||
self.get_or_create_user(
|
||||
email,
|
||||
tenant_id=tenant_id,
|
||||
signup_ip=ip_address,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Generate secure token
|
||||
token = secrets.token_urlsafe(32)
|
||||
@@ -242,6 +252,7 @@ class UserService:
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Save to Firestore
|
||||
@@ -359,6 +370,400 @@ class UserService:
|
||||
logger.exception("Error verifying magic link")
|
||||
return False, None, "An error occurred during verification"
|
||||
|
||||
def grant_welcome_credits_if_eligible(
|
||||
self,
|
||||
email: str,
|
||||
precomputed_eval: Optional[dict] = None,
|
||||
) -> Tuple[bool, str]:
|
||||
"""
|
||||
Grant welcome credits on first magic link verification.
|
||||
|
||||
Uses AI evaluation to check for abuse before granting. Fail-open:
|
||||
if evaluation fails, credits are granted anyway.
|
||||
|
||||
Uses a dedicated welcome_credits_granted flag as primary idempotency
|
||||
check (survives credit_transactions list trimming). Falls back to
|
||||
checking for welcome_credit transaction as secondary defense.
|
||||
|
||||
Args:
|
||||
email: User's email address.
|
||||
precomputed_eval: Optional pre-computed evaluation from magic link doc.
|
||||
Keys: credit_eval_decision, credit_eval_reasoning, credit_eval_error.
|
||||
If provided and has a decision, skips the AI call.
|
||||
|
||||
Returns:
|
||||
Tuple of (credits_granted: bool, status: str).
|
||||
status is one of: "granted", "denied", "already_granted", "not_found", "error"
|
||||
"""
|
||||
try:
|
||||
email = email.lower()
|
||||
user = self.get_user(email)
|
||||
if not user:
|
||||
return False, "not_found"
|
||||
|
||||
# Primary check: dedicated flag (survives transaction list trimming)
|
||||
if user.welcome_credits_granted:
|
||||
return False, "already_granted"
|
||||
|
||||
# Secondary check: look for existing welcome_credit transaction
|
||||
for txn in user.credit_transactions:
|
||||
if txn.reason == "welcome_credit":
|
||||
return False, "already_granted"
|
||||
|
||||
# AI evaluation: check for abuse signals before granting
|
||||
# Use pre-computed result from magic link if available
|
||||
try:
|
||||
from backend.services.credit_evaluation_service import (
|
||||
get_credit_evaluation_service,
|
||||
CreditEvaluation,
|
||||
)
|
||||
precomputed_decision = (precomputed_eval or {}).get("credit_eval_decision")
|
||||
if precomputed_decision:
|
||||
logger.info(f"Using pre-computed credit eval for {email}: {precomputed_decision}")
|
||||
evaluation = CreditEvaluation(
|
||||
decision=precomputed_decision,
|
||||
reasoning=(precomputed_eval or {}).get("credit_eval_reasoning", ""),
|
||||
confidence=1.0,
|
||||
error=(precomputed_eval or {}).get("credit_eval_error"),
|
||||
)
|
||||
else:
|
||||
eval_service = get_credit_evaluation_service()
|
||||
evaluation = eval_service.evaluate(email, "welcome")
|
||||
|
||||
if evaluation.decision == "deny":
|
||||
# Mark as evaluated but not granted so we don't re-evaluate
|
||||
self.update_user(email, welcome_credits_granted=True)
|
||||
logger.info(
|
||||
f"Denied welcome credits to {email}: {evaluation.reasoning}"
|
||||
)
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
get_email_service().send_credit_denied_email(email, "welcome")
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send credit denied email to {email}")
|
||||
return False, "denied"
|
||||
|
||||
if evaluation.decision == "pending_review":
|
||||
# Don't mark welcome_credits_granted — allow retry after manual review
|
||||
logger.info(
|
||||
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
|
||||
)
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
email_service.send_credit_review_needed_email(
|
||||
email, "welcome", evaluation.reasoning, signals=evaluation.signals,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to send review needed email for {email}")
|
||||
return False, "pending_review"
|
||||
except Exception:
|
||||
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
email_service.send_credit_review_needed_email(
|
||||
email, "welcome", f"Evaluation error: {email}",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, "pending_review"
|
||||
|
||||
# Grant welcome credits
|
||||
welcome_credit = self.NEW_USER_FREE_CREDITS
|
||||
transaction = CreditTransaction(
|
||||
id=str(uuid.uuid4()),
|
||||
amount=welcome_credit,
|
||||
reason="welcome_credit",
|
||||
)
|
||||
|
||||
transactions = user.credit_transactions[-MAX_CREDIT_TRANSACTIONS + 1:]
|
||||
transactions.append(transaction)
|
||||
|
||||
new_balance = user.credits + welcome_credit
|
||||
self.update_user(
|
||||
email,
|
||||
credits=new_balance,
|
||||
credit_transactions=[t.model_dump(mode='json') for t in transactions],
|
||||
welcome_credits_granted=True,
|
||||
)
|
||||
|
||||
logger.info(f"Granted {welcome_credit} welcome credits to {email}")
|
||||
return True, "granted"
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error granting welcome credits to {email}")
|
||||
return False, "error"
|
||||
|
||||
# =========================================================================
|
||||
# Anti-Abuse Rate Limiting
|
||||
# =========================================================================
|
||||
|
||||
# Maximum new signups allowed per IP address in the rate limit window
|
||||
MAX_SIGNUPS_PER_IP = 2
|
||||
SIGNUP_RATE_LIMIT_HOURS = 24
|
||||
|
||||
def count_recent_signups_from_ip(self, ip_address: str, hours: int = 24) -> int:
|
||||
"""
|
||||
Count new user accounts created from this IP in the last N hours.
|
||||
|
||||
Queries gen_users where signup_ip matches and created_at is recent.
|
||||
Used to rate-limit new account creation per IP address.
|
||||
|
||||
Args:
|
||||
ip_address: Client IP to check
|
||||
hours: Lookback window in hours (default: 24)
|
||||
|
||||
Returns:
|
||||
Number of recent signups from this IP
|
||||
"""
|
||||
try:
|
||||
cutoff = datetime.utcnow() - timedelta(hours=hours)
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("signup_ip", "==", ip_address))
|
||||
.where(filter=FieldFilter("created_at", ">=", cutoff))
|
||||
)
|
||||
|
||||
count = 0
|
||||
for _ in query.stream():
|
||||
count += 1
|
||||
return count
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error counting signups from IP {ip_address}")
|
||||
# On error, don't block — return 0 to allow the request
|
||||
return 0
|
||||
|
||||
def count_recent_signups_from_fingerprint(
|
||||
self, device_fingerprint: str, hours: int = 24
|
||||
) -> int:
|
||||
"""
|
||||
Count new user accounts created with this device fingerprint in the last N hours.
|
||||
|
||||
Args:
|
||||
device_fingerprint: Browser fingerprint to check
|
||||
hours: Lookback window in hours (default: 24)
|
||||
|
||||
Returns:
|
||||
Number of recent signups from this fingerprint
|
||||
"""
|
||||
try:
|
||||
cutoff = datetime.utcnow() - timedelta(hours=hours)
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("device_fingerprint", "==", device_fingerprint))
|
||||
.where(filter=FieldFilter("created_at", ">=", cutoff))
|
||||
)
|
||||
|
||||
count = 0
|
||||
for _ in query.stream():
|
||||
count += 1
|
||||
return count
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error counting signups from fingerprint")
|
||||
return 0
|
||||
|
||||
def is_signup_rate_limited(
|
||||
self, ip_address: Optional[str] = None, device_fingerprint: Optional[str] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Check if a signup should be rate limited based on IP and/or fingerprint.
|
||||
|
||||
Either signal hitting the limit triggers a block.
|
||||
"""
|
||||
if ip_address:
|
||||
ip_count = self.count_recent_signups_from_ip(
|
||||
ip_address, hours=self.SIGNUP_RATE_LIMIT_HOURS
|
||||
)
|
||||
if ip_count >= self.MAX_SIGNUPS_PER_IP:
|
||||
return True
|
||||
|
||||
if device_fingerprint:
|
||||
fp_count = self.count_recent_signups_from_fingerprint(
|
||||
device_fingerprint, hours=self.SIGNUP_RATE_LIMIT_HOURS
|
||||
)
|
||||
if fp_count >= self.MAX_SIGNUPS_PER_IP:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
# =========================================================================
|
||||
# Anti-Abuse Investigation
|
||||
# =========================================================================
|
||||
|
||||
def find_users_by_signup_ip(self, ip_address: str) -> List[User]:
|
||||
"""Find all users who signed up from this IP address."""
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("signup_ip", "==", ip_address))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(50)
|
||||
)
|
||||
return [User(**doc.to_dict()) for doc in query.stream()]
|
||||
except Exception:
|
||||
logger.exception(f"Error finding users by IP {ip_address}")
|
||||
return []
|
||||
|
||||
def find_users_by_fingerprint(self, device_fingerprint: str) -> List[User]:
|
||||
"""Find all users who signed up with this device fingerprint."""
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("device_fingerprint", "==", device_fingerprint))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(50)
|
||||
)
|
||||
return [User(**doc.to_dict()) for doc in query.stream()]
|
||||
except Exception:
|
||||
logger.exception(f"Error finding users by fingerprint")
|
||||
return []
|
||||
|
||||
def find_suspicious_accounts(self, min_jobs: int = 2, max_spend: int = 0) -> List[User]:
|
||||
"""
|
||||
Find accounts with many jobs but no spend (potential free-credit abusers).
|
||||
|
||||
Args:
|
||||
min_jobs: Minimum total_jobs_created to flag (default: 2)
|
||||
max_spend: Maximum total_spent in cents to include (default: 0 = free only)
|
||||
"""
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("total_jobs_created", ">=", min_jobs))
|
||||
.order_by("total_jobs_created", direction=firestore.Query.DESCENDING)
|
||||
.limit(100)
|
||||
)
|
||||
users = []
|
||||
for doc in query.stream():
|
||||
user = User(**doc.to_dict())
|
||||
if user.total_spent <= max_spend and not is_internal_or_test_email(user.email):
|
||||
users.append(user)
|
||||
return users
|
||||
except Exception:
|
||||
logger.exception("Error finding suspicious accounts")
|
||||
return []
|
||||
|
||||
def find_related_accounts(self, email: str) -> dict:
|
||||
"""
|
||||
Given a user email, find all accounts that share the same signup IP
|
||||
or device fingerprint. Returns a dict with grouped results.
|
||||
"""
|
||||
user = self.get_user(email)
|
||||
if not user:
|
||||
return {"user": None, "by_ip": [], "by_fingerprint": []}
|
||||
|
||||
by_ip = []
|
||||
if user.signup_ip:
|
||||
by_ip = [
|
||||
u for u in self.find_users_by_signup_ip(user.signup_ip)
|
||||
if u.email != user.email
|
||||
]
|
||||
|
||||
by_fingerprint = []
|
||||
if user.device_fingerprint:
|
||||
by_fingerprint = [
|
||||
u for u in self.find_users_by_fingerprint(user.device_fingerprint)
|
||||
if u.email != user.email
|
||||
]
|
||||
|
||||
return {
|
||||
"user": user,
|
||||
"by_ip": by_ip,
|
||||
"by_fingerprint": by_fingerprint,
|
||||
}
|
||||
|
||||
def find_account_correlations(self) -> dict:
|
||||
"""
|
||||
Find clusters of accounts sharing the same fingerprint or signup IP.
|
||||
|
||||
Returns groups of 2+ accounts that share the same identifier,
|
||||
sorted by group size (largest first). Excludes internal/test accounts.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
|
||||
# Known bad IPs (load balancer, metadata, placeholder) that don't represent real client IPs
|
||||
BAD_IPS = {"169.254.169.126", "unknown", ""}
|
||||
|
||||
try:
|
||||
all_users = []
|
||||
for doc in self.db.collection(USERS_COLLECTION).stream():
|
||||
user = User(**doc.to_dict())
|
||||
if not is_internal_or_test_email(user.email):
|
||||
all_users.append(user)
|
||||
|
||||
# Group by fingerprint
|
||||
fp_groups: dict[str, list[User]] = defaultdict(list)
|
||||
for user in all_users:
|
||||
if user.device_fingerprint:
|
||||
fp_groups[user.device_fingerprint].append(user)
|
||||
|
||||
# Group by IP (exclude known bad IPs)
|
||||
ip_groups: dict[str, list[User]] = defaultdict(list)
|
||||
for user in all_users:
|
||||
if user.signup_ip and user.signup_ip not in BAD_IPS:
|
||||
ip_groups[user.signup_ip].append(user)
|
||||
|
||||
# Collect user agents from latest sessions for users in clusters
|
||||
cluster_emails = set()
|
||||
for fp, users in fp_groups.items():
|
||||
if len(users) >= 2:
|
||||
cluster_emails.update(u.email for u in users)
|
||||
for ip, users in ip_groups.items():
|
||||
if len(users) >= 2:
|
||||
cluster_emails.update(u.email for u in users)
|
||||
|
||||
user_agents: dict[str, str] = {}
|
||||
for email in cluster_emails:
|
||||
try:
|
||||
sessions = (
|
||||
self.db.collection(SESSIONS_COLLECTION)
|
||||
.where(filter=FieldFilter("user_email", "==", email))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(1)
|
||||
.stream()
|
||||
)
|
||||
for session_doc in sessions:
|
||||
session_data = session_doc.to_dict()
|
||||
ua = session_data.get("user_agent")
|
||||
if ua:
|
||||
user_agents[email] = ua
|
||||
except Exception:
|
||||
pass # Skip if session lookup fails
|
||||
|
||||
# Build response - only clusters with 2+ users
|
||||
fingerprint_clusters = []
|
||||
for fp, users in fp_groups.items():
|
||||
if len(users) >= 2:
|
||||
fingerprint_clusters.append({
|
||||
"fingerprint": fp,
|
||||
"users": sorted(users, key=lambda u: u.created_at or "", reverse=True),
|
||||
})
|
||||
fingerprint_clusters.sort(key=lambda c: len(c["users"]), reverse=True)
|
||||
|
||||
ip_clusters = []
|
||||
for ip, users in ip_groups.items():
|
||||
if len(users) >= 2:
|
||||
ip_clusters.append({
|
||||
"ip": ip,
|
||||
"users": sorted(users, key=lambda u: u.created_at or "", reverse=True),
|
||||
})
|
||||
ip_clusters.sort(key=lambda c: len(c["users"]), reverse=True)
|
||||
|
||||
return {
|
||||
"fingerprint_clusters": fingerprint_clusters,
|
||||
"ip_clusters": ip_clusters,
|
||||
"user_agents": user_agents,
|
||||
}
|
||||
except Exception:
|
||||
logger.exception("Error finding account correlations")
|
||||
return {"fingerprint_clusters": [], "ip_clusters": [], "user_agents": {}}
|
||||
|
||||
# =========================================================================
|
||||
# Session Management
|
||||
# =========================================================================
|
||||
@@ -368,7 +773,8 @@ class UserService:
|
||||
user_email: str,
|
||||
ip_address: Optional[str] = None,
|
||||
user_agent: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
tenant_id: Optional[str] = None,
|
||||
device_fingerprint: Optional[str] = None,
|
||||
) -> Session:
|
||||
"""
|
||||
Create a new session for an authenticated user.
|
||||
@@ -378,6 +784,7 @@ class UserService:
|
||||
ip_address: Client IP for auditing
|
||||
user_agent: Client user agent for auditing
|
||||
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
|
||||
device_fingerprint: Browser fingerprint for cross-account correlation
|
||||
"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
token_prefix = token[:12]
|
||||
@@ -389,6 +796,7 @@ class UserService:
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Serialize and write to Firestore
|
||||
|
||||
@@ -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,19 +361,35 @@ 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.
|
||||
|
||||
Always uses Cloud Run Jobs to avoid instance termination during long-running
|
||||
Modal API calls. The BackgroundTasks approach caused Cloud Run to terminate
|
||||
instances mid-processing when no HTTP requests were active.
|
||||
Uses Cloud Run Jobs with L4 GPU in us-east4 for direct audio separation.
|
||||
"""
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="audio-separation-job",
|
||||
worker_module="audio_worker",
|
||||
location="us-east4", # GPU job runs in us-east4 (L4 quota)
|
||||
)
|
||||
|
||||
async def trigger_lyrics_worker(self, job_id: str) -> bool:
|
||||
@@ -431,6 +447,7 @@ class WorkerService:
|
||||
job_id: str,
|
||||
cloud_run_job_name: str,
|
||||
worker_module: str,
|
||||
location: str | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Trigger a worker as a Cloud Run Job.
|
||||
@@ -443,6 +460,7 @@ class WorkerService:
|
||||
job_id: Job ID to process
|
||||
cloud_run_job_name: Name of the Cloud Run Job (e.g., "lyrics-transcription-job")
|
||||
worker_module: Worker module name (e.g., "lyrics_worker")
|
||||
location: GCP region for the job (defaults to settings.gcp_region)
|
||||
|
||||
Returns:
|
||||
True if job was triggered successfully, False otherwise
|
||||
@@ -455,7 +473,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger Cloud Run Job")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
location = location or self.settings.gcp_region
|
||||
job_name = f"projects/{project}/locations/{location}/jobs/{cloud_run_job_name}"
|
||||
|
||||
# Create Cloud Run Jobs client
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -150,15 +150,15 @@ class TestStyleLoadingFix:
|
||||
}
|
||||
|
||||
# Upload style JSON to GCS (the CORRECT location)
|
||||
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
|
||||
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
|
||||
self.storage.upload_string(json.dumps(style_json), style_gcs_path)
|
||||
|
||||
# Upload mock assets
|
||||
assets = {
|
||||
"intro_background": f"uploads/{job_id}/style/intro_background.png",
|
||||
"karaoke_background": f"uploads/{job_id}/style/karaoke_background.png",
|
||||
"end_background": f"uploads/{job_id}/style/end_background.png",
|
||||
"font": f"uploads/{job_id}/style/font.ttf",
|
||||
"intro_background": f"jobs/{job_id}/style/intro_background.png",
|
||||
"karaoke_background": f"jobs/{job_id}/style/karaoke_background.png",
|
||||
"end_background": f"jobs/{job_id}/style/end_background.png",
|
||||
"font": f"jobs/{job_id}/style/font.ttf",
|
||||
}
|
||||
|
||||
for asset_key, gcs_path in assets.items():
|
||||
@@ -255,7 +255,7 @@ class TestStyleLoadingFix:
|
||||
job_id = f"test-bug-{int(time.time() * 1000)}"
|
||||
|
||||
# Upload style to CORRECT location
|
||||
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
|
||||
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
|
||||
self.storage.upload_string('{"karaoke": {"font_size": 100}}', style_gcs_path)
|
||||
|
||||
# Create job with styles in CORRECT location
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
"""
|
||||
Unit tests for admin audio edit review endpoints.
|
||||
|
||||
Tests the GET /api/admin/audio-edit-reviews and
|
||||
GET /api/admin/audio-edit-reviews/{job_id} endpoints.
|
||||
"""
|
||||
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
|
||||
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
|
||||
|
||||
|
||||
# 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,
|
||||
)
|
||||
|
||||
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _make_audio_edit_job_doc(job_id, artist="Test Artist", title="Test Song",
|
||||
user_email="user@example.com", status="complete",
|
||||
has_edit_stack=True):
|
||||
"""Create a mock Firestore document for a job with audio edits."""
|
||||
doc = Mock()
|
||||
doc.id = job_id
|
||||
now = datetime.now(timezone.utc)
|
||||
state_data = {}
|
||||
if has_edit_stack:
|
||||
state_data["audio_edit_stack"] = [
|
||||
{"edit_id": "e1", "operation": "cut", "gcs_path": f"jobs/{job_id}/edits/e1.flac"}
|
||||
]
|
||||
|
||||
doc.to_dict.return_value = {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"user_email": user_email,
|
||||
"status": status,
|
||||
"state_data": state_data,
|
||||
"file_urls": {},
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
return doc
|
||||
|
||||
|
||||
def _make_session(job_id, trigger="auto", edit_count=3):
|
||||
"""Create a mock AudioEditSession."""
|
||||
return AudioEditSession(
|
||||
session_id="sess-1",
|
||||
job_id=job_id,
|
||||
user_email="user@example.com",
|
||||
edit_count=edit_count,
|
||||
trigger=trigger,
|
||||
audio_duration_seconds=150.0,
|
||||
original_duration_seconds=225.0,
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
summary=AudioEditSessionSummary(
|
||||
total_operations=edit_count,
|
||||
operations_breakdown={"cut": 2, "mute": 1},
|
||||
duration_change_seconds=-75.0,
|
||||
net_duration_seconds=150.0,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestListAudioEditReviews:
|
||||
"""Tests for GET /api/admin/audio-edit-reviews."""
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_returns_jobs_with_edit_stacks(self, mock_get_user_service, MockFS, client):
|
||||
"""Jobs with audio edit stacks should appear."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_audio_edit_job_doc("job-1", has_edit_stack=True),
|
||||
_make_audio_edit_job_doc("job-2", has_edit_stack=False),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
# job-2 has no edit stack and no sessions subcollection
|
||||
sessions_ref = Mock()
|
||||
sessions_ref.limit.return_value.stream.return_value = iter([])
|
||||
mock_db.collection.return_value.document.return_value.collection.return_value = sessions_ref
|
||||
|
||||
# Sessions for job-1
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = [
|
||||
_make_session("job-1")
|
||||
]
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["job_id"] == "job-1"
|
||||
assert data["reviews"][0]["session_count"] == 1
|
||||
assert data["reviews"][0]["total_edits"] == 3
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_search_filter(self, mock_get_user_service, MockFS, client):
|
||||
"""Search should filter by artist, title, and email."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_audio_edit_job_doc("job-1", artist="Beatles", title="Hey Jude"),
|
||||
_make_audio_edit_job_doc("job-2", artist="Queen", title="Bohemian Rhapsody"),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = [_make_session("job-1")]
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews?search=beatles")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["artist"] == "Beatles"
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_pagination(self, mock_get_user_service, MockFS, client):
|
||||
"""Pagination should work with offset and limit."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [_make_audio_edit_job_doc(f"job-{i}") for i in range(5)]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = []
|
||||
|
||||
response = client.get("/api/admin/audio-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.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_exclude_test_emails(self, mock_get_user_service, MockFS, client):
|
||||
"""Test emails should be excluded when exclude_test=true."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_audio_edit_job_doc("job-1", user_email="real@example.com"),
|
||||
_make_audio_edit_job_doc("job-2", user_email="test@inbox.testmail.app"),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = []
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews?exclude_test=true")
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["user_email"] == "real@example.com"
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_includes_in_audio_edit_jobs(self, mock_get_user_service, MockFS, client):
|
||||
"""Jobs in audio edit statuses should appear even without edit stack."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_audio_edit_job_doc("job-1", status="in_audio_edit", has_edit_stack=False),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = []
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews")
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["job_id"] == "job-1"
|
||||
|
||||
|
||||
class TestGetAudioEditReviewDetail:
|
||||
"""Tests for GET /api/admin/audio-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/audio-edit-reviews/nonexistent")
|
||||
assert response.status_code == 404
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.AudioTranscodingService")
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_returns_full_detail(self, MockJobManager, MockStorage, MockFS, MockTranscoding, client):
|
||||
"""Should return job metadata, sessions, edit stack, and audio URLs."""
|
||||
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/edited.flac"
|
||||
job.state_data = {
|
||||
"audio_edit_stack": [
|
||||
{"edit_id": "e1", "operation": "cut", "gcs_path": "jobs/test-job/edits/e1.flac",
|
||||
"duration_before": 225, "duration_after": 150, "timestamp": "2026-03-01T10:00:00"},
|
||||
],
|
||||
"original_input_media_gcs_path": "jobs/test-job/input/original.flac",
|
||||
}
|
||||
MockJobManager.return_value.get_job.return_value = job
|
||||
|
||||
storage = MockStorage.return_value
|
||||
storage.file_exists.return_value = False
|
||||
|
||||
session = _make_session("test-job", trigger="submit")
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = [session]
|
||||
|
||||
response = client.get("/api/admin/audio-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 len(data["sessions"]) == 1
|
||||
assert data["sessions"][0]["trigger"] == "submit"
|
||||
assert len(data["edit_stack"]) == 1
|
||||
assert data["edit_stack"][0]["operation"] == "cut"
|
||||
|
||||
@patch("backend.services.firestore_service.FirestoreService")
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_handles_empty_state_gracefully(self, MockJobManager, MockStorage, MockFS, client):
|
||||
"""Should handle jobs with no edit data gracefully."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job"
|
||||
job.artist = "Test"
|
||||
job.title = "Song"
|
||||
job.user_email = "u@e.com"
|
||||
job.status = JobStatus.AWAITING_AUDIO_EDIT
|
||||
job.created_at = None
|
||||
job.updated_at = None
|
||||
job.input_media_gcs_path = None
|
||||
job.state_data = {}
|
||||
MockJobManager.return_value.get_job.return_value = job
|
||||
|
||||
storage = MockStorage.return_value
|
||||
storage.file_exists.return_value = False
|
||||
|
||||
MockFS.return_value.list_audio_edit_sessions.return_value = []
|
||||
|
||||
response = client.get("/api/admin/audio-edit-reviews/test-job")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["sessions"] == []
|
||||
assert data["edit_stack"] == []
|
||||
assert data["edit_log"] is None
|
||||
@@ -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,460 @@
|
||||
"""
|
||||
Unit tests for admin feedback endpoint and feedback email notification.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from datetime import datetime
|
||||
|
||||
from backend.services.email_service import EmailService
|
||||
|
||||
|
||||
class TestAdminFeedbackEndpoint:
|
||||
"""Tests for GET /api/admin/feedback endpoint."""
|
||||
|
||||
def _make_feedback_doc(self, email="user@example.com", overall=4, **kwargs):
|
||||
"""Create a mock Firestore feedback document."""
|
||||
doc = Mock()
|
||||
doc.id = kwargs.get("id", "test-id-1")
|
||||
data = {
|
||||
"id": doc.id,
|
||||
"user_email": email,
|
||||
"created_at": kwargs.get("created_at", datetime(2026, 3, 1, 12, 0, 0)),
|
||||
"overall_rating": overall,
|
||||
"ease_of_use_rating": kwargs.get("ease_of_use", 4),
|
||||
"lyrics_accuracy_rating": kwargs.get("lyrics_accuracy", 3),
|
||||
"correction_experience_rating": kwargs.get("correction_experience", 4),
|
||||
"what_went_well": kwargs.get("what_went_well", "Great app"),
|
||||
"what_could_improve": kwargs.get("what_could_improve", "More songs"),
|
||||
"additional_comments": kwargs.get("additional_comments", None),
|
||||
"would_recommend": kwargs.get("would_recommend", True),
|
||||
"would_use_again": kwargs.get("would_use_again", True),
|
||||
}
|
||||
doc.to_dict.return_value = data
|
||||
return doc
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_returns_items(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that feedback items are returned correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
|
||||
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 2
|
||||
assert len(result.items) == 2
|
||||
assert result.has_more is False
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_search_filter(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that search filters by email."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
|
||||
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search="alice", exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.items[0].user_email == "alice@example.com"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_exclude_test(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that test emails are excluded when exclude_test=True."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
|
||||
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
|
||||
doc2 = self._make_feedback_doc("test@inbox.testmail.app", 3, id="id-2")
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
# Make is_test_email return True for the test email
|
||||
mock_is_test.side_effect = lambda e: "testmail" in e
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=True,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.items[0].user_email == "alice@example.com"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_pagination(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test pagination with offset and limit."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
docs = [
|
||||
self._make_feedback_doc(f"user{i}@example.com", 4, id=f"id-{i}")
|
||||
for i in range(5)
|
||||
]
|
||||
mock_db.collection.return_value.stream.return_value = docs
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=2, offset=2, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 5
|
||||
assert len(result.items) == 2
|
||||
assert result.has_more is True
|
||||
assert result.offset == 2
|
||||
assert result.limit == 2
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_aggregate_stats(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that aggregate rating averages are computed correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc1 = self._make_feedback_doc("a@x.com", 5, id="id-1", ease_of_use=4, lyrics_accuracy=3, correction_experience=2)
|
||||
doc2 = self._make_feedback_doc("b@x.com", 3, id="id-2", ease_of_use=2, lyrics_accuracy=5, correction_experience=4)
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.avg_overall_rating == 4.0
|
||||
assert result.avg_ease_of_use_rating == 3.0
|
||||
assert result.avg_lyrics_accuracy_rating == 4.0
|
||||
assert result.avg_correction_experience_rating == 3.0
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_empty(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test empty results."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
|
||||
mock_db.collection.return_value.stream.return_value = []
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 0
|
||||
assert len(result.items) == 0
|
||||
assert result.avg_overall_rating is None
|
||||
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_handles_string_created_at(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that string timestamps (not datetime objects) are handled correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at="2026-03-01T12:00:00")
|
||||
mock_db.collection.return_value.stream.return_value = [doc]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.items[0].created_at == "2026-03-01T12:00:00"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_handles_none_created_at(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that None created_at is handled correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at=None)
|
||||
mock_db.collection.return_value.stream.return_value = [doc]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.items[0].created_at is None
|
||||
|
||||
|
||||
class TestSubmitFeedbackEmailIntegration:
|
||||
"""Test that submit_user_feedback correctly calls send_feedback_notification."""
|
||||
|
||||
@patch("backend.services.email_service.get_email_service")
|
||||
@patch("backend.services.auth_service.get_auth_service")
|
||||
def test_submit_feedback_sends_admin_notification(self, mock_get_auth, mock_get_email):
|
||||
"""Verify the caller (submit_user_feedback) passes correct args to email service."""
|
||||
import asyncio
|
||||
import uuid as uuid_mod
|
||||
from backend.api.routes.users import submit_user_feedback
|
||||
from backend.models.user import UserFeedbackRequest
|
||||
|
||||
# Mock auth
|
||||
mock_auth_svc = Mock()
|
||||
mock_auth_result = Mock()
|
||||
mock_auth_result.is_valid = True
|
||||
mock_auth_result.user_email = "alice@example.com"
|
||||
mock_auth_svc.validate_token_full.return_value = mock_auth_result
|
||||
mock_get_auth.return_value = mock_auth_svc
|
||||
|
||||
# Mock email service
|
||||
mock_email_svc = Mock()
|
||||
mock_email_svc.send_feedback_notification.return_value = True
|
||||
mock_get_email.return_value = mock_email_svc
|
||||
|
||||
# Mock user service with a db that has a collection mock
|
||||
mock_user_svc = Mock()
|
||||
mock_user = Mock()
|
||||
mock_user.email = "alice@example.com"
|
||||
mock_user.total_jobs_completed = 5
|
||||
mock_user.has_submitted_feedback = False
|
||||
mock_user_svc.get_or_create_user.return_value = mock_user
|
||||
mock_user_svc.update_user.return_value = None
|
||||
mock_user_svc.add_credits.return_value = None
|
||||
|
||||
went_well = "The lyrics synchronization was incredibly accurate and impressive overall"
|
||||
could_improve = "Speed could be faster for longer songs in the processing queue"
|
||||
|
||||
request = UserFeedbackRequest(
|
||||
overall_rating=4,
|
||||
ease_of_use_rating=3,
|
||||
lyrics_accuracy_rating=5,
|
||||
correction_experience_rating=2,
|
||||
what_went_well=went_well,
|
||||
what_could_improve=could_improve,
|
||||
additional_comments=None,
|
||||
would_recommend=True,
|
||||
would_use_again=False,
|
||||
)
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# Verify email notification was called with matching args
|
||||
mock_email_svc.send_feedback_notification.assert_called_once_with(
|
||||
user_email="alice@example.com",
|
||||
overall_rating=4,
|
||||
ease_of_use_rating=3,
|
||||
lyrics_accuracy_rating=5,
|
||||
correction_experience_rating=2,
|
||||
what_went_well=went_well,
|
||||
what_could_improve=could_improve,
|
||||
additional_comments=None,
|
||||
would_recommend=True,
|
||||
would_use_again=False,
|
||||
)
|
||||
|
||||
assert result.credits_granted == 1
|
||||
|
||||
@patch("backend.services.email_service.get_email_service")
|
||||
@patch("backend.services.auth_service.get_auth_service")
|
||||
def test_submit_feedback_continues_on_email_failure(self, mock_get_auth, mock_get_email):
|
||||
"""Verify feedback submission succeeds even if email notification fails."""
|
||||
import asyncio
|
||||
import uuid as uuid_mod
|
||||
from backend.api.routes.users import submit_user_feedback
|
||||
from backend.models.user import UserFeedbackRequest
|
||||
|
||||
mock_auth_svc = Mock()
|
||||
mock_auth_result = Mock()
|
||||
mock_auth_result.is_valid = True
|
||||
mock_auth_result.user_email = "bob@example.com"
|
||||
mock_auth_svc.validate_token_full.return_value = mock_auth_result
|
||||
mock_get_auth.return_value = mock_auth_svc
|
||||
|
||||
# Email service throws an exception
|
||||
mock_email_svc = Mock()
|
||||
mock_email_svc.send_feedback_notification.side_effect = Exception("SendGrid down")
|
||||
mock_get_email.return_value = mock_email_svc
|
||||
|
||||
mock_user_svc = Mock()
|
||||
mock_user = Mock()
|
||||
mock_user.email = "bob@example.com"
|
||||
mock_user.total_jobs_completed = 3
|
||||
mock_user.has_submitted_feedback = False
|
||||
mock_user_svc.get_or_create_user.return_value = mock_user
|
||||
|
||||
request = UserFeedbackRequest(
|
||||
overall_rating=5,
|
||||
ease_of_use_rating=5,
|
||||
lyrics_accuracy_rating=5,
|
||||
correction_experience_rating=5,
|
||||
what_went_well="Everything was perfect and I really enjoyed the experience a lot",
|
||||
)
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# User still gets credits even though email failed
|
||||
assert result.status == "success"
|
||||
assert result.credits_granted == 1
|
||||
|
||||
|
||||
class TestFeedbackEmailNotification:
|
||||
"""Tests for send_feedback_notification email method."""
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
def test_send_feedback_notification_calls_provider(self, mock_get_provider):
|
||||
"""Test that feedback notification sends email via provider."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = True
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
result = service.send_feedback_notification(
|
||||
user_email="alice@example.com",
|
||||
overall_rating=5,
|
||||
ease_of_use_rating=4,
|
||||
lyrics_accuracy_rating=3,
|
||||
correction_experience_rating=4,
|
||||
what_went_well="Great lyrics sync",
|
||||
what_could_improve="More song variety",
|
||||
additional_comments=None,
|
||||
would_recommend=True,
|
||||
would_use_again=True,
|
||||
)
|
||||
|
||||
assert result is True
|
||||
mock_provider.send_email.assert_called_once()
|
||||
call_args = mock_provider.send_email.call_args
|
||||
|
||||
# Check email is sent to admin
|
||||
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
|
||||
assert to_email == "admin@nomadkaraoke.com"
|
||||
|
||||
# Check subject contains user email and rating
|
||||
subject = call_args.kwargs.get("subject") or call_args[0][1]
|
||||
assert "alice@example.com" in subject
|
||||
assert "5/5" in subject
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
def test_send_feedback_notification_content(self, mock_get_provider):
|
||||
"""Test that feedback notification email contains all feedback fields."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = True
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
service.send_feedback_notification(
|
||||
user_email="bob@example.com",
|
||||
overall_rating=3,
|
||||
ease_of_use_rating=2,
|
||||
lyrics_accuracy_rating=4,
|
||||
correction_experience_rating=5,
|
||||
what_went_well="Easy to use",
|
||||
what_could_improve="Better mobile support",
|
||||
additional_comments="Love it overall",
|
||||
would_recommend=False,
|
||||
would_use_again=True,
|
||||
)
|
||||
|
||||
call_args = mock_provider.send_email.call_args
|
||||
html_content = call_args.kwargs.get("html_content") or call_args[0][2]
|
||||
text_content = call_args.kwargs.get("text_content") or call_args[0][3]
|
||||
|
||||
# Check HTML contains feedback text
|
||||
assert "Easy to use" in html_content
|
||||
assert "Better mobile support" in html_content
|
||||
assert "Love it overall" in html_content
|
||||
assert "bob@example.com" in html_content
|
||||
|
||||
# Check plain text also contains feedback
|
||||
assert "Easy to use" in text_content
|
||||
assert "Better mobile support" in text_content
|
||||
assert "3/5" in text_content
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
@patch.dict("os.environ", {"ADMIN_NOTIFICATION_EMAIL": "custom@admin.com"})
|
||||
def test_send_feedback_notification_custom_admin_email(self, mock_get_provider):
|
||||
"""Test that admin email can be configured via env var."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = True
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
service.send_feedback_notification(
|
||||
user_email="test@example.com",
|
||||
overall_rating=4,
|
||||
ease_of_use_rating=4,
|
||||
lyrics_accuracy_rating=4,
|
||||
correction_experience_rating=4,
|
||||
)
|
||||
|
||||
call_args = mock_provider.send_email.call_args
|
||||
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
|
||||
assert to_email == "custom@admin.com"
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
def test_send_feedback_notification_returns_false_on_failure(self, mock_get_provider):
|
||||
"""Test that failure is returned when provider fails."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = False
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
result = service.send_feedback_notification(
|
||||
user_email="test@example.com",
|
||||
overall_rating=1,
|
||||
ease_of_use_rating=1,
|
||||
lyrics_accuracy_rating=1,
|
||||
correction_experience_rating=1,
|
||||
)
|
||||
|
||||
assert result is False
|
||||
@@ -1016,3 +1016,103 @@ class TestResetEndpointWithRealJobData:
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
assert response.json()["new_status"] == "pending"
|
||||
|
||||
|
||||
class TestResetJobToAwaitingAudioEdit:
|
||||
"""Tests for resetting job to AWAITING_AUDIO_EDIT state."""
|
||||
|
||||
def test_reset_to_awaiting_audio_edit_success(self, client, mock_job):
|
||||
"""Test resetting a job to awaiting_audio_edit."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_audio_edit"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["new_status"] == "awaiting_audio_edit"
|
||||
|
||||
def test_reset_clears_edit_stack_and_downstream_flags(self, client):
|
||||
"""Test that resetting clears audio edit state and downstream processing flags."""
|
||||
from datetime import UTC
|
||||
job = Job(
|
||||
job_id="test-job-123",
|
||||
status=JobStatus.COMPLETE,
|
||||
artist="Test",
|
||||
title="Song",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={
|
||||
"audio_edit_stack": [{"edit_id": "e1"}],
|
||||
"audio_edit_redo_stack": [{"edit_id": "e2"}],
|
||||
"audio_complete": True,
|
||||
"lyrics_complete": True,
|
||||
"review_complete": True,
|
||||
"screens_progress": {"stage": "complete"},
|
||||
}
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.update_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_audio_edit"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
cleared = data.get("cleared_data", [])
|
||||
assert "audio_edit_stack" in cleared
|
||||
assert "audio_edit_redo_stack" in cleared
|
||||
assert "audio_complete" in cleared
|
||||
assert "lyrics_complete" in cleared
|
||||
assert "review_complete" in cleared
|
||||
assert "screens_progress" in cleared
|
||||
|
||||
def test_reset_restores_original_input_media_path(self, client):
|
||||
"""Critical test: resetting to audio edit must restore the original
|
||||
input_media_gcs_path. The submit endpoint overwrites this with edited
|
||||
audio, so the reset must undo that to let the user start fresh."""
|
||||
from datetime import UTC
|
||||
job = Job(
|
||||
job_id="test-job-123",
|
||||
status=JobStatus.COMPLETE,
|
||||
artist="Test",
|
||||
title="Song",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
input_media_gcs_path="jobs/test-job-123/input/edited.flac",
|
||||
state_data={
|
||||
"original_input_media_gcs_path": "jobs/test-job-123/input/original.flac",
|
||||
"audio_edit_stack": [{"edit_id": "e1"}],
|
||||
}
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.update_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_audio_edit"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
# Verify the Firestore update included restoring the original path
|
||||
# The update goes through job_ref.update() which is the mock_db call
|
||||
# We check the update_job call for status change
|
||||
update_args = mock_jm.update_job.call_args[0][1]
|
||||
assert update_args["status"] == "awaiting_audio_edit"
|
||||
@@ -0,0 +1,833 @@
|
||||
"""
|
||||
Tests for anti-abuse improvements: credits on verification, IP rate limiting,
|
||||
and device fingerprinting.
|
||||
|
||||
Covers:
|
||||
- Phase 1: Welcome credits granted on verification, not account creation
|
||||
- Phase 2: Per-IP signup rate limiting (2 new accounts per 24h)
|
||||
- Phase 3: Device fingerprint rate limiting
|
||||
"""
|
||||
import pytest
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import MagicMock, Mock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
# Mock Firestore before importing modules that use it
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
from backend.models.user import (
|
||||
User,
|
||||
MagicLinkToken,
|
||||
CreditTransaction,
|
||||
SendMagicLinkRequest,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Phase 1: Credits on Verification
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGetOrCreateUserNoCredits:
|
||||
"""New users should be created with 0 credits."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_new_user_created_with_zero_credits(self, mock_fs, mock_settings):
|
||||
"""get_or_create_user creates users with 0 credits."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# Simulate user not found
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
user = service.get_or_create_user("new@example.com")
|
||||
|
||||
assert user.credits == 0
|
||||
assert user.credit_transactions == []
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_new_user_stores_signup_ip(self, mock_fs, mock_settings):
|
||||
"""get_or_create_user stores the signup IP."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
user = service.get_or_create_user(
|
||||
"new@example.com", signup_ip="1.2.3.4"
|
||||
)
|
||||
|
||||
assert user.signup_ip == "1.2.3.4"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_new_user_stores_device_fingerprint(self, mock_fs, mock_settings):
|
||||
"""get_or_create_user stores the device fingerprint."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
user = service.get_or_create_user(
|
||||
"new@example.com", device_fingerprint="abc123"
|
||||
)
|
||||
|
||||
assert user.device_fingerprint == "abc123"
|
||||
|
||||
|
||||
class TestGrantWelcomeCredits:
|
||||
"""Welcome credits should be granted on first verification."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_grants_credits_to_new_user(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible grants credits to user without welcome_credit txn."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User exists with 0 credits and no transactions
|
||||
user = User(email="new@example.com", credits=0, credit_transactions=[])
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
|
||||
from backend.services.credit_evaluation_service import CreditEvaluation
|
||||
mock_eval.return_value.evaluate.return_value = CreditEvaluation(decision="grant", reasoning="OK", confidence=1.0)
|
||||
granted, status = service.grant_welcome_credits_if_eligible("new@example.com")
|
||||
|
||||
assert granted is True
|
||||
# Verify update was called with credits and flag
|
||||
mock_db.collection.return_value.document.return_value.update.assert_called_once()
|
||||
update_args = mock_db.collection.return_value.document.return_value.update.call_args[0][0]
|
||||
assert update_args['credits'] == 1
|
||||
assert update_args['welcome_credits_granted'] is True
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_uses_precomputed_eval_when_provided(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible uses pre-computed eval and skips AI call."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="new@example.com", credits=0, credit_transactions=[])
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
|
||||
granted, status = service.grant_welcome_credits_if_eligible(
|
||||
"new@example.com",
|
||||
precomputed_eval={
|
||||
"credit_eval_decision": "grant",
|
||||
"credit_eval_reasoning": "Pre-computed: clean user",
|
||||
},
|
||||
)
|
||||
# AI evaluation should NOT have been called
|
||||
mock_eval.return_value.evaluate.assert_not_called()
|
||||
|
||||
assert granted is True
|
||||
assert status == "granted"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_skips_if_flag_already_set(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible returns False if welcome_credits_granted flag is True."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User has the flag set (even if transactions were trimmed)
|
||||
user = User(
|
||||
email="existing@example.com",
|
||||
credits=2,
|
||||
welcome_credits_granted=True,
|
||||
)
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
|
||||
|
||||
assert granted is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_skips_if_transaction_exists(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible returns False if welcome_credit txn exists (secondary check)."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User has transaction but flag not set (legacy user)
|
||||
user = User(
|
||||
email="existing@example.com",
|
||||
credits=2,
|
||||
welcome_credits_granted=False,
|
||||
credit_transactions=[
|
||||
CreditTransaction(
|
||||
id=str(uuid.uuid4()),
|
||||
amount=2,
|
||||
reason="welcome_credit",
|
||||
)
|
||||
],
|
||||
)
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
|
||||
|
||||
assert granted is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_returns_false_for_nonexistent_user(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible returns False for unknown user."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
granted, status = service.grant_welcome_credits_if_eligible("ghost@example.com")
|
||||
|
||||
assert granted is False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Phase 2: Per-IP Signup Rate Limiting
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestIPRateLimiting:
|
||||
"""Test IP-based signup rate limiting."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_count_recent_signups_from_ip(self, mock_fs, mock_settings):
|
||||
"""count_recent_signups_from_ip counts matching users."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# Simulate 2 matching users
|
||||
mock_docs = [MagicMock(), MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
count = service.count_recent_signups_from_ip("1.2.3.4")
|
||||
|
||||
assert count == 2
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_is_signup_rate_limited_by_ip(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited returns True when IP count >= 2."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# 2 signups = rate limited
|
||||
mock_docs = [MagicMock(), MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
assert service.is_signup_rate_limited(ip_address="1.2.3.4") is True
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_not_rate_limited_with_one_signup(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited returns False when IP count < 2."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_docs = [MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
assert service.is_signup_rate_limited(ip_address="1.2.3.4") is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_no_ip_not_rate_limited(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited returns False when no IP provided."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
assert service.is_signup_rate_limited(ip_address=None) is False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Phase 3: Device Fingerprint Rate Limiting
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestFingerprintRateLimiting:
|
||||
"""Test fingerprint-based signup rate limiting."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_count_recent_signups_from_fingerprint(self, mock_fs, mock_settings):
|
||||
"""count_recent_signups_from_fingerprint counts matching users."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_docs = [MagicMock(), MagicMock(), MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
count = service.count_recent_signups_from_fingerprint("fp123")
|
||||
|
||||
assert count == 3
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_is_signup_rate_limited_by_fingerprint(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited returns True when fingerprint count >= 2."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# IP returns 0, fingerprint returns 2
|
||||
def side_effect_stream():
|
||||
return iter([MagicMock(), MagicMock()])
|
||||
|
||||
# We need separate mock chains for IP and fingerprint queries
|
||||
# Since both use the same mock chain, we'll set up the calls differently
|
||||
call_count = [0]
|
||||
def stream_side_effect():
|
||||
call_count[0] += 1
|
||||
if call_count[0] == 1:
|
||||
return iter([]) # IP query: 0 results
|
||||
return iter([MagicMock(), MagicMock()]) # Fingerprint query: 2 results
|
||||
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream = stream_side_effect
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.is_signup_rate_limited(
|
||||
ip_address="1.2.3.4", device_fingerprint="fp123"
|
||||
)
|
||||
|
||||
assert result is True
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_no_fingerprint_not_rate_limited(self, mock_fs, mock_settings):
|
||||
"""is_signup_rate_limited doesn't check fingerprint when None."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# IP query returns 0
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.is_signup_rate_limited(
|
||||
ip_address="1.2.3.4", device_fingerprint=None
|
||||
)
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Integration: Magic Link Endpoint Rate Limiting
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_validation_svc():
|
||||
"""Create a mock EmailValidationService."""
|
||||
svc = MagicMock()
|
||||
svc.is_disposable_domain.return_value = False
|
||||
svc.is_email_blocked.return_value = False
|
||||
svc.is_ip_blocked.return_value = False
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_svc():
|
||||
"""Create a mock UserService."""
|
||||
svc = MagicMock()
|
||||
svc.get_user.return_value = None # New user by default
|
||||
svc.is_signup_rate_limited.return_value = False
|
||||
svc.create_magic_link.return_value = MagicLinkToken(
|
||||
token="test-token",
|
||||
email="test@example.com",
|
||||
expires_at=datetime.utcnow() + timedelta(minutes=15),
|
||||
)
|
||||
svc.NEW_USER_FREE_CREDITS = 1
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_email_svc():
|
||||
"""Create a mock EmailService."""
|
||||
svc = MagicMock()
|
||||
svc.is_configured.return_value = True
|
||||
svc.send_magic_link.return_value = True
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_validation_svc, mock_user_svc, mock_email_svc):
|
||||
"""Create TestClient with mocked services via FastAPI dependency overrides."""
|
||||
from backend.main import app
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_user_svc
|
||||
app.dependency_overrides[get_email_service] = lambda: mock_email_svc
|
||||
|
||||
with patch(
|
||||
"backend.api.routes.users.get_email_validation_service",
|
||||
return_value=mock_validation_svc,
|
||||
):
|
||||
yield TestClient(app)
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestMagicLinkRateLimiting:
|
||||
"""Integration tests for rate limiting in the magic link endpoint."""
|
||||
|
||||
def test_new_signup_allowed_when_not_rate_limited(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""New signup succeeds when not rate limited."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = False
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "new@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_user_svc.create_magic_link.assert_called_once()
|
||||
|
||||
def test_new_signup_blocked_when_rate_limited(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""New signup is silently rejected when rate limited."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "abuser@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
# Magic link should NOT have been created
|
||||
mock_user_svc.create_magic_link.assert_not_called()
|
||||
|
||||
def test_existing_user_not_rate_limited(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""Returning user bypasses rate limiting."""
|
||||
mock_user_svc.get_user.return_value = User(
|
||||
email="existing@example.com", credits=5
|
||||
)
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "existing@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Rate limit check should not be called for existing users
|
||||
mock_user_svc.is_signup_rate_limited.assert_not_called()
|
||||
mock_user_svc.create_magic_link.assert_called_once()
|
||||
|
||||
def test_fingerprint_passed_to_create_magic_link(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""Device fingerprint from request body is passed to create_magic_link."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = False
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "new@example.com", "device_fingerprint": "fp-abc123"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
create_call = mock_user_svc.create_magic_link.call_args
|
||||
assert create_call.kwargs.get('device_fingerprint') == "fp-abc123"
|
||||
|
||||
def test_fingerprint_passed_to_rate_limiter(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""Device fingerprint is included in rate limit check."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = False
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "new@example.com", "device_fingerprint": "fp-abc123"},
|
||||
)
|
||||
|
||||
rate_limit_call = mock_user_svc.is_signup_rate_limited.call_args
|
||||
assert rate_limit_call.kwargs.get('device_fingerprint') == "fp-abc123"
|
||||
|
||||
def test_missing_fingerprint_gracefully_handled(
|
||||
self, client, mock_user_svc
|
||||
):
|
||||
"""Missing fingerprint doesn't break the flow."""
|
||||
mock_user_svc.get_user.return_value = None
|
||||
mock_user_svc.is_signup_rate_limited.return_value = False
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "new@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
rate_limit_call = mock_user_svc.is_signup_rate_limited.call_args
|
||||
assert rate_limit_call.kwargs.get('device_fingerprint') is None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Integration: Verify Endpoint Grants Credits
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestVerifyGrantsCredits:
|
||||
"""Test that the verify endpoint grants welcome credits."""
|
||||
|
||||
def _make_verify_client(self, mock_user_svc, user, credits_eligible):
|
||||
"""Helper to create a TestClient for verify endpoint tests."""
|
||||
from backend.main import app
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
mock_user_svc.verify_magic_link.return_value = (True, user, "Success")
|
||||
mock_user_svc.grant_welcome_credits_if_eligible.return_value = (credits_eligible, "granted" if credits_eligible else "already_granted")
|
||||
mock_user_svc.get_user.return_value = user
|
||||
mock_user_svc.create_session.return_value = MagicMock(token="session-token")
|
||||
mock_user_svc.NEW_USER_FREE_CREDITS = 1
|
||||
|
||||
# Mock magic link doc for first-login check
|
||||
mock_ml_doc = MagicMock()
|
||||
mock_ml_doc.exists = True
|
||||
mock_ml_doc.to_dict.return_value = {
|
||||
'email': user.email,
|
||||
'tenant_id': None,
|
||||
}
|
||||
mock_user_svc.db.collection.return_value.document.return_value.get.return_value = mock_ml_doc
|
||||
|
||||
mock_email_svc = MagicMock()
|
||||
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_user_svc
|
||||
app.dependency_overrides[get_email_service] = lambda: mock_email_svc
|
||||
|
||||
client = TestClient(app)
|
||||
return client
|
||||
|
||||
def test_verify_returns_credits_granted(self, mock_user_svc):
|
||||
"""Verify endpoint returns credits_granted in response."""
|
||||
user = User(email="new@example.com", credits=2, email_verified=True)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
|
||||
|
||||
try:
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["credits_granted"] == 1
|
||||
mock_user_svc.grant_welcome_credits_if_eligible.assert_called_once()
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_passes_precomputed_eval(self, mock_user_svc):
|
||||
"""Verify endpoint passes pre-computed eval from magic link doc."""
|
||||
user = User(email="new@example.com", credits=2, email_verified=True)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
|
||||
|
||||
# Add pre-computed eval to the magic link doc
|
||||
mock_ml_doc = mock_user_svc.db.collection.return_value.document.return_value.get.return_value
|
||||
mock_ml_doc.to_dict.return_value = {
|
||||
'email': user.email,
|
||||
'tenant_id': None,
|
||||
'credit_eval_decision': 'grant',
|
||||
'credit_eval_reasoning': 'Clean user',
|
||||
}
|
||||
|
||||
try:
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
|
||||
assert response.status_code == 200
|
||||
# Verify precomputed_eval was passed through
|
||||
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
|
||||
assert call_kwargs[1]['precomputed_eval'] == {
|
||||
'credit_eval_decision': 'grant',
|
||||
'credit_eval_reasoning': 'Clean user',
|
||||
}
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_falls_back_without_precomputed_eval(self, mock_user_svc):
|
||||
"""Verify endpoint passes None when no pre-computed eval exists."""
|
||||
user = User(email="new@example.com", credits=2, email_verified=True)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
|
||||
|
||||
try:
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
|
||||
assert response.status_code == 200
|
||||
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
|
||||
assert call_kwargs[1]['precomputed_eval'] is None
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_returns_zero_credits_for_returning_user(self, mock_user_svc):
|
||||
"""Returning user gets credits_granted=0."""
|
||||
user = User(
|
||||
email="existing@example.com",
|
||||
credits=5,
|
||||
email_verified=True,
|
||||
last_login_at=datetime.utcnow(),
|
||||
)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=False)
|
||||
|
||||
try:
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["credits_granted"] == 0
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Model Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestModelFields:
|
||||
"""Test that new fields exist on models."""
|
||||
|
||||
def test_user_has_signup_ip(self):
|
||||
"""User model has signup_ip field."""
|
||||
user = User(email="test@example.com", signup_ip="1.2.3.4")
|
||||
assert user.signup_ip == "1.2.3.4"
|
||||
|
||||
def test_user_has_device_fingerprint(self):
|
||||
"""User model has device_fingerprint field."""
|
||||
user = User(email="test@example.com", device_fingerprint="fp123")
|
||||
assert user.device_fingerprint == "fp123"
|
||||
|
||||
def test_user_defaults_none(self):
|
||||
"""New fields default to None."""
|
||||
user = User(email="test@example.com")
|
||||
assert user.signup_ip is None
|
||||
assert user.device_fingerprint is None
|
||||
|
||||
def test_magic_link_has_device_fingerprint(self):
|
||||
"""MagicLinkToken model has device_fingerprint field."""
|
||||
ml = MagicLinkToken(
|
||||
token="tok",
|
||||
email="test@example.com",
|
||||
expires_at=datetime.utcnow(),
|
||||
device_fingerprint="fp123",
|
||||
)
|
||||
assert ml.device_fingerprint == "fp123"
|
||||
|
||||
def test_send_magic_link_request_has_fingerprint(self):
|
||||
"""SendMagicLinkRequest accepts device_fingerprint."""
|
||||
req = SendMagicLinkRequest(
|
||||
email="test@example.com",
|
||||
device_fingerprint="fp123",
|
||||
)
|
||||
assert req.device_fingerprint == "fp123"
|
||||
|
||||
def test_send_magic_link_request_fingerprint_optional(self):
|
||||
"""SendMagicLinkRequest works without device_fingerprint."""
|
||||
req = SendMagicLinkRequest(email="test@example.com")
|
||||
assert req.device_fingerprint is None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Error Path Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestErrorPaths:
|
||||
"""Test graceful degradation on errors."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_grant_credits_handles_exception(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible returns False on exception."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User lookup raises exception
|
||||
mock_db.collection.return_value.document.return_value.get.side_effect = Exception("Firestore down")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
granted, status = service.grant_welcome_credits_if_eligible("test@example.com")
|
||||
assert granted is False
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_count_signups_from_ip_handles_exception(self, mock_fs, mock_settings):
|
||||
"""count_recent_signups_from_ip returns 0 on Firestore error (fail-open)."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_db.collection.return_value.where.return_value.where.side_effect = Exception("Query error")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
count = service.count_recent_signups_from_ip("1.2.3.4")
|
||||
assert count == 0 # Fail-open: don't block on error
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_count_signups_from_fingerprint_handles_exception(self, mock_fs, mock_settings):
|
||||
"""count_recent_signups_from_fingerprint returns 0 on error (fail-open)."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_db.collection.return_value.where.return_value.where.side_effect = Exception("Query error")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
count = service.count_recent_signups_from_fingerprint("fp123")
|
||||
assert count == 0
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Caller-Callee Contract Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCallerCalleeContracts:
|
||||
"""Verify that callers pass the right data to callees."""
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_create_magic_link_passes_fingerprint_to_get_or_create(self, mock_fs, mock_settings):
|
||||
"""create_magic_link passes device_fingerprint through to get_or_create_user."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# User already exists (to avoid save path)
|
||||
user = User(email="test@example.com", credits=0)
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
|
||||
with patch.object(service, 'get_or_create_user', wraps=service.get_or_create_user) as spy:
|
||||
service.create_magic_link(
|
||||
"test@example.com",
|
||||
ip_address="1.2.3.4",
|
||||
device_fingerprint="fp-xyz",
|
||||
)
|
||||
spy.assert_called_once_with(
|
||||
"test@example.com",
|
||||
tenant_id=None,
|
||||
signup_ip="1.2.3.4",
|
||||
device_fingerprint="fp-xyz",
|
||||
)
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_create_magic_link_stores_fingerprint_on_token(self, mock_fs, mock_settings):
|
||||
"""create_magic_link includes device_fingerprint in the MagicLinkToken."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="test@example.com", credits=0)
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
|
||||
ml = service.create_magic_link(
|
||||
"test@example.com",
|
||||
ip_address="1.2.3.4",
|
||||
device_fingerprint="fp-xyz",
|
||||
)
|
||||
|
||||
assert ml.device_fingerprint == "fp-xyz"
|
||||
|
||||
# Also verify the data written to Firestore includes the fingerprint
|
||||
set_call = mock_db.collection.return_value.document.return_value.set
|
||||
set_call.assert_called()
|
||||
saved_data = set_call.call_args[0][0]
|
||||
assert saved_data["device_fingerprint"] == "fp-xyz"
|
||||
@@ -0,0 +1,480 @@
|
||||
"""
|
||||
Tests for anti-abuse investigation features: admin endpoints, session/job
|
||||
fingerprint tracking, and user lookup methods.
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import MagicMock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
from backend.models.user import User, Session, MagicLinkToken
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Model Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestSessionFingerprint:
|
||||
"""Session model stores device_fingerprint."""
|
||||
|
||||
def test_session_has_device_fingerprint(self):
|
||||
session = Session(
|
||||
token="tok",
|
||||
user_email="test@example.com",
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
device_fingerprint="fp-abc",
|
||||
)
|
||||
assert session.device_fingerprint == "fp-abc"
|
||||
|
||||
def test_session_fingerprint_defaults_none(self):
|
||||
session = Session(
|
||||
token="tok",
|
||||
user_email="test@example.com",
|
||||
expires_at=datetime.utcnow() + timedelta(days=30),
|
||||
)
|
||||
assert session.device_fingerprint is None
|
||||
|
||||
|
||||
class TestJobCreationIp:
|
||||
"""Job model stores creation_ip."""
|
||||
|
||||
def test_job_has_creation_ip(self):
|
||||
from backend.models.job import Job, JobStatus
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
creation_ip="1.2.3.4",
|
||||
)
|
||||
assert job.creation_ip == "1.2.3.4"
|
||||
|
||||
def test_job_creation_ip_defaults_none(self):
|
||||
from backend.models.job import Job, JobStatus
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
assert job.creation_ip is None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Internal/Test Email Filtering
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestInternalOrTestEmail:
|
||||
"""Tests for is_internal_or_test_email utility."""
|
||||
|
||||
def test_nomadkaraoke_is_internal(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("admin@nomadkaraoke.com") is True
|
||||
|
||||
def test_beveridge_is_internal(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("vocalstar@beveridge.uk") is True
|
||||
|
||||
def test_testmail_is_test(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("test123@inbox.testmail.app") is True
|
||||
|
||||
def test_regular_email_is_not_internal(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("user@gmail.com") is False
|
||||
|
||||
def test_empty_email(self):
|
||||
from backend.utils.test_data import is_internal_or_test_email
|
||||
assert is_internal_or_test_email("") is False
|
||||
|
||||
def test_is_internal_email_only(self):
|
||||
from backend.utils.test_data import is_internal_email
|
||||
assert is_internal_email("andrew@beveridge.uk") is True
|
||||
assert is_internal_email("user@gmail.com") is False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# UserService Investigation Methods
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestFindUsersBySignupIp:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_finds_matching_users(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user1 = User(email="a@test.com", signup_ip="1.2.3.4").model_dump(mode='json')
|
||||
user2 = User(email="b@test.com", signup_ip="1.2.3.4").model_dump(mode='json')
|
||||
mock_doc1 = MagicMock()
|
||||
mock_doc1.to_dict.return_value = user1
|
||||
mock_doc2 = MagicMock()
|
||||
mock_doc2.to_dict.return_value = user2
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [mock_doc1, mock_doc2]
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
results = service.find_users_by_signup_ip("1.2.3.4")
|
||||
|
||||
assert len(results) == 2
|
||||
assert results[0].email == "a@test.com"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_returns_empty_on_error(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
mock_db.collection.return_value.where.side_effect = Exception("Firestore down")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
results = service.find_users_by_signup_ip("1.2.3.4")
|
||||
assert results == []
|
||||
|
||||
|
||||
class TestFindUsersByFingerprint:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_finds_matching_users(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user1 = User(email="a@test.com", device_fingerprint="fp123").model_dump(mode='json')
|
||||
mock_doc1 = MagicMock()
|
||||
mock_doc1.to_dict.return_value = user1
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [mock_doc1]
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
results = service.find_users_by_fingerprint("fp123")
|
||||
|
||||
assert len(results) == 1
|
||||
|
||||
|
||||
class TestFindSuspiciousAccounts:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_finds_free_high_usage_accounts(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
free_abuser = User(email="free@test.com", total_jobs_created=5, total_spent=0).model_dump(mode='json')
|
||||
paying_user = User(email="paid@test.com", total_jobs_created=10, total_spent=500).model_dump(mode='json')
|
||||
mock_doc1 = MagicMock()
|
||||
mock_doc1.to_dict.return_value = free_abuser
|
||||
mock_doc2 = MagicMock()
|
||||
mock_doc2.to_dict.return_value = paying_user
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [mock_doc1, mock_doc2]
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
results = service.find_suspicious_accounts(min_jobs=2, max_spend=0)
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0].email == "free@test.com"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_excludes_internal_and_test_accounts(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
real_user = User(email="abuser@gmail.com", total_jobs_created=5, total_spent=0).model_dump(mode='json')
|
||||
internal_user = User(email="admin@nomadkaraoke.com", total_jobs_created=10, total_spent=0).model_dump(mode='json')
|
||||
test_user = User(email="e2e@inbox.testmail.app", total_jobs_created=8, total_spent=0).model_dump(mode='json')
|
||||
personal_user = User(email="vocalstar@beveridge.uk", total_jobs_created=3, total_spent=0).model_dump(mode='json')
|
||||
|
||||
docs = []
|
||||
for data in [real_user, internal_user, test_user, personal_user]:
|
||||
doc = MagicMock()
|
||||
doc.to_dict.return_value = data
|
||||
docs.append(doc)
|
||||
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
results = service.find_suspicious_accounts(min_jobs=2, max_spend=0)
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0].email == "abuser@gmail.com"
|
||||
|
||||
|
||||
class TestFindRelatedAccounts:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_finds_related_by_ip_and_fingerprint(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
target = User(email="target@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
|
||||
with patch.object(service, 'get_user', return_value=target), \
|
||||
patch.object(service, 'find_users_by_signup_ip', return_value=[
|
||||
target,
|
||||
User(email="related@test.com", signup_ip="1.2.3.4"),
|
||||
]), \
|
||||
patch.object(service, 'find_users_by_fingerprint', return_value=[
|
||||
target,
|
||||
User(email="device-buddy@test.com", device_fingerprint="fp123"),
|
||||
]):
|
||||
result = service.find_related_accounts("target@test.com")
|
||||
|
||||
assert result["user"].email == "target@test.com"
|
||||
# Should exclude the target user from related lists
|
||||
assert len(result["by_ip"]) == 1
|
||||
assert result["by_ip"][0].email == "related@test.com"
|
||||
assert len(result["by_fingerprint"]) == 1
|
||||
assert result["by_fingerprint"][0].email == "device-buddy@test.com"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_returns_empty_for_unknown_user(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.find_related_accounts("ghost@test.com")
|
||||
|
||||
assert result["user"] is None
|
||||
assert result["by_ip"] == []
|
||||
assert result["by_fingerprint"] == []
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Endpoint Integration Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_svc():
|
||||
svc = MagicMock()
|
||||
svc.NEW_USER_FREE_CREDITS = 1
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_client(mock_user_svc):
|
||||
from backend.main import app
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.api.dependencies import require_admin
|
||||
|
||||
mock_auth = MagicMock()
|
||||
mock_auth.is_admin = True
|
||||
mock_auth.user_email = "admin@nomadkaraoke.com"
|
||||
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_user_svc
|
||||
app.dependency_overrides[require_admin] = lambda: mock_auth
|
||||
|
||||
yield TestClient(app)
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestAdminAbuseEndpoints:
|
||||
|
||||
def test_suspicious_accounts_endpoint(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_suspicious_accounts.return_value = [
|
||||
User(email="free@test.com", total_jobs_created=5, total_spent=0),
|
||||
]
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/suspicious?min_jobs=2&max_spend=0")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["count"] == 1
|
||||
assert data["users"][0]["email"] == "free@test.com"
|
||||
|
||||
def test_by_ip_endpoint(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_users_by_signup_ip.return_value = [
|
||||
User(email="a@test.com", signup_ip="1.2.3.4"),
|
||||
User(email="b@test.com", signup_ip="1.2.3.4"),
|
||||
]
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/by-ip/1.2.3.4")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["count"] == 2
|
||||
|
||||
def test_by_fingerprint_endpoint(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_users_by_fingerprint.return_value = [
|
||||
User(email="a@test.com", device_fingerprint="fp123"),
|
||||
]
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/by-fingerprint/fp123")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["count"] == 1
|
||||
|
||||
def test_related_endpoint(self, admin_client, mock_user_svc):
|
||||
target = User(email="target@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3)
|
||||
mock_user_svc.find_related_accounts.return_value = {
|
||||
"user": target,
|
||||
"by_ip": [User(email="buddy@test.com", signup_ip="1.2.3.4")],
|
||||
"by_fingerprint": [],
|
||||
}
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/related/target@test.com")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["user"]["email"] == "target@test.com"
|
||||
assert len(data["related_by_ip"]) == 1
|
||||
assert len(data["related_by_fingerprint"]) == 0
|
||||
|
||||
def test_related_endpoint_user_not_found(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_related_accounts.return_value = {
|
||||
"user": None, "by_ip": [], "by_fingerprint": [],
|
||||
}
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/related/ghost@test.com")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_correlations_endpoint(self, admin_client, mock_user_svc):
|
||||
user_a = User(email="a@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=2)
|
||||
user_b = User(email="b@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3)
|
||||
|
||||
mock_user_svc.find_account_correlations.return_value = {
|
||||
"fingerprint_clusters": [
|
||||
{"fingerprint": "fp123", "users": [user_a, user_b]},
|
||||
],
|
||||
"ip_clusters": [
|
||||
{"ip": "1.2.3.4", "users": [user_a, user_b]},
|
||||
],
|
||||
"user_agents": {"a@test.com": "Mozilla/5.0", "b@test.com": "Mozilla/5.0"},
|
||||
}
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/correlations")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["fingerprint_clusters"]) == 1
|
||||
assert data["fingerprint_clusters"][0]["fingerprint"] == "fp123"
|
||||
assert data["fingerprint_clusters"][0]["count"] == 2
|
||||
assert data["fingerprint_clusters"][0]["users"][0]["user_agent"] == "Mozilla/5.0"
|
||||
assert len(data["ip_clusters"]) == 1
|
||||
assert data["ip_clusters"][0]["ip"] == "1.2.3.4"
|
||||
assert data["ip_clusters"][0]["count"] == 2
|
||||
|
||||
def test_correlations_endpoint_empty(self, admin_client, mock_user_svc):
|
||||
mock_user_svc.find_account_correlations.return_value = {
|
||||
"fingerprint_clusters": [],
|
||||
"ip_clusters": [],
|
||||
"user_agents": {},
|
||||
}
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/correlations")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["fingerprint_clusters"] == []
|
||||
assert data["ip_clusters"] == []
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Correlations Service Method Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestFindAccountCorrelations:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_groups_by_fingerprint_and_ip(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user_a = User(email="a@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=2).model_dump(mode='json')
|
||||
user_b = User(email="b@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3).model_dump(mode='json')
|
||||
user_c = User(email="c@gmail.com", signup_ip="5.6.7.8", device_fingerprint="fp999", total_jobs_created=1).model_dump(mode='json')
|
||||
|
||||
docs = []
|
||||
for data in [user_a, user_b, user_c]:
|
||||
doc = MagicMock()
|
||||
doc.to_dict.return_value = data
|
||||
docs.append(doc)
|
||||
|
||||
# Mock the users collection stream
|
||||
mock_db.collection.return_value.stream.return_value = docs
|
||||
|
||||
# Mock session lookups (return empty for simplicity)
|
||||
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.find_account_correlations()
|
||||
|
||||
# a and b share fp123 → 1 fingerprint cluster
|
||||
assert len(result["fingerprint_clusters"]) == 1
|
||||
assert result["fingerprint_clusters"][0]["fingerprint"] == "fp123"
|
||||
assert len(result["fingerprint_clusters"][0]["users"]) == 2
|
||||
|
||||
# a and b share IP 1.2.3.4 → 1 IP cluster
|
||||
assert len(result["ip_clusters"]) == 1
|
||||
assert result["ip_clusters"][0]["ip"] == "1.2.3.4"
|
||||
assert len(result["ip_clusters"][0]["users"]) == 2
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_excludes_internal_accounts(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
real_user = User(email="user@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123").model_dump(mode='json')
|
||||
internal_user = User(email="admin@nomadkaraoke.com", signup_ip="1.2.3.4", device_fingerprint="fp123").model_dump(mode='json')
|
||||
|
||||
docs = []
|
||||
for data in [real_user, internal_user]:
|
||||
doc = MagicMock()
|
||||
doc.to_dict.return_value = data
|
||||
docs.append(doc)
|
||||
|
||||
mock_db.collection.return_value.stream.return_value = docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.find_account_correlations()
|
||||
|
||||
# Only 1 non-internal user with fp123, so no cluster (need 2+)
|
||||
assert len(result["fingerprint_clusters"]) == 0
|
||||
assert len(result["ip_clusters"]) == 0
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_returns_empty_on_error(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
mock_db.collection.return_value.stream.side_effect = Exception("Firestore down")
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
result = service.find_account_correlations()
|
||||
|
||||
assert result["fingerprint_clusters"] == []
|
||||
assert result["ip_clusters"] == []
|
||||
@@ -5,7 +5,9 @@ These tests mock the storage service and shared karaoke_gen modules to verify:
|
||||
- GCS file download/upload operations
|
||||
- Audio analysis delegation to shared AudioAnalyzer
|
||||
- Waveform generation delegation to shared WaveformGenerator
|
||||
- Waveform data caching (cache_waveform_data / load_cached_waveform)
|
||||
"""
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch, ANY
|
||||
import tempfile
|
||||
@@ -292,3 +294,119 @@ class TestGenerateWaveformWithMutes:
|
||||
# Verify return
|
||||
assert result_path == "uploads/job123/waveform_muted.png"
|
||||
|
||||
|
||||
class TestCacheWaveformData:
|
||||
"""Test cache_waveform_data method."""
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_caches_waveform_to_gcs(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""cache_waveform_data should generate waveform and upload JSON to GCS."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
mock_waveform = Mock()
|
||||
mock_waveform.generate_data_only.return_value = ([0.1, 0.5, 0.3], 200.0)
|
||||
mock_waveform_class.return_value = mock_waveform
|
||||
|
||||
service = AudioAnalysisService()
|
||||
|
||||
amplitudes, duration = service.cache_waveform_data(
|
||||
gcs_audio_path="jobs/j1/input/song.flac",
|
||||
job_id="j1",
|
||||
cache_gcs_path="jobs/j1/audio_edit/waveform_original.json",
|
||||
num_points=1000,
|
||||
)
|
||||
|
||||
assert amplitudes == [0.1, 0.5, 0.3]
|
||||
assert duration == 200.0
|
||||
|
||||
# Verify JSON was uploaded with correct structure
|
||||
mock_storage.upload_json.assert_called_once()
|
||||
call_args = mock_storage.upload_json.call_args
|
||||
assert call_args[0][0] == "jobs/j1/audio_edit/waveform_original.json"
|
||||
uploaded_data = call_args[0][1]
|
||||
assert uploaded_data["amplitudes"] == [0.1, 0.5, 0.3]
|
||||
assert uploaded_data["duration_seconds"] == 200.0
|
||||
assert uploaded_data["num_points"] == 1000
|
||||
assert uploaded_data["source_gcs_path"] == "jobs/j1/input/song.flac"
|
||||
|
||||
|
||||
class TestLoadCachedWaveform:
|
||||
"""Test load_cached_waveform method."""
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_returns_none_when_cache_missing(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""Should return None when cache file doesn't exist."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
service = AudioAnalysisService()
|
||||
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
|
||||
|
||||
assert result is None
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_loads_cached_waveform(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""Should load and parse cached waveform JSON from GCS."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
cache_data = {
|
||||
"amplitudes": [0.2, 0.6, 0.4],
|
||||
"duration_seconds": 180.0,
|
||||
"num_points": 1000,
|
||||
"source_gcs_path": "jobs/j1/input/song.flac",
|
||||
}
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
# Simulate download_file writing JSON to the local path
|
||||
def write_json(gcs_path, local_path):
|
||||
with open(local_path, 'w') as f:
|
||||
json.dump(cache_data, f)
|
||||
mock_storage.download_file.side_effect = write_json
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
service = AudioAnalysisService()
|
||||
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
|
||||
|
||||
assert result is not None
|
||||
amplitudes, duration = result
|
||||
assert amplitudes == [0.2, 0.6, 0.4]
|
||||
assert duration == 180.0
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_returns_none_on_error(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""Should return None gracefully on any error."""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.download_file.side_effect = Exception("GCS timeout")
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
service = AudioAnalysisService()
|
||||
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
|
||||
|
||||
assert result is None
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
"""
|
||||
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 TestAudioEditPreGeneration:
|
||||
"""Tests for pre-generation of editor assets when requires_audio_edit is set."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pregenerates_assets_when_audio_edit_requested(self):
|
||||
"""Should transcode OGG + cache waveform before transitioning to awaiting_audio_edit."""
|
||||
job = _make_job(state_data={'requires_audio_edit': True})
|
||||
|
||||
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.services.audio_transcoding_service.AudioTranscodingService") as MockTS, \
|
||||
patch("backend.services.audio_analysis_service.AudioAnalysisService") as MockAS:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
# First get_job returns the initial job, second returns the one with requires_audio_edit
|
||||
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_ts = MagicMock()
|
||||
MockTS.return_value = mock_ts
|
||||
|
||||
mock_as = MagicMock()
|
||||
mock_as.cache_waveform_data.return_value = ([0.1, 0.5], 200.0)
|
||||
MockAS.return_value = mock_as
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is True
|
||||
# Should have transcoded OGG
|
||||
mock_ts.transcode_if_needed.assert_called_once_with("uploads/test-job-123/audio/song.flac")
|
||||
# Should have cached waveform
|
||||
mock_as.cache_waveform_data.assert_called_once_with(
|
||||
"uploads/test-job-123/audio/song.flac",
|
||||
"test-job-123",
|
||||
"jobs/test-job-123/audio_edit/waveform_original.json",
|
||||
)
|
||||
# Should have stored cache path in state_data
|
||||
mock_jm.update_state_data.assert_any_call(
|
||||
"test-job-123", "audio_edit_waveform_cache_path",
|
||||
"jobs/test-job-123/audio_edit/waveform_original.json",
|
||||
)
|
||||
# Should have transitioned to awaiting_audio_edit
|
||||
calls = mock_jm.transition_to_state.call_args_list
|
||||
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pregeneration_failure_is_nonfatal(self):
|
||||
"""Pre-generation failure should not prevent the job from reaching awaiting_audio_edit."""
|
||||
job = _make_job(state_data={'requires_audio_edit': True})
|
||||
|
||||
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.services.audio_transcoding_service.AudioTranscodingService") as MockTS:
|
||||
|
||||
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")
|
||||
|
||||
# Transcoding fails
|
||||
mock_ts = MagicMock()
|
||||
mock_ts.transcode_if_needed.side_effect = RuntimeError("ffmpeg not found")
|
||||
MockTS.return_value = mock_ts
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
# Should still succeed and transition to awaiting_audio_edit
|
||||
assert result is True
|
||||
calls = mock_jm.transition_to_state.call_args_list
|
||||
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
|
||||
|
||||
|
||||
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,549 @@
|
||||
"""
|
||||
Tests for audio edit API endpoints in backend/api/routes/review.py.
|
||||
|
||||
Tests the 6 new endpoints: input-audio-info, apply, undo, redo, upload, submit.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import Mock, patch, MagicMock, AsyncMock
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.audio_edit_service import AudioMetadata
|
||||
|
||||
NOW = datetime.now(UTC)
|
||||
|
||||
# Patch paths - these are imported inside endpoint functions
|
||||
PATCH_JM = "backend.api.routes.review.JobManager"
|
||||
PATCH_EDIT_SVC = "backend.services.audio_edit_service.AudioEditService"
|
||||
PATCH_ANALYSIS_SVC = "backend.services.audio_analysis_service.AudioAnalysisService"
|
||||
PATCH_TRANSCODE_SVC = "backend.services.audio_transcoding_service.AudioTranscodingService"
|
||||
PATCH_STORAGE_SVC = "backend.api.routes.review.StorageService"
|
||||
PATCH_WORKER_SVC = "backend.services.worker_service.get_worker_service"
|
||||
|
||||
|
||||
def _job(**kwargs):
|
||||
"""Create a Job with required fields filled in."""
|
||||
defaults = dict(created_at=NOW, updated_at=NOW)
|
||||
defaults.update(kwargs)
|
||||
return Job(**defaults)
|
||||
|
||||
|
||||
# --- Fixtures ---
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _ensure_auth_overrides():
|
||||
"""Ensure auth overrides are set for every test, even when conftest autouse is fragile."""
|
||||
from backend.api.dependencies import require_auth, require_admin, require_review_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.main import app
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
return (job_id, "full")
|
||||
|
||||
async def mock_require_auth():
|
||||
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
|
||||
message="Test", is_admin=True, user_email="test@example.com")
|
||||
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
app.dependency_overrides[require_auth] = mock_require_auth
|
||||
app.dependency_overrides[require_admin] = mock_require_auth
|
||||
yield
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(require_admin, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager():
|
||||
with patch(PATCH_JM) as MockJM:
|
||||
jm = Mock()
|
||||
MockJM.return_value = jm
|
||||
yield jm
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_services():
|
||||
"""Mock all service dependencies used by audio edit endpoints."""
|
||||
with patch(PATCH_EDIT_SVC) as MockES, \
|
||||
patch(PATCH_ANALYSIS_SVC) as MockAS, \
|
||||
patch(PATCH_TRANSCODE_SVC) as MockTS:
|
||||
es = Mock()
|
||||
MockES.return_value = es
|
||||
# Default metadata for duration_before lookups
|
||||
es.get_metadata_from_gcs.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
as_inst = Mock()
|
||||
MockAS.return_value = as_inst
|
||||
as_inst.get_waveform_data.return_value = ([0.1, 0.5, 0.3], 200.0)
|
||||
ts = Mock()
|
||||
MockTS.return_value = ts
|
||||
ts.get_review_audio_url.return_value = "https://example.com/audio.ogg"
|
||||
yield {"edit": es, "analysis": as_inst, "transcode": ts}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def audio_edit_job():
|
||||
"""Job in awaiting_audio_edit state with input media."""
|
||||
return _job(
|
||||
job_id="edit-job-1",
|
||||
status=JobStatus.AWAITING_AUDIO_EDIT,
|
||||
progress=15,
|
||||
input_media_gcs_path="jobs/edit-job-1/input/song.flac",
|
||||
state_data={},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def audio_edit_job_with_edits():
|
||||
"""Job in in_audio_edit state with existing edit stack."""
|
||||
return _job(
|
||||
job_id="edit-job-2",
|
||||
status=JobStatus.IN_AUDIO_EDIT,
|
||||
progress=15,
|
||||
input_media_gcs_path="jobs/edit-job-2/input/song.flac",
|
||||
state_data={
|
||||
"audio_edit_stack": [
|
||||
{
|
||||
"edit_id": "aaa",
|
||||
"operation": "trim_start",
|
||||
"params": {"end_seconds": 10.0},
|
||||
"gcs_path": "jobs/edit-job-2/audio_edit/edit_aaa.flac",
|
||||
"duration_seconds": 190.0,
|
||||
"timestamp": "2026-03-08T12:00:00",
|
||||
}
|
||||
],
|
||||
"audio_edit_redo_stack": [],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# --- GET /input-audio-info ---
|
||||
|
||||
class TestGetInputAudioInfo:
|
||||
|
||||
def test_returns_audio_info(self, test_client, mock_job_manager, mock_services, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
resp = test_client.get("/api/review/edit-job-1/input-audio-info")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["job_id"] == "edit-job-1"
|
||||
assert data["original_duration_seconds"] > 0
|
||||
assert data["current_duration_seconds"] > 0
|
||||
assert data["original_audio_url"] == "https://example.com/audio.ogg"
|
||||
assert data["current_audio_url"] == "https://example.com/audio.ogg"
|
||||
assert data["edit_stack"] == []
|
||||
assert data["can_undo"] is False
|
||||
assert "waveform_data" in data
|
||||
assert "original_waveform_data" in data
|
||||
|
||||
def test_returns_edited_audio_when_edits_exist(self, test_client, mock_job_manager, mock_services, audio_edit_job_with_edits):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
|
||||
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
resp = test_client.get("/api/review/edit-job-2/input-audio-info")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data["edit_stack"]) == 1
|
||||
assert data["can_undo"] is True
|
||||
assert data["edit_stack"][0]["edit_id"] == "aaa"
|
||||
assert data["edit_stack"][0]["operation"] == "trim_start"
|
||||
|
||||
def test_404_when_job_not_found(self, test_client, mock_job_manager):
|
||||
mock_job_manager.get_job.return_value = None
|
||||
resp = test_client.get("/api/review/nonexistent/input-audio-info")
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_404_when_no_input_audio(self, test_client, mock_job_manager):
|
||||
job = _job(job_id="no-audio", status=JobStatus.AWAITING_AUDIO_EDIT,
|
||||
input_media_gcs_path=None, state_data={})
|
||||
mock_job_manager.get_job.return_value = job
|
||||
resp = test_client.get("/api/review/no-audio/input-audio-info")
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_uses_cached_waveform_when_available(self, test_client, mock_job_manager, mock_services):
|
||||
"""When waveform cache exists, should use it instead of on-demand generation."""
|
||||
job = _job(
|
||||
job_id="cached-job",
|
||||
status=JobStatus.AWAITING_AUDIO_EDIT,
|
||||
input_media_gcs_path="jobs/cached-job/input/song.flac",
|
||||
state_data={"audio_edit_waveform_cache_path": "jobs/cached-job/audio_edit/waveform_original.json"},
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_services["analysis"].load_cached_waveform.return_value = ([0.2, 0.6, 0.4], 180.0)
|
||||
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
|
||||
duration_seconds=180.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
resp = test_client.get("/api/review/cached-job/input-audio-info")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["original_duration_seconds"] == 180.0
|
||||
assert data["original_waveform_data"]["amplitudes"] == [0.2, 0.6, 0.4]
|
||||
# Should have used cache, not on-demand generation
|
||||
mock_services["analysis"].load_cached_waveform.assert_called_once_with(
|
||||
"jobs/cached-job/audio_edit/waveform_original.json"
|
||||
)
|
||||
mock_services["analysis"].get_waveform_data.assert_not_called()
|
||||
|
||||
def test_falls_back_to_on_demand_when_cache_missing(self, test_client, mock_job_manager, mock_services):
|
||||
"""When waveform cache path is set but cache doesn't exist, should fall back."""
|
||||
job = _job(
|
||||
job_id="no-cache-job",
|
||||
status=JobStatus.AWAITING_AUDIO_EDIT,
|
||||
input_media_gcs_path="jobs/no-cache-job/input/song.flac",
|
||||
state_data={"audio_edit_waveform_cache_path": "jobs/no-cache-job/audio_edit/waveform_original.json"},
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_services["analysis"].load_cached_waveform.return_value = None
|
||||
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
resp = test_client.get("/api/review/no-cache-job/input-audio-info")
|
||||
assert resp.status_code == 200
|
||||
# Should have fallen back to on-demand
|
||||
mock_services["analysis"].get_waveform_data.assert_called_once()
|
||||
|
||||
def test_on_demand_when_no_cache_path_in_state(self, test_client, mock_job_manager, mock_services, audio_edit_job):
|
||||
"""Jobs without cache path in state_data should use on-demand generation."""
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
resp = test_client.get("/api/review/edit-job-1/input-audio-info")
|
||||
assert resp.status_code == 200
|
||||
# No cache path → should not attempt to load cache
|
||||
mock_services["analysis"].load_cached_waveform.assert_not_called()
|
||||
mock_services["analysis"].get_waveform_data.assert_called_once()
|
||||
|
||||
|
||||
# --- POST /audio-edit/apply ---
|
||||
|
||||
class TestApplyAudioEdit:
|
||||
|
||||
def test_apply_trim_start(self, test_client, mock_job_manager, mock_services, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
mock_services["edit"].apply_edit.return_value = (
|
||||
AudioMetadata(duration_seconds=170.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=25000000),
|
||||
"jobs/edit-job-1/audio_edit/edit_abc.flac",
|
||||
)
|
||||
|
||||
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
|
||||
"operation": "trim_start",
|
||||
"params": {"end_seconds": 30.0},
|
||||
"edit_id": "abc",
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["edit_id"] == "abc"
|
||||
assert data["can_undo"] is True
|
||||
assert len(data["edit_stack"]) == 1
|
||||
assert data["edit_stack"][0]["operation"] == "trim_start"
|
||||
assert "current_audio_url" in data
|
||||
assert "waveform_data" in data
|
||||
assert "duration_after" in data
|
||||
|
||||
# Should transition to IN_AUDIO_EDIT
|
||||
mock_job_manager.transition_to_state.assert_called_once()
|
||||
|
||||
def test_apply_transitions_to_in_audio_edit(self, test_client, mock_job_manager, mock_services, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
mock_services["edit"].apply_edit.return_value = (
|
||||
AudioMetadata(duration_seconds=170.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=25000000),
|
||||
"jobs/edit-job-1/audio_edit/edit_abc.flac",
|
||||
)
|
||||
|
||||
test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
|
||||
"operation": "trim_start",
|
||||
"params": {"end_seconds": 30.0},
|
||||
})
|
||||
|
||||
mock_job_manager.transition_to_state.assert_called_once_with(
|
||||
job_id="edit-job-1",
|
||||
new_status=JobStatus.IN_AUDIO_EDIT,
|
||||
progress=15,
|
||||
message="Audio editing in progress",
|
||||
)
|
||||
|
||||
def test_apply_skips_transition_if_already_in_edit(self, test_client, mock_job_manager, mock_services, audio_edit_job_with_edits):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
|
||||
mock_services["edit"].apply_edit.return_value = (
|
||||
AudioMetadata(duration_seconds=170.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=25000000),
|
||||
"jobs/edit-job-2/audio_edit/edit_xyz.flac",
|
||||
)
|
||||
|
||||
test_client.post("/api/review/edit-job-2/audio-edit/apply", json={
|
||||
"operation": "mute",
|
||||
"params": {"start_seconds": 10.0, "end_seconds": 15.0},
|
||||
})
|
||||
|
||||
mock_job_manager.transition_to_state.assert_not_called()
|
||||
|
||||
def test_apply_missing_operation(self, test_client, mock_job_manager, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
|
||||
"params": {"end_seconds": 30.0},
|
||||
})
|
||||
assert resp.status_code == 400
|
||||
assert "operation" in resp.json()["detail"].lower()
|
||||
|
||||
def test_apply_invalid_operation(self, test_client, mock_job_manager, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
|
||||
"operation": "reverse",
|
||||
"params": {},
|
||||
})
|
||||
assert resp.status_code == 400
|
||||
assert "Invalid operation" in resp.json()["detail"]
|
||||
|
||||
def test_apply_wrong_status(self, test_client, mock_job_manager):
|
||||
job = _job(job_id="wrong-status", status=JobStatus.COMPLETE,
|
||||
input_media_gcs_path="jobs/x/input/song.flac", state_data={})
|
||||
mock_job_manager.get_job.return_value = job
|
||||
resp = test_client.post("/api/review/wrong-status/audio-edit/apply", json={
|
||||
"operation": "trim_start",
|
||||
"params": {"end_seconds": 10.0},
|
||||
})
|
||||
assert resp.status_code == 400
|
||||
assert "not in audio edit state" in resp.json()["detail"]
|
||||
|
||||
def test_apply_join_requires_upload_id(self, test_client, mock_job_manager, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
|
||||
"operation": "join_end",
|
||||
"params": {},
|
||||
})
|
||||
assert resp.status_code == 400
|
||||
assert "upload_id" in resp.json()["detail"].lower()
|
||||
|
||||
def test_apply_join_invalid_upload_id(self, test_client, mock_job_manager, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
|
||||
"operation": "join_end",
|
||||
"params": {"upload_id": "nonexistent"},
|
||||
})
|
||||
assert resp.status_code == 404
|
||||
assert "not found" in resp.json()["detail"].lower()
|
||||
|
||||
def test_apply_clears_redo_stack(self, test_client, mock_job_manager, mock_services):
|
||||
"""When applying a new edit, the redo stack should be cleared."""
|
||||
job = _job(
|
||||
job_id="redo-clear",
|
||||
status=JobStatus.IN_AUDIO_EDIT,
|
||||
input_media_gcs_path="jobs/redo-clear/input/song.flac",
|
||||
state_data={
|
||||
"audio_edit_stack": [],
|
||||
"audio_edit_redo_stack": [{"edit_id": "old", "gcs_path": "old.flac"}],
|
||||
},
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_services["edit"].apply_edit.return_value = (
|
||||
AudioMetadata(duration_seconds=180.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=25000000),
|
||||
"jobs/redo-clear/audio_edit/edit_new.flac",
|
||||
)
|
||||
|
||||
resp = test_client.post("/api/review/redo-clear/audio-edit/apply", json={
|
||||
"operation": "mute",
|
||||
"params": {"start_seconds": 5.0, "end_seconds": 10.0},
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["can_redo"] is False
|
||||
|
||||
|
||||
# --- POST /audio-edit/undo ---
|
||||
|
||||
class TestUndoAudioEdit:
|
||||
|
||||
def test_undo_pops_edit_stack(self, test_client, mock_job_manager, mock_services, audio_edit_job_with_edits):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
|
||||
|
||||
resp = test_client.post("/api/review/edit-job-2/audio-edit/undo")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data["edit_stack"]) == 0
|
||||
assert data["can_undo"] is False
|
||||
assert data["can_redo"] is True
|
||||
|
||||
# Verify state_data was updated
|
||||
update_call = mock_job_manager.update_job.call_args[0]
|
||||
state_data = update_call[1]["state_data"]
|
||||
assert len(state_data["audio_edit_stack"]) == 0
|
||||
assert len(state_data["audio_edit_redo_stack"]) == 1
|
||||
|
||||
def test_undo_nothing_to_undo(self, test_client, mock_job_manager, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
resp = test_client.post("/api/review/edit-job-1/audio-edit/undo")
|
||||
assert resp.status_code == 400
|
||||
assert "Nothing to undo" in resp.json()["detail"]
|
||||
|
||||
def test_undo_wrong_status(self, test_client, mock_job_manager):
|
||||
job = _job(job_id="done", status=JobStatus.COMPLETE, state_data={})
|
||||
mock_job_manager.get_job.return_value = job
|
||||
resp = test_client.post("/api/review/done/audio-edit/undo")
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
# --- POST /audio-edit/redo ---
|
||||
|
||||
class TestRedoAudioEdit:
|
||||
|
||||
def test_redo_pops_redo_stack(self, test_client, mock_job_manager, mock_services):
|
||||
job = _job(
|
||||
job_id="redo-job",
|
||||
status=JobStatus.IN_AUDIO_EDIT,
|
||||
input_media_gcs_path="jobs/redo-job/input/song.flac",
|
||||
state_data={
|
||||
"audio_edit_stack": [],
|
||||
"audio_edit_redo_stack": [
|
||||
{
|
||||
"edit_id": "bbb",
|
||||
"operation": "trim_end",
|
||||
"params": {"end_seconds": 180.0},
|
||||
"gcs_path": "jobs/redo-job/audio_edit/edit_bbb.flac",
|
||||
"duration_seconds": 180.0,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
resp = test_client.post("/api/review/redo-job/audio-edit/redo")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data["edit_stack"]) == 1
|
||||
assert data["can_undo"] is True
|
||||
assert data["can_redo"] is False
|
||||
|
||||
def test_redo_nothing_to_redo(self, test_client, mock_job_manager, audio_edit_job_with_edits):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
|
||||
resp = test_client.post("/api/review/edit-job-2/audio-edit/redo")
|
||||
assert resp.status_code == 400
|
||||
assert "Nothing to redo" in resp.json()["detail"]
|
||||
|
||||
|
||||
# --- POST /audio-edit/submit ---
|
||||
|
||||
class TestSubmitAudioEdit:
|
||||
|
||||
def test_submit_with_edits_copies_audio(self, test_client, mock_job_manager, audio_edit_job_with_edits):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
|
||||
|
||||
with patch(PATCH_STORAGE_SVC) as MockStorage, \
|
||||
patch(PATCH_WORKER_SVC) as mock_get_ws:
|
||||
mock_ws = AsyncMock()
|
||||
mock_get_ws.return_value = mock_ws
|
||||
|
||||
resp = test_client.post("/api/review/edit-job-2/audio-edit/submit",
|
||||
json={})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["edits_applied"] == 1
|
||||
|
||||
# Should copy edited audio to canonical path
|
||||
storage_inst = MockStorage.return_value
|
||||
storage_inst.download_file.assert_called_once()
|
||||
storage_inst.upload_file.assert_called_once()
|
||||
|
||||
# Should update input_media_gcs_path
|
||||
update_call = mock_job_manager.update_job.call_args[0]
|
||||
assert update_call[1]["input_media_gcs_path"] == "jobs/edit-job-2/input/edited.flac"
|
||||
|
||||
# Should transition to AUDIO_EDIT_COMPLETE
|
||||
mock_job_manager.transition_to_state.assert_called_once_with(
|
||||
job_id="edit-job-2",
|
||||
new_status=JobStatus.AUDIO_EDIT_COMPLETE,
|
||||
progress=18,
|
||||
message="Audio edit complete, starting processing",
|
||||
)
|
||||
|
||||
def test_submit_without_edits_uses_original(self, test_client, mock_job_manager, audio_edit_job):
|
||||
mock_job_manager.get_job.return_value = audio_edit_job
|
||||
|
||||
with patch(PATCH_STORAGE_SVC) as MockStorage, \
|
||||
patch(PATCH_WORKER_SVC) as mock_get_ws:
|
||||
mock_ws = AsyncMock()
|
||||
mock_get_ws.return_value = mock_ws
|
||||
|
||||
resp = test_client.post("/api/review/edit-job-1/audio-edit/submit",
|
||||
json={})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["edits_applied"] == 0
|
||||
|
||||
# Should NOT copy any files
|
||||
MockStorage.return_value.download_file.assert_not_called()
|
||||
|
||||
# Should NOT update input_media_gcs_path
|
||||
mock_job_manager.update_job.assert_not_called()
|
||||
|
||||
def test_submit_wrong_status(self, test_client, mock_job_manager):
|
||||
job = _job(job_id="done", status=JobStatus.COMPLETE, state_data={})
|
||||
mock_job_manager.get_job.return_value = job
|
||||
resp = test_client.post("/api/review/done/audio-edit/submit", json={})
|
||||
assert resp.status_code == 400
|
||||
|
||||
def test_submit_job_not_found(self, test_client, mock_job_manager):
|
||||
mock_job_manager.get_job.return_value = None
|
||||
resp = test_client.post("/api/review/nonexistent/audio-edit/submit", json={})
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
# --- Helper function tests ---
|
||||
|
||||
class TestHelperFunctions:
|
||||
|
||||
def test_get_current_audio_gcs_path_no_edits(self):
|
||||
from backend.api.routes.review import _get_current_audio_gcs_path
|
||||
job = _job(
|
||||
job_id="test",
|
||||
status=JobStatus.AWAITING_AUDIO_EDIT,
|
||||
input_media_gcs_path="jobs/test/input/song.flac",
|
||||
state_data={},
|
||||
)
|
||||
assert _get_current_audio_gcs_path(job) == "jobs/test/input/song.flac"
|
||||
|
||||
def test_get_current_audio_gcs_path_with_edits(self):
|
||||
from backend.api.routes.review import _get_current_audio_gcs_path
|
||||
job = _job(
|
||||
job_id="test",
|
||||
status=JobStatus.IN_AUDIO_EDIT,
|
||||
input_media_gcs_path="jobs/test/input/song.flac",
|
||||
state_data={
|
||||
"audio_edit_stack": [
|
||||
{"gcs_path": "jobs/test/audio_edit/edit_1.flac"},
|
||||
{"gcs_path": "jobs/test/audio_edit/edit_2.flac"},
|
||||
],
|
||||
},
|
||||
)
|
||||
assert _get_current_audio_gcs_path(job) == "jobs/test/audio_edit/edit_2.flac"
|
||||
|
||||
def test_get_current_audio_gcs_path_empty_state_data(self):
|
||||
from backend.api.routes.review import _get_current_audio_gcs_path
|
||||
job = _job(
|
||||
job_id="test",
|
||||
status=JobStatus.AWAITING_AUDIO_EDIT,
|
||||
input_media_gcs_path="jobs/test/input/song.flac",
|
||||
state_data={},
|
||||
)
|
||||
assert _get_current_audio_gcs_path(job) == "jobs/test/input/song.flac"
|
||||
@@ -0,0 +1,320 @@
|
||||
"""
|
||||
Tests for audio_edit_service.py — server-side FFmpeg audio editing.
|
||||
|
||||
Tests use mocked subprocess calls since we can't guarantee ffmpeg is
|
||||
available in CI. Integration tests with real audio files are in a
|
||||
separate test module.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, MagicMock, call
|
||||
|
||||
from backend.services.audio_edit_service import AudioEditService, AudioMetadata
|
||||
|
||||
|
||||
class TestGetMetadata:
|
||||
"""Test get_metadata and get_metadata_from_gcs."""
|
||||
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_get_metadata_parses_ffprobe(self, mock_run):
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=0,
|
||||
stdout=json.dumps({
|
||||
"format": {
|
||||
"duration": "245.3",
|
||||
"format_name": "flac",
|
||||
"size": "35000000",
|
||||
},
|
||||
"streams": [{
|
||||
"codec_type": "audio",
|
||||
"sample_rate": "44100",
|
||||
"channels": 2,
|
||||
}],
|
||||
}),
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
meta = service.get_metadata("/tmp/test.flac")
|
||||
|
||||
assert meta.duration_seconds == 245.3
|
||||
assert meta.sample_rate == 44100
|
||||
assert meta.channels == 2
|
||||
assert meta.format == "flac"
|
||||
assert meta.file_size_bytes == 35000000
|
||||
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_get_metadata_ffprobe_failure(self, mock_run):
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=1,
|
||||
stderr="ffprobe error",
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
with pytest.raises(RuntimeError, match="ffprobe failed"):
|
||||
service.get_metadata("/tmp/test.flac")
|
||||
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
|
||||
def test_get_metadata_from_gcs(self, mock_tmpdir, mock_run):
|
||||
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/test")
|
||||
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
|
||||
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=0,
|
||||
stdout=json.dumps({
|
||||
"format": {"duration": "100.0", "format_name": "flac", "size": "1000"},
|
||||
"streams": [{"codec_type": "audio", "sample_rate": "44100", "channels": 2}],
|
||||
}),
|
||||
)
|
||||
|
||||
mock_storage = Mock()
|
||||
service = AudioEditService(storage_service=mock_storage)
|
||||
meta = service.get_metadata_from_gcs("jobs/123/input/song.flac")
|
||||
|
||||
mock_storage.download_file.assert_called_once()
|
||||
assert meta.duration_seconds == 100.0
|
||||
|
||||
|
||||
class TestFFmpegOperations:
|
||||
"""Test trim, cut, mute, join operations via FFmpeg."""
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_trim_start(self, mock_run, mock_meta):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
result = service.trim_start("/tmp/input.flac", 30.0, "/tmp/output.flac")
|
||||
|
||||
# Check ffmpeg was called with -ss
|
||||
cmd = mock_run.call_args[0][0]
|
||||
assert "-ss" in cmd
|
||||
assert "30.0" in cmd
|
||||
assert result.duration_seconds == 200.0
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_trim_end(self, mock_run, mock_meta):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=120.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=20000000,
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
result = service.trim_end("/tmp/input.flac", 120.0, "/tmp/output.flac")
|
||||
|
||||
cmd = mock_run.call_args[0][0]
|
||||
assert "-t" in cmd
|
||||
assert "120.0" in cmd
|
||||
assert result.duration_seconds == 120.0
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_cut_region(self, mock_run, mock_meta):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=180.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=25000000,
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
result = service.cut_region("/tmp/input.flac", 30.0, 45.0, "/tmp/output.flac")
|
||||
|
||||
cmd = mock_run.call_args[0][0]
|
||||
assert "-filter_complex" in cmd
|
||||
filter_str = cmd[cmd.index("-filter_complex") + 1]
|
||||
assert "atrim=0:30.0" in filter_str
|
||||
assert "atrim=45.0" in filter_str
|
||||
assert "concat=n=2" in filter_str
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_mute_region(self, mock_run, mock_meta):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=245.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=35000000,
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
result = service.mute_region("/tmp/input.flac", 10.0, 15.0, "/tmp/output.flac")
|
||||
|
||||
cmd = mock_run.call_args[0][0]
|
||||
assert "-af" in cmd
|
||||
af_str = cmd[cmd.index("-af") + 1]
|
||||
assert "volume=enable='between(t,10.0,15.0)':volume=0" in af_str
|
||||
assert result.duration_seconds == 245.0 # Duration preserved
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_join_audio_end(self, mock_run, mock_meta):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=260.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=40000000,
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
result = service.join_audio("/tmp/main.flac", "/tmp/extra.flac", "end", "/tmp/output.flac")
|
||||
|
||||
cmd = mock_run.call_args[0][0]
|
||||
assert "-filter_complex" in cmd
|
||||
# For "end", main comes first, extra second
|
||||
assert cmd[cmd.index("-i") + 1] == "/tmp/main.flac"
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_join_audio_start(self, mock_run, mock_meta):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=260.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=40000000,
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
result = service.join_audio("/tmp/main.flac", "/tmp/extra.flac", "start", "/tmp/output.flac")
|
||||
|
||||
cmd = mock_run.call_args[0][0]
|
||||
# For "start", extra comes first, main second
|
||||
first_input_idx = cmd.index("-i") + 1
|
||||
assert cmd[first_input_idx] == "/tmp/extra.flac"
|
||||
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
def test_ffmpeg_failure_raises(self, mock_run):
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=1,
|
||||
stderr="Error: something went wrong",
|
||||
)
|
||||
|
||||
service = AudioEditService(storage_service=Mock())
|
||||
with pytest.raises(RuntimeError, match="ffmpeg failed"):
|
||||
service.trim_start("/tmp/input.flac", 30.0, "/tmp/output.flac")
|
||||
|
||||
|
||||
class TestApplyEdit:
|
||||
"""Test the apply_edit method that orchestrates download/edit/upload."""
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
|
||||
def test_apply_edit_trim_start(self, mock_tmpdir, mock_run, mock_meta):
|
||||
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
|
||||
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=200.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=30000000,
|
||||
)
|
||||
|
||||
mock_storage = Mock()
|
||||
service = AudioEditService(storage_service=mock_storage)
|
||||
|
||||
metadata, result_path = service.apply_edit(
|
||||
input_gcs_path="jobs/123/input/song.flac",
|
||||
operation="trim_start",
|
||||
params={"end_seconds": 30.0},
|
||||
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
|
||||
job_id="123",
|
||||
)
|
||||
|
||||
mock_storage.download_file.assert_called_once()
|
||||
mock_storage.upload_file.assert_called_once()
|
||||
assert result_path == "jobs/123/audio_edit/edit_abc.flac"
|
||||
assert metadata.duration_seconds == 200.0
|
||||
|
||||
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
|
||||
@patch("backend.services.audio_edit_service.subprocess.run")
|
||||
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
|
||||
def test_apply_edit_join_downloads_both_files(self, mock_tmpdir, mock_run, mock_meta):
|
||||
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
|
||||
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
mock_meta.return_value = AudioMetadata(
|
||||
duration_seconds=260.0, sample_rate=44100, channels=2,
|
||||
format="flac", file_size_bytes=40000000,
|
||||
)
|
||||
|
||||
mock_storage = Mock()
|
||||
service = AudioEditService(storage_service=mock_storage)
|
||||
|
||||
metadata, result_path = service.apply_edit(
|
||||
input_gcs_path="jobs/123/input/song.flac",
|
||||
operation="join_end",
|
||||
params={"upload_gcs_path": "jobs/123/audio_edit/upload_xyz.flac"},
|
||||
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
|
||||
job_id="123",
|
||||
)
|
||||
|
||||
# Should download both the main audio and the upload
|
||||
assert mock_storage.download_file.call_count == 2
|
||||
|
||||
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
|
||||
def test_apply_edit_unknown_operation(self, mock_tmpdir):
|
||||
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
|
||||
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
|
||||
|
||||
mock_storage = Mock()
|
||||
service = AudioEditService(storage_service=mock_storage)
|
||||
|
||||
with pytest.raises(ValueError, match="Unknown operation"):
|
||||
service.apply_edit(
|
||||
input_gcs_path="jobs/123/input/song.flac",
|
||||
operation="reverse",
|
||||
params={},
|
||||
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
|
||||
job_id="123",
|
||||
)
|
||||
|
||||
|
||||
class TestStateTransitions:
|
||||
"""Test that new job states and transitions are correctly defined."""
|
||||
|
||||
def test_new_states_exist(self):
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
assert hasattr(JobStatus, 'AWAITING_AUDIO_EDIT')
|
||||
assert hasattr(JobStatus, 'IN_AUDIO_EDIT')
|
||||
assert hasattr(JobStatus, 'AUDIO_EDIT_COMPLETE')
|
||||
assert JobStatus.AWAITING_AUDIO_EDIT.value == "awaiting_audio_edit"
|
||||
assert JobStatus.IN_AUDIO_EDIT.value == "in_audio_edit"
|
||||
assert JobStatus.AUDIO_EDIT_COMPLETE.value == "audio_edit_complete"
|
||||
|
||||
def test_downloading_can_transition_to_awaiting_audio_edit(self):
|
||||
from backend.models.job import JobStatus, STATE_TRANSITIONS
|
||||
|
||||
allowed = STATE_TRANSITIONS[JobStatus.DOWNLOADING]
|
||||
assert JobStatus.AWAITING_AUDIO_EDIT in allowed
|
||||
|
||||
def test_awaiting_audio_edit_transitions(self):
|
||||
from backend.models.job import JobStatus, STATE_TRANSITIONS
|
||||
|
||||
allowed = STATE_TRANSITIONS[JobStatus.AWAITING_AUDIO_EDIT]
|
||||
assert JobStatus.IN_AUDIO_EDIT in allowed
|
||||
assert JobStatus.AUDIO_EDIT_COMPLETE in allowed
|
||||
assert JobStatus.FAILED in allowed
|
||||
assert JobStatus.CANCELLED in allowed
|
||||
|
||||
def test_in_audio_edit_transitions(self):
|
||||
from backend.models.job import JobStatus, STATE_TRANSITIONS
|
||||
|
||||
allowed = STATE_TRANSITIONS[JobStatus.IN_AUDIO_EDIT]
|
||||
assert JobStatus.AWAITING_AUDIO_EDIT in allowed
|
||||
assert JobStatus.AUDIO_EDIT_COMPLETE in allowed
|
||||
assert JobStatus.FAILED in allowed
|
||||
assert JobStatus.CANCELLED in allowed
|
||||
|
||||
def test_audio_edit_complete_continues_to_processing(self):
|
||||
from backend.models.job import JobStatus, STATE_TRANSITIONS
|
||||
|
||||
allowed = STATE_TRANSITIONS[JobStatus.AUDIO_EDIT_COMPLETE]
|
||||
assert JobStatus.SEPARATING_STAGE1 in allowed
|
||||
assert JobStatus.TRANSCRIBING in allowed
|
||||
assert JobStatus.GENERATING_SCREENS in allowed
|
||||
assert JobStatus.FAILED in allowed
|
||||
@@ -0,0 +1,258 @@
|
||||
"""
|
||||
Tests for audio edit session persistence (Phase 2).
|
||||
|
||||
Tests the model, API endpoints, and deduplication logic.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import pytest
|
||||
from datetime import datetime, UTC, timezone
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
NOW = datetime.now(UTC)
|
||||
PATCH_JM = "backend.api.routes.review.JobManager"
|
||||
PATCH_FS = "backend.api.routes.review.FirestoreService"
|
||||
PATCH_STORAGE = "backend.api.routes.review.StorageService"
|
||||
|
||||
|
||||
def _job(**kwargs):
|
||||
defaults = dict(created_at=NOW, updated_at=NOW)
|
||||
defaults.update(kwargs)
|
||||
return Job(**defaults)
|
||||
|
||||
|
||||
# --- Model Tests ---
|
||||
|
||||
class TestAudioEditSessionModel:
|
||||
|
||||
def test_to_dict_and_from_dict_roundtrip(self):
|
||||
summary = AudioEditSessionSummary(
|
||||
total_operations=3,
|
||||
operations_breakdown={"trim_start": 1, "mute": 2},
|
||||
duration_change_seconds=-15.5,
|
||||
net_duration_seconds=184.5,
|
||||
)
|
||||
session = AudioEditSession(
|
||||
session_id="test-id",
|
||||
job_id="job-1",
|
||||
user_email="user@example.com",
|
||||
edit_count=3,
|
||||
trigger="manual",
|
||||
audio_duration_seconds=184.5,
|
||||
original_duration_seconds=200.0,
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
summary=summary,
|
||||
edit_data_gcs_path="jobs/job-1/audio_edit_sessions/test-id.json",
|
||||
data_hash="abc123",
|
||||
)
|
||||
|
||||
d = session.to_dict()
|
||||
restored = AudioEditSession.from_dict(d)
|
||||
|
||||
assert restored.session_id == "test-id"
|
||||
assert restored.job_id == "job-1"
|
||||
assert restored.edit_count == 3
|
||||
assert restored.trigger == "manual"
|
||||
assert restored.audio_duration_seconds == 184.5
|
||||
assert restored.original_duration_seconds == 200.0
|
||||
assert restored.artist == "Test Artist"
|
||||
assert restored.summary.total_operations == 3
|
||||
assert restored.summary.operations_breakdown == {"trim_start": 1, "mute": 2}
|
||||
assert restored.data_hash == "abc123"
|
||||
|
||||
def test_from_dict_with_string_datetimes(self):
|
||||
data = {
|
||||
"session_id": "sid",
|
||||
"created_at": "2026-03-08T12:00:00",
|
||||
"updated_at": "2026-03-08T12:30:00",
|
||||
}
|
||||
session = AudioEditSession.from_dict(data)
|
||||
assert session.created_at.year == 2026
|
||||
assert session.updated_at.minute == 30
|
||||
|
||||
def test_from_dict_defaults(self):
|
||||
session = AudioEditSession.from_dict({})
|
||||
assert session.edit_count == 0
|
||||
assert session.trigger == "auto"
|
||||
assert session.summary.total_operations == 0
|
||||
|
||||
def test_summary_to_dict_and_from_dict(self):
|
||||
s = AudioEditSessionSummary(total_operations=5, operations_breakdown={"cut": 5})
|
||||
d = s.to_dict()
|
||||
restored = AudioEditSessionSummary.from_dict(d)
|
||||
assert restored.total_operations == 5
|
||||
assert restored.operations_breakdown == {"cut": 5}
|
||||
|
||||
|
||||
# --- API Endpoint Tests ---
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _ensure_auth_overrides():
|
||||
"""Ensure auth overrides are set for every test."""
|
||||
from backend.api.dependencies import require_auth, require_admin, require_review_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.main import app
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
return (job_id, "full")
|
||||
|
||||
async def mock_require_auth():
|
||||
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
|
||||
message="Test", is_admin=True, user_email="test@example.com")
|
||||
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
app.dependency_overrides[require_auth] = mock_require_auth
|
||||
app.dependency_overrides[require_admin] = mock_require_auth
|
||||
yield
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(require_admin, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager():
|
||||
with patch(PATCH_JM) as MockJM:
|
||||
jm = Mock()
|
||||
MockJM.return_value = jm
|
||||
yield jm
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_firestore_svc():
|
||||
with patch(PATCH_FS) as MockFS:
|
||||
fs = Mock()
|
||||
MockFS.return_value = fs
|
||||
yield fs
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage_svc():
|
||||
with patch(PATCH_STORAGE) as MockS:
|
||||
s = Mock()
|
||||
MockS.return_value = s
|
||||
yield s
|
||||
|
||||
|
||||
class TestSaveAudioEditSession:
|
||||
|
||||
def test_save_new_session(self, test_client, mock_job_manager, mock_firestore_svc, mock_storage_svc):
|
||||
job = _job(job_id="j1", status=JobStatus.IN_AUDIO_EDIT,
|
||||
artist="Artist", title="Song", state_data={})
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_firestore_svc.get_latest_audio_edit_session_hash.return_value = None
|
||||
|
||||
edit_data = {"entries": [{"operation": "trim_start", "params": {"end_seconds": 30}}]}
|
||||
resp = test_client.post("/api/review/j1/audio-edit-sessions", json={
|
||||
"edit_data": edit_data,
|
||||
"edit_count": 1,
|
||||
"trigger": "auto",
|
||||
"summary": {
|
||||
"total_operations": 1,
|
||||
"operations_breakdown": {"trim_start": 1},
|
||||
"duration_change_seconds": -30.0,
|
||||
"net_duration_seconds": 170.0,
|
||||
},
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "saved"
|
||||
assert "session_id" in data
|
||||
|
||||
# Should upload to GCS and save to Firestore
|
||||
mock_storage_svc.upload_json.assert_called_once()
|
||||
mock_firestore_svc.save_audio_edit_session.assert_called_once()
|
||||
|
||||
def test_skip_duplicate_session(self, test_client, mock_job_manager, mock_firestore_svc):
|
||||
job = _job(job_id="j2", status=JobStatus.IN_AUDIO_EDIT, state_data={})
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
edit_data = {"entries": []}
|
||||
data_json = json.dumps(edit_data, sort_keys=True, default=str)
|
||||
existing_hash = hashlib.sha256(data_json.encode()).hexdigest()
|
||||
mock_firestore_svc.get_latest_audio_edit_session_hash.return_value = existing_hash
|
||||
|
||||
resp = test_client.post("/api/review/j2/audio-edit-sessions", json={
|
||||
"edit_data": edit_data,
|
||||
"edit_count": 0,
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "skipped"
|
||||
assert data["reason"] == "identical_data"
|
||||
|
||||
def test_save_job_not_found(self, test_client, mock_job_manager):
|
||||
mock_job_manager.get_job.return_value = None
|
||||
resp = test_client.post("/api/review/missing/audio-edit-sessions", json={
|
||||
"edit_data": {},
|
||||
})
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
class TestListAudioEditSessions:
|
||||
|
||||
def test_list_sessions(self, test_client, mock_firestore_svc):
|
||||
session = AudioEditSession(
|
||||
session_id="s1", job_id="j1", edit_count=2,
|
||||
summary=AudioEditSessionSummary(total_operations=2),
|
||||
)
|
||||
mock_firestore_svc.list_audio_edit_sessions.return_value = [session]
|
||||
|
||||
resp = test_client.get("/api/review/j1/audio-edit-sessions")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data["sessions"]) == 1
|
||||
assert data["sessions"][0]["session_id"] == "s1"
|
||||
|
||||
def test_list_empty(self, test_client, mock_firestore_svc):
|
||||
mock_firestore_svc.list_audio_edit_sessions.return_value = []
|
||||
resp = test_client.get("/api/review/j1/audio-edit-sessions")
|
||||
assert resp.status_code == 200
|
||||
assert len(resp.json()["sessions"]) == 0
|
||||
|
||||
|
||||
class TestGetAudioEditSession:
|
||||
|
||||
def test_get_with_gcs_data(self, test_client, mock_firestore_svc, mock_storage_svc):
|
||||
session = AudioEditSession(
|
||||
session_id="s1", job_id="j1",
|
||||
edit_data_gcs_path="jobs/j1/audio_edit_sessions/s1.json",
|
||||
)
|
||||
mock_firestore_svc.get_audio_edit_session.return_value = session
|
||||
mock_storage_svc.download_json.return_value = {"entries": [{"op": "trim"}]}
|
||||
|
||||
resp = test_client.get("/api/review/j1/audio-edit-sessions/s1")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["session_id"] == "s1"
|
||||
assert data["edit_data"] == {"entries": [{"op": "trim"}]}
|
||||
|
||||
def test_get_not_found(self, test_client, mock_firestore_svc):
|
||||
mock_firestore_svc.get_audio_edit_session.return_value = None
|
||||
resp = test_client.get("/api/review/j1/audio-edit-sessions/missing")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
class TestDeleteAudioEditSession:
|
||||
|
||||
def test_delete_session(self, test_client, mock_firestore_svc, mock_storage_svc):
|
||||
session = AudioEditSession(
|
||||
session_id="s1", job_id="j1",
|
||||
edit_data_gcs_path="jobs/j1/audio_edit_sessions/s1.json",
|
||||
)
|
||||
mock_firestore_svc.get_audio_edit_session.return_value = session
|
||||
|
||||
resp = test_client.delete("/api/review/j1/audio-edit-sessions/s1")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["status"] == "deleted"
|
||||
|
||||
mock_storage_svc.delete_file.assert_called_once_with("jobs/j1/audio_edit_sessions/s1.json")
|
||||
mock_firestore_svc.delete_audio_edit_session.assert_called_once_with("j1", "s1")
|
||||
|
||||
def test_delete_not_found(self, test_client, mock_firestore_svc):
|
||||
mock_firestore_svc.get_audio_edit_session.return_value = None
|
||||
resp = test_client.delete("/api/review/j1/audio-edit-sessions/missing")
|
||||
assert resp.status_code == 404
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Tests for audio processor robustness fixes.
|
||||
|
||||
Covers:
|
||||
- Stage 2 validation catches missing stems
|
||||
- _normalize_audio_files handles missing clean instrumental path
|
||||
- _generate_combined_instrumentals handles missing backing vocals path
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
|
||||
|
||||
def _make_processor():
|
||||
"""Create an AudioProcessor with mocked dependencies."""
|
||||
processor = AudioProcessor.__new__(AudioProcessor)
|
||||
processor.logger = MagicMock()
|
||||
processor.clean_instrumental_model = "model_bs_roformer"
|
||||
processor.backing_vocals_models = ["mel_band_roformer_karaoke"]
|
||||
processor.other_stems_models = []
|
||||
processor.lossless_output_format = "FLAC"
|
||||
processor.ffmpeg_base_command = "ffmpeg -y"
|
||||
return processor
|
||||
|
||||
|
||||
class TestNormalizeAudioFilesNullSafety:
|
||||
"""Tests for _normalize_audio_files defensive checks."""
|
||||
|
||||
def test_raises_on_missing_clean_instrumental(self):
|
||||
processor = _make_processor()
|
||||
separation_result = {
|
||||
"clean_instrumental": {}, # missing "instrumental" key
|
||||
"combined_instrumentals": {},
|
||||
}
|
||||
with pytest.raises(ValueError, match="clean instrumental path is missing"):
|
||||
processor._normalize_audio_files(separation_result, "Artist - Title", "/tmp/output")
|
||||
|
||||
def test_raises_on_none_clean_instrumental(self):
|
||||
processor = _make_processor()
|
||||
separation_result = {
|
||||
"clean_instrumental": {"instrumental": None},
|
||||
"combined_instrumentals": {},
|
||||
}
|
||||
with pytest.raises(ValueError, match="clean instrumental path is missing"):
|
||||
processor._normalize_audio_files(separation_result, "Artist - Title", "/tmp/output")
|
||||
|
||||
def test_works_with_valid_path(self, tmp_path):
|
||||
processor = _make_processor()
|
||||
# Create a real file so _file_exists returns True
|
||||
audio_file = tmp_path / "instrumental.flac"
|
||||
audio_file.write_bytes(b"fake audio data")
|
||||
|
||||
separation_result = {
|
||||
"clean_instrumental": {"instrumental": str(audio_file), "vocals": str(tmp_path / "vocals.flac")},
|
||||
"combined_instrumentals": {},
|
||||
"other_stems": {},
|
||||
"backing_vocals": {},
|
||||
}
|
||||
# Mock _normalize_audio to avoid actually running ffmpeg
|
||||
with patch.object(processor, "_normalize_audio"):
|
||||
processor._normalize_audio_files(separation_result, "Artist - Title", str(tmp_path))
|
||||
|
||||
# Should have logged success (no exception)
|
||||
assert processor.logger.info.called
|
||||
|
||||
def test_normalizes_combined_instrumentals(self, tmp_path):
|
||||
processor = _make_processor()
|
||||
instrumental = tmp_path / "instrumental.flac"
|
||||
instrumental.write_bytes(b"fake instrumental")
|
||||
combined = tmp_path / "combined.flac"
|
||||
combined.write_bytes(b"fake combined")
|
||||
|
||||
separation_result = {
|
||||
"clean_instrumental": {"instrumental": str(instrumental), "vocals": str(tmp_path / "v.flac")},
|
||||
"combined_instrumentals": {"mel_band_roformer_karaoke": str(combined)},
|
||||
}
|
||||
with patch.object(processor, "_normalize_audio") as mock_normalize:
|
||||
processor._normalize_audio_files(separation_result, "Artist - Title", str(tmp_path))
|
||||
|
||||
# Both clean instrumental and combined instrumental should be normalized
|
||||
assert mock_normalize.call_count == 2
|
||||
normalized_paths = [call.args[0] for call in mock_normalize.call_args_list]
|
||||
assert str(instrumental) in normalized_paths
|
||||
assert str(combined) in normalized_paths
|
||||
|
||||
|
||||
class TestGenerateCombinedInstrumentalsNullSafety:
|
||||
"""Tests for _generate_combined_instrumentals defensive checks."""
|
||||
|
||||
def test_skips_model_with_missing_backing_vocals(self, tmp_path):
|
||||
processor = _make_processor()
|
||||
instrumental_path = str(tmp_path / "instrumental.flac")
|
||||
|
||||
# Model has lead_vocals but not backing_vocals
|
||||
backing_vocals_result = {
|
||||
"mel_band_roformer_karaoke": {"lead_vocals": "/tmp/lead.flac"}
|
||||
# "backing_vocals" key is missing
|
||||
}
|
||||
result = processor._generate_combined_instrumentals(
|
||||
instrumental_path, backing_vocals_result, "Artist - Title", str(tmp_path)
|
||||
)
|
||||
assert result == {}
|
||||
processor.logger.error.assert_called_once()
|
||||
assert "backing_vocals path is missing" in processor.logger.error.call_args[0][0]
|
||||
|
||||
|
||||
class TestStage2Validation:
|
||||
"""Tests for stage 2 remote results validation in _process_audio_separation_remote."""
|
||||
|
||||
def test_organize_stage2_missing_backing_vocals_stem(self):
|
||||
"""Test that _organize_stage2_remote_results correctly handles partial results."""
|
||||
processor = _make_processor()
|
||||
|
||||
# Simulate only getting the Vocals file, not the Instrumental file
|
||||
# This is what happened in the production failure
|
||||
import tempfile, os
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
stems_dir = os.path.join(tmpdir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
# Create only the vocals file (missing the instrumental/backing vocals file)
|
||||
vocals_file = os.path.join(tmpdir, "audio_(Vocals)_mel_band_roformer_karaoke.flac")
|
||||
with open(vocals_file, "w") as f:
|
||||
f.write("fake")
|
||||
|
||||
result = processor._organize_stage2_remote_results(
|
||||
[vocals_file], "Artist - Title", stems_dir
|
||||
)
|
||||
|
||||
# Should have the model with only lead_vocals, no backing_vocals
|
||||
assert "mel_band_roformer_karaoke" in result
|
||||
assert "lead_vocals" in result["mel_band_roformer_karaoke"]
|
||||
assert "backing_vocals" not in result["mel_band_roformer_karaoke"]
|
||||
@@ -0,0 +1,192 @@
|
||||
"""
|
||||
Tests for AudioShake API retry logic.
|
||||
|
||||
Covers:
|
||||
- Retry on 5xx server errors
|
||||
- Retry on 429 rate limit
|
||||
- Retry on connection errors
|
||||
- No retry on 4xx client errors (except 429)
|
||||
- Retry exhaustion raises the original error
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
import requests
|
||||
from tenacity import wait_none
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import (
|
||||
AudioShakeAPI,
|
||||
AudioShakeConfig,
|
||||
_is_retryable_error,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_retry_wait():
|
||||
"""Disable retry wait times in all tests to avoid sleeping."""
|
||||
# Temporarily replace the wait strategy with no-wait for both retry-decorated methods
|
||||
methods = [AudioShakeAPI._request_with_retry, AudioShakeAPI._upload_file_with_retry]
|
||||
original_waits = [m.retry.wait for m in methods]
|
||||
for m in methods:
|
||||
m.retry.wait = wait_none()
|
||||
yield
|
||||
for m, w in zip(methods, original_waits):
|
||||
m.retry.wait = w
|
||||
|
||||
|
||||
class TestIsRetryableError:
|
||||
"""Tests for the _is_retryable_error predicate."""
|
||||
|
||||
def test_connection_error_is_retryable(self):
|
||||
assert _is_retryable_error(requests.exceptions.ConnectionError()) is True
|
||||
|
||||
def test_timeout_is_retryable(self):
|
||||
assert _is_retryable_error(requests.exceptions.Timeout()) is True
|
||||
|
||||
def test_502_is_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 502
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is True
|
||||
|
||||
def test_503_is_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 503
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is True
|
||||
|
||||
def test_429_is_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 429
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is True
|
||||
|
||||
def test_400_is_not_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 400
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is False
|
||||
|
||||
def test_401_is_not_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 401
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is False
|
||||
|
||||
def test_404_is_not_retryable(self):
|
||||
response = MagicMock()
|
||||
response.status_code = 404
|
||||
error = requests.exceptions.HTTPError(response=response)
|
||||
assert _is_retryable_error(error) is False
|
||||
|
||||
def test_value_error_is_not_retryable(self):
|
||||
assert _is_retryable_error(ValueError("bad")) is False
|
||||
|
||||
|
||||
class TestAudioShakeAPIRetry:
|
||||
"""Tests for AudioShakeAPI._request_with_retry."""
|
||||
|
||||
def _make_api(self):
|
||||
config = AudioShakeConfig(api_token="test-token")
|
||||
logger = MagicMock()
|
||||
return AudioShakeAPI(config, logger)
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
|
||||
def test_succeeds_on_first_try(self, mock_request):
|
||||
api = self._make_api()
|
||||
mock_response = MagicMock()
|
||||
mock_response.raise_for_status = MagicMock()
|
||||
mock_request.return_value = mock_response
|
||||
|
||||
result = api._request_with_retry("GET", "https://api.example.com/test")
|
||||
assert result == mock_response
|
||||
mock_request.assert_called_once()
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
|
||||
def test_retries_on_502_then_succeeds(self, mock_request):
|
||||
api = self._make_api()
|
||||
|
||||
# First call: 502 error
|
||||
bad_response = MagicMock()
|
||||
bad_response.status_code = 502
|
||||
bad_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=bad_response)
|
||||
|
||||
# Second call: success
|
||||
good_response = MagicMock()
|
||||
good_response.raise_for_status = MagicMock()
|
||||
|
||||
mock_request.side_effect = [bad_response, good_response]
|
||||
|
||||
result = api._request_with_retry("GET", "https://api.example.com/test")
|
||||
|
||||
assert result == good_response
|
||||
assert mock_request.call_count == 2
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
|
||||
def test_does_not_retry_on_400(self, mock_request):
|
||||
api = self._make_api()
|
||||
|
||||
bad_response = MagicMock()
|
||||
bad_response.status_code = 400
|
||||
bad_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=bad_response)
|
||||
mock_request.return_value = bad_response
|
||||
|
||||
with pytest.raises(requests.exceptions.HTTPError):
|
||||
api._request_with_retry("GET", "https://api.example.com/test")
|
||||
|
||||
# Should NOT retry — only 1 call
|
||||
mock_request.assert_called_once()
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
|
||||
def test_retries_on_connection_error(self, mock_request):
|
||||
api = self._make_api()
|
||||
|
||||
good_response = MagicMock()
|
||||
good_response.raise_for_status = MagicMock()
|
||||
|
||||
mock_request.side_effect = [
|
||||
requests.exceptions.ConnectionError("Connection refused"),
|
||||
good_response,
|
||||
]
|
||||
|
||||
result = api._request_with_retry("GET", "https://api.example.com/test")
|
||||
|
||||
assert result == good_response
|
||||
assert mock_request.call_count == 2
|
||||
|
||||
|
||||
class TestAudioShakeUploadRetry:
|
||||
"""Tests for upload_file using retry."""
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.post")
|
||||
def test_upload_file_retries_on_502(self, mock_post, tmp_path):
|
||||
config = AudioShakeConfig(api_token="test-token")
|
||||
logger = MagicMock()
|
||||
api = AudioShakeAPI(config, logger)
|
||||
|
||||
# Create a test file with known content
|
||||
test_file = tmp_path / "test.flac"
|
||||
test_file.write_bytes(b"fake audio data")
|
||||
|
||||
# First call: 502
|
||||
bad_response = MagicMock()
|
||||
bad_response.status_code = 502
|
||||
bad_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=bad_response)
|
||||
|
||||
# Second call: success
|
||||
good_response = MagicMock()
|
||||
good_response.raise_for_status = MagicMock()
|
||||
good_response.json.return_value = {"id": "asset-123"}
|
||||
good_response.status_code = 200
|
||||
good_response.text = '{"id": "asset-123"}'
|
||||
|
||||
mock_post.side_effect = [bad_response, good_response]
|
||||
|
||||
asset_id = api.upload_file(str(test_file))
|
||||
|
||||
assert asset_id == "asset-123"
|
||||
assert mock_post.call_count == 2
|
||||
|
||||
# Verify file was re-opened on each attempt (both calls got file data)
|
||||
for call_args in mock_post.call_args_list:
|
||||
files_arg = call_args[1].get("files") or call_args[0][1] if len(call_args[0]) > 1 else call_args[1].get("files")
|
||||
assert files_arg is not None, "Each retry should pass files"
|
||||
@@ -7,6 +7,8 @@ Tests cover:
|
||||
- Timestamp adjustment for instrumental audio sync
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
|
||||
|
||||
@@ -247,3 +249,77 @@ class TestCDGGenerateFromLRCWithCountdown:
|
||||
|
||||
# Verify _remove_countdown_from_lyrics was NOT called
|
||||
mock_remove.assert_not_called()
|
||||
|
||||
|
||||
class TestCDGFontFallback:
|
||||
"""Test font resolution and fallback behavior in _validate_and_setup_font."""
|
||||
|
||||
@pytest.fixture
|
||||
def generator(self, tmp_path):
|
||||
return CDGGenerator(output_dir=str(tmp_path))
|
||||
|
||||
def test_absolute_path_that_exists_is_unchanged(self, generator, tmp_path):
|
||||
"""An absolute path to an existing font is used as-is."""
|
||||
font_file = tmp_path / "myfont.ttf"
|
||||
font_file.write_bytes(b"fake font")
|
||||
cdg_styles = {"font_path": str(font_file)}
|
||||
generator._validate_and_setup_font(cdg_styles)
|
||||
assert cdg_styles["font_path"] == str(font_file)
|
||||
|
||||
def test_nonexistent_path_falls_back_to_bundled_by_filename(self, generator):
|
||||
"""A path like 'themes/nomad/assets/AvenirNext-Bold.ttf' should resolve
|
||||
to the bundled AvenirNext-Bold.ttf by filename."""
|
||||
cdg_styles = {"font_path": "themes/nomad/assets/AvenirNext-Bold.ttf"}
|
||||
generator._validate_and_setup_font(cdg_styles)
|
||||
assert cdg_styles["font_path"] is not None
|
||||
assert cdg_styles["font_path"].endswith("AvenirNext-Bold.ttf")
|
||||
assert os.path.isfile(cdg_styles["font_path"])
|
||||
|
||||
def test_totally_unknown_font_falls_back_to_arial(self, generator):
|
||||
"""A completely unknown font name falls back to bundled arial.ttf."""
|
||||
cdg_styles = {"font_path": "nonexistent/path/SuperRareFont.ttf"}
|
||||
generator._validate_and_setup_font(cdg_styles)
|
||||
assert cdg_styles["font_path"] is not None
|
||||
assert cdg_styles["font_path"].endswith("arial.ttf")
|
||||
assert os.path.isfile(cdg_styles["font_path"])
|
||||
|
||||
def test_none_font_path_is_left_alone(self, generator):
|
||||
"""If font_path is already None, _validate_and_setup_font returns early."""
|
||||
cdg_styles = {"font_path": None}
|
||||
generator._validate_and_setup_font(cdg_styles)
|
||||
assert cdg_styles["font_path"] is None
|
||||
|
||||
def test_create_toml_data_raises_on_none_font(self, generator):
|
||||
"""_create_toml_data raises RuntimeError if font_path is None."""
|
||||
cdg_styles = {
|
||||
"font_path": None,
|
||||
"clear_mode": "eager",
|
||||
"sync_offset": 0,
|
||||
"background_color": "#000000",
|
||||
"border_color": "#000000",
|
||||
"font_size": 18,
|
||||
"stroke_width": 0,
|
||||
"stroke_style": "octagon",
|
||||
"active_fill": "#ffffff",
|
||||
"active_stroke": "#000000",
|
||||
"inactive_fill": "#888888",
|
||||
"inactive_stroke": "#000000",
|
||||
"title_color": "#ffffff",
|
||||
"artist_color": "#ffffff",
|
||||
"title_screen_background": "/tmp/fake.png",
|
||||
"title_screen_transition": "centertexttoplogobottomtext",
|
||||
"row": 4,
|
||||
"line_tile_height": 3,
|
||||
"lines_per_page": 4,
|
||||
}
|
||||
with pytest.raises(RuntimeError, match="CDG font_path is None"):
|
||||
generator._create_toml_data(
|
||||
title="Test",
|
||||
artist="Artist",
|
||||
audio_file="/tmp/audio.flac",
|
||||
output_name="output",
|
||||
sync_times=[100, 200],
|
||||
instrumentals=[],
|
||||
formatted_lyrics=["HELLO", "WORLD"],
|
||||
cdg_styles=cdg_styles,
|
||||
)
|
||||
@@ -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
|
||||
@@ -405,10 +405,10 @@ class TestCreditRefundOnJobDeletion:
|
||||
class TestWelcomeCredits:
|
||||
"""Test new user welcome credits."""
|
||||
|
||||
def test_new_user_gets_2_welcome_credits(self):
|
||||
"""Verify NEW_USER_FREE_CREDITS is set to 2."""
|
||||
def test_new_user_gets_1_welcome_credit(self):
|
||||
"""Verify NEW_USER_FREE_CREDITS is set to 1."""
|
||||
from backend.services.user_service import UserService
|
||||
assert UserService.NEW_USER_FREE_CREDITS == 2
|
||||
assert UserService.NEW_USER_FREE_CREDITS == 1
|
||||
|
||||
|
||||
class TestInsufficientCreditsError:
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
"""
|
||||
Tests for AI-powered credit evaluation service.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch, PropertyMock
|
||||
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
from backend.models.user import User
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Prompt Building Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestBuildUserPrompt:
|
||||
|
||||
def test_builds_prompt_with_all_signals(self):
|
||||
from backend.services.credit_evaluation_service import _build_user_prompt
|
||||
|
||||
prompt = _build_user_prompt(
|
||||
email="test@example.com",
|
||||
grant_type="welcome",
|
||||
user_data={
|
||||
"device_fingerprint": "fp123",
|
||||
"signup_ip": "1.2.3.4",
|
||||
"credits": 0,
|
||||
"total_jobs_created": 0,
|
||||
"total_jobs_completed": 0,
|
||||
"total_spent": 0,
|
||||
"created_at": "2026-03-23",
|
||||
},
|
||||
fingerprint_matches=[
|
||||
{"email": "other@test.com", "total_jobs_created": 5, "total_spent": 0, "created_at": "2026-03-20"},
|
||||
],
|
||||
ip_matches=[],
|
||||
ip_geo={"status": "success", "country": "US", "country_code": "US", "city": "Portland", "region": "OR", "isp": "Comcast", "org": "Comcast", "as_number": "AS7922", "as_name": "Comcast"},
|
||||
recent_signups_ip=1,
|
||||
recent_signups_fp=2,
|
||||
user_agent="Mozilla/5.0",
|
||||
)
|
||||
|
||||
assert "test@example.com" in prompt
|
||||
assert "fp123" in prompt
|
||||
assert "1.2.3.4" in prompt
|
||||
assert "other@test.com" in prompt
|
||||
assert "RED FLAG" in prompt
|
||||
assert "Portland" in prompt
|
||||
assert "Comcast" in prompt
|
||||
assert "Mozilla/5.0" in prompt
|
||||
|
||||
def test_builds_prompt_without_correlations(self):
|
||||
from backend.services.credit_evaluation_service import _build_user_prompt
|
||||
|
||||
prompt = _build_user_prompt(
|
||||
email="clean@user.com",
|
||||
grant_type="welcome",
|
||||
user_data={"device_fingerprint": "fp999", "signup_ip": "5.6.7.8"},
|
||||
fingerprint_matches=[],
|
||||
ip_matches=[],
|
||||
ip_geo=None,
|
||||
recent_signups_ip=1,
|
||||
recent_signups_fp=1,
|
||||
user_agent=None,
|
||||
)
|
||||
|
||||
assert "None found" in prompt
|
||||
assert "clean@user.com" in prompt
|
||||
|
||||
def test_includes_feedback_content(self):
|
||||
from backend.services.credit_evaluation_service import _build_user_prompt
|
||||
|
||||
prompt = _build_user_prompt(
|
||||
email="test@example.com",
|
||||
grant_type="feedback",
|
||||
user_data={},
|
||||
fingerprint_matches=[],
|
||||
ip_matches=[],
|
||||
ip_geo=None,
|
||||
recent_signups_ip=0,
|
||||
recent_signups_fp=0,
|
||||
user_agent=None,
|
||||
feedback_content={
|
||||
"overall_rating": 5,
|
||||
"what_went_well": "Great audio quality!",
|
||||
"what_could_improve": "Faster processing",
|
||||
"additional_comments": "Love it",
|
||||
},
|
||||
)
|
||||
|
||||
assert "Feedback Submitted" in prompt
|
||||
assert "Great audio quality!" in prompt
|
||||
assert "5" in prompt
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Response Parsing Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestParseGeminiResponse:
|
||||
|
||||
def test_parses_grant_decision(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response('{"decision": "grant", "reasoning": "Clean user", "confidence": 0.95}')
|
||||
assert result.decision == "grant"
|
||||
assert result.reasoning == "Clean user"
|
||||
assert result.confidence == 0.95
|
||||
assert result.error is None
|
||||
|
||||
def test_parses_deny_decision(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response('{"decision": "deny", "reasoning": "Same fingerprint as 3 other accounts", "confidence": 0.9}')
|
||||
assert result.decision == "deny"
|
||||
assert "fingerprint" in result.reasoning
|
||||
|
||||
def test_handles_markdown_code_fences(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response('```json\n{"decision": "grant", "reasoning": "OK", "confidence": 0.8}\n```')
|
||||
assert result.decision == "grant"
|
||||
|
||||
def test_fails_closed_on_invalid_json(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response("I think this user is fine")
|
||||
assert result.decision == "pending_review"
|
||||
assert result.error is not None
|
||||
|
||||
def test_fails_closed_on_unexpected_decision(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response('{"decision": "maybe", "reasoning": "Unsure", "confidence": 0.5}')
|
||||
assert result.decision == "pending_review" # fail-closed
|
||||
|
||||
def test_fails_closed_on_empty_response(self):
|
||||
from backend.services.credit_evaluation_service import _parse_gemini_response
|
||||
|
||||
result = _parse_gemini_response("")
|
||||
assert result.decision == "pending_review"
|
||||
assert result.error is not None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Evaluation Service Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreditEvaluationService:
|
||||
|
||||
@patch('backend.services.credit_evaluation_service.get_settings')
|
||||
def test_returns_grant_when_disabled(self, mock_settings):
|
||||
mock_settings.return_value = MagicMock(credit_eval_enabled=False)
|
||||
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
service = CreditEvaluationService()
|
||||
result = service.evaluate("test@example.com", "welcome")
|
||||
|
||||
assert result.decision == "grant"
|
||||
assert "disabled" in result.reasoning
|
||||
|
||||
@patch('backend.services.credit_evaluation_service.get_settings')
|
||||
def test_quick_grants_clean_users(self, mock_settings):
|
||||
mock_settings.return_value = MagicMock(
|
||||
credit_eval_enabled=True,
|
||||
credit_eval_model="gemini-3.1-pro-preview",
|
||||
google_cloud_project="test",
|
||||
)
|
||||
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
service = CreditEvaluationService()
|
||||
|
||||
with patch.object(service, '_collect_signals', return_value={
|
||||
"user_data": {"email": "clean@user.com"},
|
||||
"fingerprint_matches": [],
|
||||
"ip_matches": [],
|
||||
"ip_geo": None,
|
||||
"recent_signups_ip": 1,
|
||||
"recent_signups_fp": 1,
|
||||
"user_agent": "Mozilla/5.0",
|
||||
}), patch.object(service, '_log_evaluation'):
|
||||
result = service.evaluate("clean@user.com", "welcome")
|
||||
|
||||
assert result.decision == "grant"
|
||||
assert "clean" in result.reasoning.lower()
|
||||
|
||||
@patch('backend.services.credit_evaluation_service.get_settings')
|
||||
def test_calls_gemini_when_correlations_found(self, mock_settings):
|
||||
mock_settings.return_value = MagicMock(
|
||||
credit_eval_enabled=True,
|
||||
credit_eval_model="gemini-3.1-pro-preview",
|
||||
google_cloud_project="test",
|
||||
)
|
||||
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
service = CreditEvaluationService()
|
||||
|
||||
with patch.object(service, '_collect_signals', return_value={
|
||||
"user_data": {"email": "sus@user.com", "device_fingerprint": "fp123", "signup_ip": "1.2.3.4"},
|
||||
"fingerprint_matches": [{"email": "other@test.com", "total_jobs_created": 5, "total_spent": 0, "created_at": "2026-03-20"}],
|
||||
"ip_matches": [],
|
||||
"ip_geo": None,
|
||||
"recent_signups_ip": 1,
|
||||
"recent_signups_fp": 2,
|
||||
"user_agent": None,
|
||||
}), patch.object(service, '_call_gemini', return_value='{"decision": "deny", "reasoning": "Same fingerprint", "confidence": 0.9}'), \
|
||||
patch.object(service, '_log_evaluation'):
|
||||
result = service.evaluate("sus@user.com", "welcome")
|
||||
|
||||
assert result.decision == "deny"
|
||||
|
||||
@patch('backend.services.credit_evaluation_service.get_settings')
|
||||
def test_fails_closed_on_gemini_error(self, mock_settings):
|
||||
mock_settings.return_value = MagicMock(
|
||||
credit_eval_enabled=True,
|
||||
credit_eval_model="gemini-3.1-pro-preview",
|
||||
google_cloud_project="test",
|
||||
)
|
||||
|
||||
from backend.services.credit_evaluation_service import CreditEvaluationService
|
||||
service = CreditEvaluationService()
|
||||
|
||||
with patch.object(service, '_collect_signals', side_effect=Exception("Firestore down")), \
|
||||
patch.object(service, '_log_evaluation'):
|
||||
result = service.evaluate("test@example.com", "welcome")
|
||||
|
||||
assert result.decision == "pending_review"
|
||||
assert result.error is not None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Welcome Credit Integration Tests
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestWelcomeCreditsWithEvaluation:
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_grants_credits_when_evaluation_approves(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="new@user.com", welcome_credits_granted=False)
|
||||
user_doc = MagicMock()
|
||||
user_doc.exists = True
|
||||
user_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
from backend.services.credit_evaluation_service import CreditEvaluation
|
||||
|
||||
service = UserService()
|
||||
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
|
||||
mock_eval.return_value.evaluate.return_value = CreditEvaluation(
|
||||
decision="grant", reasoning="Clean user", confidence=0.95
|
||||
)
|
||||
granted, status = service.grant_welcome_credits_if_eligible("new@user.com")
|
||||
|
||||
assert granted is True
|
||||
assert status == "granted"
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_denies_credits_when_evaluation_rejects(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="abuser@test.com", welcome_credits_granted=False)
|
||||
user_doc = MagicMock()
|
||||
user_doc.exists = True
|
||||
user_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
from backend.services.credit_evaluation_service import CreditEvaluation
|
||||
|
||||
service = UserService()
|
||||
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval, \
|
||||
patch('backend.services.email_service.get_email_service') as mock_email:
|
||||
mock_eval.return_value.evaluate.return_value = CreditEvaluation(
|
||||
decision="deny", reasoning="Same fingerprint as 3 accounts", confidence=0.9
|
||||
)
|
||||
granted, status = service.grant_welcome_credits_if_eligible("abuser@test.com")
|
||||
|
||||
assert granted is False
|
||||
assert status == "denied"
|
||||
# Verify rejection email was sent
|
||||
mock_email.return_value.send_credit_denied_email.assert_called_once_with("abuser@test.com", "welcome")
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_pending_review_when_evaluation_fails(self, mock_fs, mock_settings):
|
||||
"""Fail-closed: if evaluation crashes, credits are NOT granted, admin notified."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="new@user.com", welcome_credits_granted=False)
|
||||
user_doc = MagicMock()
|
||||
user_doc.exists = True
|
||||
user_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
|
||||
service = UserService()
|
||||
|
||||
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval, \
|
||||
patch('backend.services.email_service.get_email_service') as mock_email:
|
||||
mock_eval.return_value.evaluate.side_effect = Exception("Gemini is down")
|
||||
granted, status = service.grant_welcome_credits_if_eligible("new@user.com")
|
||||
|
||||
assert granted is False
|
||||
assert status == "pending_review"
|
||||
# Verify admin review email was sent
|
||||
mock_email.return_value.send_credit_review_needed_email.assert_called_once()
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_skips_already_granted(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="existing@user.com", welcome_credits_granted=True)
|
||||
user_doc = MagicMock()
|
||||
user_doc.exists = True
|
||||
user_doc.to_dict.return_value = user.model_dump(mode='json')
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
granted, status = service.grant_welcome_credits_if_eligible("existing@user.com")
|
||||
|
||||
assert granted is False
|
||||
assert status == "already_granted"
|
||||
@@ -0,0 +1,173 @@
|
||||
import pytest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import sys
|
||||
sys.modules['google.cloud.firestore'] = MagicMock()
|
||||
sys.modules['google.cloud.storage'] = MagicMock()
|
||||
|
||||
|
||||
class TestParseExternalBlocklist:
|
||||
def test_parse_newline_delimited_domains(self):
|
||||
from backend.services.disposable_domain_sync_service import parse_blocklist_text
|
||||
text = "tempmail.com\nmailinator.com\n\nguerrillamail.com\n"
|
||||
result = parse_blocklist_text(text)
|
||||
assert result == {"tempmail.com", "mailinator.com", "guerrillamail.com"}
|
||||
|
||||
def test_parse_strips_whitespace(self):
|
||||
from backend.services.disposable_domain_sync_service import parse_blocklist_text
|
||||
text = " tempmail.com \n mailinator.com\t\n"
|
||||
result = parse_blocklist_text(text)
|
||||
assert result == {"tempmail.com", "mailinator.com"}
|
||||
|
||||
def test_parse_lowercases_domains(self):
|
||||
from backend.services.disposable_domain_sync_service import parse_blocklist_text
|
||||
text = "TempMail.COM\nMailinator.com\n"
|
||||
result = parse_blocklist_text(text)
|
||||
assert result == {"tempmail.com", "mailinator.com"}
|
||||
|
||||
def test_parse_empty_text(self):
|
||||
from backend.services.disposable_domain_sync_service import parse_blocklist_text
|
||||
assert parse_blocklist_text("") == set()
|
||||
assert parse_blocklist_text(" \n\n ") == set()
|
||||
|
||||
|
||||
class TestFetchExternalBlocklist:
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_success(self):
|
||||
from backend.services.disposable_domain_sync_service import fetch_external_blocklist
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = "tempmail.com\nmailinator.com\n"
|
||||
mock_response.headers = {"content-length": "30"}
|
||||
|
||||
with patch("backend.services.disposable_domain_sync_service.httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client.__aexit__ = AsyncMock(return_value=False)
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_cls.return_value = mock_client
|
||||
|
||||
domains = await fetch_external_blocklist()
|
||||
assert domains == {"tempmail.com", "mailinator.com"}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_rejects_too_many_domains(self):
|
||||
from backend.services.disposable_domain_sync_service import fetch_external_blocklist
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
fake_text = "\n".join(f"domain{i}.com" for i in range(50_001))
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.text = fake_text
|
||||
mock_response.headers = {"content-length": str(len(fake_text))}
|
||||
|
||||
with patch("backend.services.disposable_domain_sync_service.httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client.__aexit__ = AsyncMock(return_value=False)
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_cls.return_value = mock_client
|
||||
|
||||
with pytest.raises(ValueError, match="exceeds maximum"):
|
||||
await fetch_external_blocklist()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_rejects_non_200(self):
|
||||
from backend.services.disposable_domain_sync_service import fetch_external_blocklist
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.status_code = 500
|
||||
mock_response.raise_for_status = MagicMock(side_effect=Exception("Server Error"))
|
||||
|
||||
with patch("backend.services.disposable_domain_sync_service.httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client.__aexit__ = AsyncMock(return_value=False)
|
||||
mock_client.get = AsyncMock(return_value=mock_response)
|
||||
mock_client_cls.return_value = mock_client
|
||||
|
||||
with pytest.raises(Exception):
|
||||
await fetch_external_blocklist()
|
||||
|
||||
|
||||
class TestSyncDisposableDomains:
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
return mock
|
||||
|
||||
def test_sync_first_run_migration(self, mock_db):
|
||||
"""First sync: migrate old disposable_domains to manual_domains."""
|
||||
from unittest.mock import patch
|
||||
from backend.services.disposable_domain_sync_service import sync_disposable_domains
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"disposable_domains": ["tempmail.com", "custom-temp.com"],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
external_domains = {"tempmail.com", "mailinator.com"}
|
||||
|
||||
with patch("backend.services.disposable_domain_sync_service.DEFAULT_DISPOSABLE_DOMAINS", set()):
|
||||
result = sync_disposable_domains(mock_db, external_domains)
|
||||
|
||||
assert result["migrated_to_manual"] == ["custom-temp.com"]
|
||||
assert result["external_count"] == 2
|
||||
|
||||
mock_db.collection.return_value.document.return_value.set.assert_called_once()
|
||||
call_data = mock_db.collection.return_value.document.return_value.set.call_args[0][0]
|
||||
assert set(call_data["external_domains"]) == {"tempmail.com", "mailinator.com"}
|
||||
assert set(call_data["manual_domains"]) == {"custom-temp.com"}
|
||||
assert "disposable_domains" not in call_data
|
||||
|
||||
def test_sync_subsequent_run(self, mock_db):
|
||||
"""Subsequent sync: just replace external_domains."""
|
||||
from backend.services.disposable_domain_sync_service import sync_disposable_domains
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com"],
|
||||
"manual_domains": ["my-custom.com"],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
external_domains = {"tempmail.com", "mailinator.com", "newdomain.com"}
|
||||
|
||||
result = sync_disposable_domains(mock_db, external_domains)
|
||||
|
||||
assert result["external_count"] == 3
|
||||
assert result["added"] == 2
|
||||
assert result["removed"] == 0
|
||||
|
||||
def test_sync_cleans_redundant_manual_domains(self, mock_db):
|
||||
"""Sync removes manual domains that now appear in external list."""
|
||||
from backend.services.disposable_domain_sync_service import sync_disposable_domains
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com"],
|
||||
"manual_domains": ["mailinator.com", "my-custom.com"],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
external_domains = {"tempmail.com", "mailinator.com"}
|
||||
|
||||
result = sync_disposable_domains(mock_db, external_domains)
|
||||
|
||||
call_data = mock_db.collection.return_value.document.return_value.set.call_args[0][0]
|
||||
assert set(call_data["manual_domains"]) == {"my-custom.com"}
|
||||
@@ -869,3 +869,47 @@ class TestVideoWorkerDistribution:
|
||||
|
||||
# Should log warning about import error
|
||||
mock_job_log.warning.assert_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handle_native_distribution_with_warnings_does_not_crash(self):
|
||||
"""Test that distribution_warnings path doesn't raise NameError.
|
||||
|
||||
Regression test: _handle_native_distribution used to reference
|
||||
undefined 'settings' variable when distribution_warnings were present.
|
||||
"""
|
||||
from backend.workers.video_worker import _handle_native_distribution
|
||||
|
||||
mock_job = MagicMock()
|
||||
mock_job.dropbox_path = None
|
||||
mock_job.gdrive_folder_id = None
|
||||
mock_job.is_private = False
|
||||
mock_job.artist = "Test Artist"
|
||||
mock_job.title = "Test Song"
|
||||
mock_job.state_data = {}
|
||||
|
||||
mock_job_log = MagicMock()
|
||||
mock_job_manager = MagicMock()
|
||||
|
||||
# Result with distribution_warnings triggers the notification path
|
||||
result_with_warnings = {
|
||||
'distribution_warnings': ['Dropbox upload failed: timeout'],
|
||||
}
|
||||
|
||||
# Should NOT raise NameError for undefined 'settings'
|
||||
with patch('backend.workers.video_worker._send_distribution_warning_notification') as mock_notify:
|
||||
await _handle_native_distribution(
|
||||
job_id="test-warnings",
|
||||
job=mock_job,
|
||||
job_log=mock_job_log,
|
||||
job_manager=mock_job_manager,
|
||||
temp_dir="/tmp/test",
|
||||
result=result_with_warnings,
|
||||
)
|
||||
|
||||
# Verify notification was called (proving the code path was exercised)
|
||||
mock_notify.assert_called_once_with(
|
||||
job_id="test-warnings",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
warnings=['Dropbox upload failed: timeout'],
|
||||
)
|
||||
@@ -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"]
|
||||
@@ -0,0 +1,156 @@
|
||||
"""
|
||||
Unit tests for EmailService review reminder and expiry email methods.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
|
||||
# Mock Google Cloud before imports
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.storage', MagicMock())
|
||||
|
||||
|
||||
class TestSendReviewReminder:
|
||||
"""Test send_review_reminder() email method."""
|
||||
|
||||
def _make_service(self):
|
||||
"""Create an EmailService with a mock provider."""
|
||||
with patch('backend.services.email_service.get_settings'):
|
||||
from backend.services.email_service import EmailService
|
||||
service = EmailService.__new__(EmailService)
|
||||
service.provider = Mock()
|
||||
service.provider.send_email.return_value = True
|
||||
service.frontend_url = "https://gen.nomadkaraoke.com"
|
||||
service.buy_url = "https://gen.nomadkaraoke.com"
|
||||
service.settings = Mock()
|
||||
return service
|
||||
|
||||
def test_subject_with_artist_and_title(self):
|
||||
"""Subject should include artist and title."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
artist="Adele",
|
||||
title="Hello",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "Adele - Hello" in call_args.kwargs["subject"]
|
||||
assert "Reminder" in call_args.kwargs["subject"]
|
||||
|
||||
def test_subject_without_artist_and_title(self):
|
||||
"""Subject should work without artist/title."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "Reminder: Your karaoke video is waiting for review" == call_args.kwargs["subject"]
|
||||
|
||||
def test_content_includes_review_link(self):
|
||||
"""HTML content should include the review URL."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
artist="Adele",
|
||||
title="Hello",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["html_content"]
|
||||
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["text_content"]
|
||||
|
||||
def test_content_includes_expiry_warning(self):
|
||||
"""Content should warn about 24h expiry."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "24 hours" in call_args.kwargs["html_content"]
|
||||
assert "expire" in call_args.kwargs["html_content"]
|
||||
|
||||
def test_content_includes_help_offer(self):
|
||||
"""Content should offer help via reply."""
|
||||
service = self._make_service()
|
||||
service.send_review_reminder(
|
||||
to_email="user@test.com",
|
||||
job_id="abc123",
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "reply to this email" in call_args.kwargs["html_content"]
|
||||
|
||||
|
||||
class TestSendReviewExpired:
|
||||
"""Test send_review_expired() email method."""
|
||||
|
||||
def _make_service(self):
|
||||
"""Create an EmailService with a mock provider."""
|
||||
with patch('backend.services.email_service.get_settings'):
|
||||
from backend.services.email_service import EmailService
|
||||
service = EmailService.__new__(EmailService)
|
||||
service.provider = Mock()
|
||||
service.provider.send_email.return_value = True
|
||||
service.frontend_url = "https://gen.nomadkaraoke.com"
|
||||
service.buy_url = "https://gen.nomadkaraoke.com"
|
||||
service.settings = Mock()
|
||||
return service
|
||||
|
||||
def test_subject_with_artist_and_title(self):
|
||||
"""Subject should include artist and title."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
artist="Adele",
|
||||
title="Hello",
|
||||
credits_balance=2,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "Adele - Hello" in call_args.kwargs["subject"]
|
||||
assert "expired" in call_args.kwargs["subject"]
|
||||
|
||||
def test_subject_without_artist_and_title(self):
|
||||
"""Subject should work without artist/title."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
credits_balance=1,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "Your karaoke video has expired" == call_args.kwargs["subject"]
|
||||
|
||||
def test_content_includes_refund_message(self):
|
||||
"""Content should confirm credit refund."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
credits_balance=3,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "refunded" in call_args.kwargs["html_content"]
|
||||
assert "3 credits" in call_args.kwargs["html_content"]
|
||||
|
||||
def test_content_shows_singular_credit(self):
|
||||
"""Should show 'credit' (singular) for balance of 1."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
credits_balance=1,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "1 credit" in call_args.kwargs["html_content"]
|
||||
# Should NOT say "1 credits"
|
||||
assert "1 credits" not in call_args.kwargs["html_content"]
|
||||
|
||||
def test_content_includes_create_link(self):
|
||||
"""Content should include a link to create a new video."""
|
||||
service = self._make_service()
|
||||
service.send_review_expired(
|
||||
to_email="user@test.com",
|
||||
credits_balance=2,
|
||||
)
|
||||
call_args = service.provider.send_email.call_args
|
||||
assert "gen.nomadkaraoke.com/app" in call_args.kwargs["html_content"]
|
||||
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
Tests for disposable email blocking in the magic link signup flow.
|
||||
|
||||
Verifies that EmailValidationService is correctly wired into the
|
||||
POST /api/users/auth/magic-link endpoint.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_validation_svc():
|
||||
"""Create a mock EmailValidationService."""
|
||||
svc = MagicMock()
|
||||
svc.is_disposable_domain.return_value = False
|
||||
svc.is_email_blocked.return_value = False
|
||||
svc.is_ip_blocked.return_value = False
|
||||
return svc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_validation_svc):
|
||||
"""Create TestClient with mocked email validation service."""
|
||||
from backend.main import app
|
||||
|
||||
with patch(
|
||||
"backend.api.routes.users.get_email_validation_service",
|
||||
return_value=mock_validation_svc,
|
||||
):
|
||||
yield TestClient(app)
|
||||
|
||||
|
||||
class TestDisposableEmailBlocking:
|
||||
"""Tests for disposable email rejection in magic link flow."""
|
||||
|
||||
def test_disposable_email_returns_422(self, client, mock_validation_svc):
|
||||
"""Disposable email domains should be rejected with 422."""
|
||||
mock_validation_svc.is_disposable_domain.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "test@yopmail.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 422
|
||||
assert response.json()["detail"] == "disposable_email_not_allowed"
|
||||
|
||||
def test_disposable_email_does_not_send_email(self, client, mock_validation_svc):
|
||||
"""Disposable email should be rejected before any email is sent."""
|
||||
mock_validation_svc.is_disposable_domain.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "abuse@tempmail.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 422
|
||||
# Validation should have been called with lowercased email
|
||||
mock_validation_svc.is_disposable_domain.assert_called_with("abuse@tempmail.com")
|
||||
|
||||
def test_blocked_email_silent_reject(self, client, mock_validation_svc):
|
||||
"""Blocked email should return generic success (anti-enumeration)."""
|
||||
mock_validation_svc.is_email_blocked.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "blocked@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
|
||||
def test_blocked_ip_silent_reject(self, client, mock_validation_svc):
|
||||
"""Blocked IP should return generic success (anti-enumeration)."""
|
||||
mock_validation_svc.is_ip_blocked.return_value = True
|
||||
|
||||
response = client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "innocent@gmail.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
|
||||
def test_email_is_lowercased_before_check(self, client, mock_validation_svc):
|
||||
"""Email should be lowercased before disposable domain check."""
|
||||
mock_validation_svc.is_disposable_domain.return_value = True
|
||||
|
||||
client.post(
|
||||
"/api/users/auth/magic-link",
|
||||
json={"email": "Test@YOPMAIL.COM"},
|
||||
)
|
||||
|
||||
mock_validation_svc.is_disposable_domain.assert_called_with("test@yopmail.com")
|
||||
|
||||
|
||||
class TestDisposableDomainList:
|
||||
"""Verify DEFAULT_DISPOSABLE_DOMAINS is now empty (replaced by external sync)."""
|
||||
|
||||
def test_defaults_empty_after_migration(self):
|
||||
from backend.services.email_validation_service import DEFAULT_DISPOSABLE_DOMAINS
|
||||
assert len(DEFAULT_DISPOSABLE_DOMAINS) == 0
|
||||
|
||||
def test_gmail_not_in_defaults(self):
|
||||
from backend.services.email_validation_service import DEFAULT_DISPOSABLE_DOMAINS
|
||||
assert "gmail.com" not in DEFAULT_DISPOSABLE_DOMAINS
|
||||
@@ -1,12 +1,16 @@
|
||||
"""
|
||||
Unit tests for EmailValidationService.
|
||||
|
||||
Tests email normalization, disposable domain detection, and blocklist management.
|
||||
Tests email normalization, disposable domain detection, blocklist management,
|
||||
and external API-based disposable domain checking (DeBounce + verifymail.io).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
|
||||
# Mock Google Cloud before imports
|
||||
import sys
|
||||
sys.modules['google.cloud.firestore'] = MagicMock()
|
||||
@@ -107,14 +111,22 @@ class TestEmailNormalization:
|
||||
|
||||
|
||||
class TestDisposableDomainDetection:
|
||||
"""Test disposable domain detection."""
|
||||
"""Test disposable domain detection (static blocklist only — external APIs mocked)."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
"""Create a mock Firestore client."""
|
||||
"""Create a mock Firestore client with new data model."""
|
||||
mock = MagicMock()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com", "mailinator.com", "guerrillamail.com"],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
|
||||
@@ -128,9 +140,26 @@ class TestDisposableDomainDetection:
|
||||
service = EmailValidationService(db=mock_db)
|
||||
return service
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_external_apis(self):
|
||||
"""Mock external API calls — these tests focus on static blocklist logic."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
# DeBounce returns clean for everything
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
# No verifymail API key configured
|
||||
mock_settings.get_secret.return_value = None
|
||||
yield mock_client
|
||||
|
||||
def test_detect_known_disposable_domain(self, email_service):
|
||||
"""Test known disposable domains are detected."""
|
||||
# These are in DEFAULT_DISPOSABLE_DOMAINS
|
||||
assert email_service.is_disposable_domain("user@tempmail.com") is True
|
||||
assert email_service.is_disposable_domain("user@mailinator.com") is True
|
||||
assert email_service.is_disposable_domain("user@guerrillamail.com") is True
|
||||
@@ -165,6 +194,7 @@ class TestBlocklistManagement:
|
||||
"disposable_domains": ["custom-temp.com"],
|
||||
"blocked_emails": ["spammer@example.com"],
|
||||
"blocked_ips": ["192.168.1.100"],
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
@@ -179,6 +209,22 @@ class TestBlocklistManagement:
|
||||
service = EmailValidationService(db=mock_db)
|
||||
return service
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_external_apis(self):
|
||||
"""Mock external API calls."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
yield
|
||||
|
||||
def test_is_email_blocked(self, email_service):
|
||||
"""Test blocked email detection."""
|
||||
assert email_service.is_email_blocked("spammer@example.com") is True
|
||||
@@ -199,16 +245,226 @@ class TestBlocklistManagement:
|
||||
assert email_service.is_disposable_domain("user@custom-temp.com") is True
|
||||
|
||||
def test_blocklist_caching(self, email_service, mock_db):
|
||||
"""Test blocklist is cached."""
|
||||
# First call
|
||||
email_service.is_disposable_domain("user@test.com")
|
||||
# Second call should use cache
|
||||
email_service.is_disposable_domain("user@test2.com")
|
||||
"""Test blocklist config is cached between calls."""
|
||||
# Use well-known providers to avoid external API calls and Firestore writes
|
||||
email_service.is_disposable_domain("user@gmail.com")
|
||||
email_service.is_disposable_domain("user@yahoo.com")
|
||||
|
||||
# Should only call Firestore once due to caching
|
||||
# Should only call Firestore once for the blocklist config (both hit WELL_KNOWN_PROVIDERS first,
|
||||
# but the first call loads the config, and the second call uses the cache)
|
||||
# Actually, well-known providers short-circuit before get_blocklist_config(), so use
|
||||
# a disposable domain instead to exercise the config loading path.
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
mock_db.collection.return_value.document.return_value.get.reset_mock()
|
||||
|
||||
email_service.is_disposable_domain("user@custom-temp.com") # hits static list
|
||||
email_service.is_disposable_domain("user@custom-temp.com") # should use cache
|
||||
|
||||
# Only 1 Firestore read for blocklist config (cached on second call)
|
||||
assert mock_db.collection.return_value.document.return_value.get.call_count == 1
|
||||
|
||||
|
||||
class TestEffectiveBlocklist:
|
||||
"""Test effective blocklist computation with new data model."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com", "mailinator.com", "allowed-one.com"],
|
||||
"manual_domains": ["my-custom.com"],
|
||||
"allowlisted_domains": ["allowed-one.com"],
|
||||
"blocked_emails": ["bad@example.com"],
|
||||
"blocked_ips": ["1.2.3.4"],
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
|
||||
@pytest.fixture
|
||||
def email_service(self, mock_db):
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
return EmailValidationService(db=mock_db)
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_external_apis(self):
|
||||
"""Mock external API calls."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
yield
|
||||
|
||||
def test_effective_set_excludes_allowlisted(self, email_service):
|
||||
config = email_service.get_blocklist_config()
|
||||
assert "tempmail.com" in config["disposable_domains"]
|
||||
assert "mailinator.com" in config["disposable_domains"]
|
||||
assert "my-custom.com" in config["disposable_domains"]
|
||||
assert "allowed-one.com" not in config["disposable_domains"]
|
||||
|
||||
def test_allowlisted_domain_not_blocked(self, email_service):
|
||||
assert email_service.is_disposable_domain("user@allowed-one.com") is False
|
||||
|
||||
def test_external_domain_blocked(self, email_service):
|
||||
assert email_service.is_disposable_domain("user@tempmail.com") is True
|
||||
|
||||
def test_manual_domain_blocked(self, email_service):
|
||||
assert email_service.is_disposable_domain("user@my-custom.com") is True
|
||||
|
||||
|
||||
class TestNewDataModelCRUD:
|
||||
"""Test CRUD operations with the new data model."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com", "mailinator.com"],
|
||||
"manual_domains": ["my-custom.com"],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
|
||||
@pytest.fixture
|
||||
def email_service(self, mock_db):
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
return EmailValidationService(db=mock_db)
|
||||
|
||||
def test_add_disposable_domain_writes_to_manual(self, email_service, mock_db):
|
||||
"""Test add_disposable_domain writes to manual_domains field."""
|
||||
email_service.add_disposable_domain("new-spam.com", "admin@test.com")
|
||||
# Get the transaction set call args
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "new-spam.com" in data["manual_domains"]
|
||||
assert "my-custom.com" in data["manual_domains"]
|
||||
|
||||
def test_remove_disposable_domain_manual(self, email_service, mock_db):
|
||||
"""Test removing a manual domain removes from manual_domains."""
|
||||
email_service.remove_disposable_domain("my-custom.com", "admin@test.com")
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "my-custom.com" not in data["manual_domains"]
|
||||
|
||||
def test_remove_disposable_domain_external_adds_to_allowlist(self, email_service, mock_db):
|
||||
"""Test removing an external domain adds it to allowlisted_domains."""
|
||||
email_service.remove_disposable_domain("tempmail.com", "admin@test.com")
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "tempmail.com" in data["allowlisted_domains"]
|
||||
# external_domains should still contain it (not removed, just allowlisted)
|
||||
assert "tempmail.com" in data["external_domains"]
|
||||
|
||||
def test_add_allowlisted_domain(self, email_service, mock_db):
|
||||
"""Test add_allowlisted_domain writes to allowlisted_domains field."""
|
||||
email_service.add_allowlisted_domain("legit.com", "admin@test.com")
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "legit.com" in data["allowlisted_domains"]
|
||||
|
||||
def test_remove_allowlisted_domain(self, email_service, mock_db):
|
||||
"""Test remove_allowlisted_domain removes from allowlisted_domains."""
|
||||
# Set up mock with an existing allowlisted domain
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["tempmail.com"],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": ["legit.com"],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
result = email_service.remove_allowlisted_domain("legit.com", "admin@test.com")
|
||||
assert result is True
|
||||
transaction = mock_db.transaction.return_value
|
||||
set_call = transaction.set
|
||||
assert set_call.called
|
||||
data = set_call.call_args[0][1]
|
||||
assert "legit.com" not in data["allowlisted_domains"]
|
||||
|
||||
def test_remove_allowlisted_domain_not_found(self, email_service, mock_db):
|
||||
"""Test remove_allowlisted_domain returns False when domain not found."""
|
||||
result = email_service.remove_allowlisted_domain("nonexistent.com", "admin@test.com")
|
||||
assert result is False
|
||||
|
||||
def test_get_blocklist_raw_data(self, email_service, mock_db):
|
||||
"""Test get_blocklist_raw_data returns all raw fields."""
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
# Clear cache so it reads fresh
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
|
||||
raw = email_service.get_blocklist_raw_data()
|
||||
assert "external_domains" in raw
|
||||
assert "manual_domains" in raw
|
||||
assert "allowlisted_domains" in raw
|
||||
assert "blocked_emails" in raw
|
||||
assert "blocked_ips" in raw
|
||||
assert "last_sync_at" in raw
|
||||
assert "last_sync_count" in raw
|
||||
assert "updated_at" in raw
|
||||
assert "updated_by" in raw
|
||||
# Check sorted
|
||||
assert raw["external_domains"] == sorted(["tempmail.com", "mailinator.com"])
|
||||
assert raw["manual_domains"] == ["my-custom.com"]
|
||||
|
||||
def test_get_blocklist_raw_data_no_doc(self, email_service, mock_db):
|
||||
"""Test get_blocklist_raw_data returns defaults when doc doesn't exist."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
raw = email_service.get_blocklist_raw_data()
|
||||
assert raw["external_domains"] == []
|
||||
assert raw["manual_domains"] == []
|
||||
assert raw["allowlisted_domains"] == []
|
||||
assert raw["last_sync_at"] is None
|
||||
|
||||
def test_get_blocklist_stats_new_model(self, email_service, mock_db):
|
||||
"""Test get_blocklist_stats returns counts for new data model fields."""
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
|
||||
stats = email_service.get_blocklist_stats()
|
||||
assert stats["external_domains_count"] == 2
|
||||
assert stats["manual_domains_count"] == 1
|
||||
assert stats["allowlisted_domains_count"] == 0
|
||||
assert stats["disposable_domains_count"] == 3 # 2 external + 1 manual - 0 allowlisted
|
||||
assert stats["blocked_emails_count"] == 0
|
||||
assert stats["blocked_ips_count"] == 0
|
||||
|
||||
|
||||
class TestIPHashing:
|
||||
"""Test IP address hashing."""
|
||||
|
||||
@@ -240,3 +496,375 @@ class TestIPHashing:
|
||||
hash_result = email_service.hash_ip("192.168.1.1")
|
||||
assert len(hash_result) == 64
|
||||
assert all(c in "0123456789abcdef" for c in hash_result)
|
||||
|
||||
|
||||
class TestExternalAPIChecks:
|
||||
"""Test external API-based disposable domain detection (DeBounce + verifymail.io)."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": ["yopmail.com"],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
mock.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
return mock
|
||||
|
||||
@pytest.fixture
|
||||
def email_service(self, mock_db):
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
return EmailValidationService(db=mock_db)
|
||||
|
||||
# =========================================================================
|
||||
# Well-known provider skip
|
||||
# =========================================================================
|
||||
|
||||
def test_well_known_providers_skip_all_checks(self, email_service):
|
||||
"""Well-known providers return False without any API calls."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client:
|
||||
assert email_service.is_disposable_domain("user@gmail.com") is False
|
||||
assert email_service.is_disposable_domain("user@yahoo.com") is False
|
||||
assert email_service.is_disposable_domain("user@hotmail.com") is False
|
||||
assert email_service.is_disposable_domain("user@outlook.com") is False
|
||||
assert email_service.is_disposable_domain("user@protonmail.com") is False
|
||||
assert email_service.is_disposable_domain("user@icloud.com") is False
|
||||
# No HTTP calls should have been made
|
||||
mock_client.return_value.get.assert_not_called()
|
||||
|
||||
# =========================================================================
|
||||
# DeBounce API
|
||||
# =========================================================================
|
||||
|
||||
def test_debounce_flags_disposable(self, email_service):
|
||||
"""DeBounce returning disposable=true should flag the domain."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "true"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
result = email_service.is_disposable_domain("user@sketchy-domain.xyz")
|
||||
assert result is True
|
||||
|
||||
def test_debounce_clean_and_no_verifymail_key(self, email_service):
|
||||
"""DeBounce clean + no verifymail key → domain is clean."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
result = email_service.is_disposable_domain("user@legit-company.com")
|
||||
assert result is False
|
||||
|
||||
def test_debounce_timeout_falls_through_to_verifymail(self, email_service):
|
||||
"""DeBounce timeout → should try verifymail.io."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
# DeBounce times out, verifymail says disposable
|
||||
mock_client.return_value.get.side_effect = [
|
||||
httpx.TimeoutException("timeout"), # DeBounce
|
||||
]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
# DeBounce returns None (error) so verifymail is NOT called
|
||||
# (tier 4 only runs if debounce_result is False, not None)
|
||||
result = email_service.is_disposable_domain("user@unknown.xyz")
|
||||
assert result is False
|
||||
|
||||
def test_debounce_error_does_not_block_users(self, email_service):
|
||||
"""If DeBounce errors, don't block the user."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_client.return_value.get.side_effect = Exception("network error")
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
result = email_service.is_disposable_domain("user@some-domain.com")
|
||||
assert result is False
|
||||
|
||||
# =========================================================================
|
||||
# verifymail.io API
|
||||
# =========================================================================
|
||||
|
||||
def test_verifymail_catches_what_debounce_misses(self, email_service):
|
||||
"""DeBounce clean + verifymail disposable → flagged."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
# DeBounce says clean, verifymail says disposable
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
|
||||
verifymail_resp = Mock()
|
||||
verifymail_resp.json.return_value = {"disposable": True, "block": True}
|
||||
verifymail_resp.raise_for_status = Mock()
|
||||
|
||||
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
result = email_service.is_disposable_domain("user@sneaky-disposable.io.vn")
|
||||
assert result is True
|
||||
|
||||
def test_verifymail_block_flag_also_triggers(self, email_service):
|
||||
"""verifymail.io block=True (even if disposable=False) → flagged."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
|
||||
verifymail_resp = Mock()
|
||||
verifymail_resp.json.return_value = {"disposable": False, "block": True}
|
||||
verifymail_resp.raise_for_status = Mock()
|
||||
|
||||
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
result = email_service.is_disposable_domain("user@blocked-domain.store")
|
||||
assert result is True
|
||||
|
||||
def test_both_apis_clean(self, email_service):
|
||||
"""Both APIs say clean → not disposable."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
|
||||
verifymail_resp = Mock()
|
||||
verifymail_resp.json.return_value = {"disposable": False, "block": False}
|
||||
verifymail_resp.raise_for_status = Mock()
|
||||
|
||||
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
result = email_service.is_disposable_domain("user@real-company.vn")
|
||||
assert result is False
|
||||
|
||||
def test_both_apis_timeout_falls_back_to_static(self, email_service):
|
||||
"""Both APIs timeout → fall back to static list (returns False for unknown domain)."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_client.return_value.get.side_effect = httpx.TimeoutException("timeout")
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
# Unknown domain not in static list → False (don't block real users)
|
||||
result = email_service.is_disposable_domain("user@unknown-domain.com")
|
||||
assert result is False
|
||||
|
||||
def test_verifymail_skipped_when_no_api_key(self, email_service):
|
||||
"""verifymail.io is skipped when API key is not configured."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = debounce_resp
|
||||
mock_settings.get_secret.return_value = None # No API key
|
||||
|
||||
result = email_service.is_disposable_domain("user@some-domain.com")
|
||||
assert result is False
|
||||
# Only one HTTP call (DeBounce), not two
|
||||
assert mock_client.return_value.get.call_count == 1
|
||||
|
||||
# =========================================================================
|
||||
# Auto-learn
|
||||
# =========================================================================
|
||||
|
||||
def test_auto_learn_adds_to_manual_domains(self, email_service, mock_db):
|
||||
"""When DeBounce flags a domain, it should be auto-learned to manual_domains."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "true"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
email_service.is_disposable_domain("user@new-disposable.xyz")
|
||||
|
||||
# Verify Firestore was written to with the domain in manual_domains
|
||||
set_calls = mock_db.collection.return_value.document.return_value.set.call_args_list
|
||||
assert len(set_calls) > 0
|
||||
# Find the auto-learn write
|
||||
for call in set_calls:
|
||||
data = call[0][0]
|
||||
if "manual_domains" in data:
|
||||
assert "new-disposable.xyz" in data["manual_domains"]
|
||||
assert data.get("updated_by") == "auto-learn"
|
||||
break
|
||||
else:
|
||||
pytest.fail("Auto-learn did not write manual_domains")
|
||||
|
||||
def test_auto_learn_verifymail_also_persists(self, email_service, mock_db):
|
||||
"""When verifymail flags a domain DeBounce missed, it should also auto-learn."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
debounce_resp = Mock()
|
||||
debounce_resp.json.return_value = {"disposable": "false"}
|
||||
debounce_resp.raise_for_status = Mock()
|
||||
|
||||
verifymail_resp = Mock()
|
||||
verifymail_resp.json.return_value = {"disposable": True, "block": True}
|
||||
verifymail_resp.raise_for_status = Mock()
|
||||
|
||||
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
|
||||
mock_settings.get_secret.return_value = "test-api-key"
|
||||
|
||||
email_service.is_disposable_domain("user@tricky-disposable.store")
|
||||
|
||||
set_calls = mock_db.collection.return_value.document.return_value.set.call_args_list
|
||||
found_auto_learn = False
|
||||
for call in set_calls:
|
||||
data = call[0][0]
|
||||
if "manual_domains" in data and "tricky-disposable.store" in data["manual_domains"]:
|
||||
found_auto_learn = True
|
||||
break
|
||||
assert found_auto_learn, "verifymail flagged domain was not auto-learned"
|
||||
|
||||
# =========================================================================
|
||||
# Verified-clean domain cache
|
||||
# =========================================================================
|
||||
|
||||
def test_verified_clean_domain_skips_api_calls(self, email_service, mock_db):
|
||||
"""Domain verified clean within 7 days should skip external API calls."""
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
|
||||
# Set up blocklist with a verified clean domain
|
||||
recent = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": [],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
"verified_clean_domains": {
|
||||
"recently-checked.com": {"checked_at": recent},
|
||||
},
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client:
|
||||
result = email_service.is_disposable_domain("user@recently-checked.com")
|
||||
assert result is False
|
||||
# No HTTP calls — skipped due to verified-clean cache
|
||||
mock_client.return_value.get.assert_not_called()
|
||||
|
||||
def test_expired_clean_domain_rechecks_api(self, email_service, mock_db):
|
||||
"""Domain verified clean >7 days ago should re-check external APIs."""
|
||||
from backend.services.email_validation_service import EmailValidationService
|
||||
|
||||
expired = (datetime.now(timezone.utc) - timedelta(days=8)).isoformat()
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"external_domains": [],
|
||||
"manual_domains": [],
|
||||
"allowlisted_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
"verified_clean_domains": {
|
||||
"expired-check.com": {"checked_at": expired},
|
||||
},
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
EmailValidationService._blocklist_cache = None
|
||||
EmailValidationService._blocklist_cache_time = None
|
||||
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
result = email_service.is_disposable_domain("user@expired-check.com")
|
||||
assert result is False
|
||||
# Should have called DeBounce since cache expired
|
||||
assert mock_client.return_value.get.call_count >= 1
|
||||
|
||||
def test_clean_result_persisted_to_firestore(self, email_service, mock_db):
|
||||
"""When both APIs say clean, the domain should be persisted as verified clean."""
|
||||
with patch(
|
||||
"backend.services.email_validation_service._get_http_client"
|
||||
) as mock_client, patch(
|
||||
"backend.services.email_validation_service.settings"
|
||||
) as mock_settings:
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"disposable": "false"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client.return_value.get.return_value = mock_response
|
||||
mock_settings.get_secret.return_value = None
|
||||
|
||||
email_service.is_disposable_domain("user@new-legit-domain.com")
|
||||
|
||||
# Check that verified_clean_domains was written
|
||||
set_calls = mock_db.collection.return_value.document.return_value.set.call_args_list
|
||||
found_clean = False
|
||||
for call in set_calls:
|
||||
data = call[0][0]
|
||||
if "verified_clean_domains" in data:
|
||||
verified = data["verified_clean_domains"]
|
||||
if "new-legit-domain.com" in verified:
|
||||
assert "checked_at" in verified["new-legit-domain.com"]
|
||||
found_clean = True
|
||||
break
|
||||
assert found_clean, "Clean domain was not persisted to verified_clean_domains"
|
||||
@@ -348,6 +348,53 @@ class TestGCEEncodingBackend:
|
||||
assert output.lossless_4k_mp4_path == "gs://bucket/output/lossless.mp4"
|
||||
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_maps_with_vocals_mp4_from_list(self, mock_get_service):
|
||||
"""Test GCE encoding maps 'With Vocals' MP4 from output_files list.
|
||||
|
||||
The GCE worker returns output_files as a list of blob paths.
|
||||
The mapper must recognize '(With Vocals).mp4' and set with_vocals_mp4_path.
|
||||
Regression test for: with_vocals_mp4 silently dropped from GCE results.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"output_files": [
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4",
|
||||
"jobs/test/finals/Artist - Title (With Vocals).mp4",
|
||||
"jobs/test/finals/Artist - Title (Karaoke).mp4",
|
||||
]
|
||||
})
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.mov",
|
||||
karaoke_video_path="/input/karaoke.mov",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
options={
|
||||
"job_id": "test-job",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
output = await backend.encode(input_config)
|
||||
|
||||
assert output.success is True
|
||||
assert output.with_vocals_mp4_path == "jobs/test/finals/Artist - Title (With Vocals).mp4"
|
||||
assert output.lossless_4k_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4"
|
||||
assert output.lossy_4k_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4"
|
||||
assert output.lossless_mkv_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv"
|
||||
assert output.lossy_720p_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4"
|
||||
|
||||
|
||||
class TestGetEncodingBackend:
|
||||
"""Test encoding backend factory function."""
|
||||
|
||||
|
||||
@@ -310,3 +310,63 @@ class TestWaitForCompletionPollTolerance:
|
||||
|
||||
assert result["status"] == "complete"
|
||||
assert call_count == 6 # 2 fail + 1 success + 2 fail + 1 success
|
||||
|
||||
|
||||
class TestDynamicURLResolution:
|
||||
"""Tests that EncodingService reads URL from Firestore, not static config."""
|
||||
|
||||
def test_url_from_worker_manager(self):
|
||||
"""Should read primary_url from worker manager."""
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_config.return_value = MagicMock(
|
||||
primary_url="http://34.1.2.3:8080",
|
||||
)
|
||||
service = EncodingService()
|
||||
service._initialized = True
|
||||
service._api_key = "test-key"
|
||||
service.set_worker_manager(mock_manager)
|
||||
|
||||
url = service._get_worker_url()
|
||||
assert url == "http://34.1.2.3:8080"
|
||||
mock_manager.get_config.assert_called_once()
|
||||
|
||||
def test_url_caches_within_ttl(self):
|
||||
"""Should cache URL and not re-read within TTL."""
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_config.return_value = MagicMock(
|
||||
primary_url="http://34.1.2.3:8080",
|
||||
)
|
||||
service = EncodingService()
|
||||
service._initialized = True
|
||||
service.set_worker_manager(mock_manager)
|
||||
|
||||
service._get_worker_url()
|
||||
service._get_worker_url()
|
||||
|
||||
assert mock_manager.get_config.call_count == 1
|
||||
|
||||
def test_url_refreshes_after_ttl(self):
|
||||
"""Should re-read URL after TTL expires."""
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_config.return_value = MagicMock(
|
||||
primary_url="http://34.1.2.3:8080",
|
||||
)
|
||||
service = EncodingService()
|
||||
service._initialized = True
|
||||
service.set_worker_manager(mock_manager)
|
||||
service._URL_CACHE_TTL = 0 # Expire immediately
|
||||
|
||||
service._get_worker_url()
|
||||
service._get_worker_url()
|
||||
|
||||
assert mock_manager.get_config.call_count == 2
|
||||
|
||||
def test_fallback_to_static_url_without_manager(self):
|
||||
"""Should fall back to static URL when no worker manager set."""
|
||||
service = EncodingService()
|
||||
service._url = "http://static:8080"
|
||||
service._api_key = "test-key"
|
||||
service._initialized = True
|
||||
|
||||
url = service._get_worker_url()
|
||||
assert url == "http://static:8080"
|
||||
@@ -0,0 +1,330 @@
|
||||
"""
|
||||
Tests for the blue-green encoding worker manager service.
|
||||
|
||||
Tests cover:
|
||||
- Task 1: Firestore config document schema, get_config, update_activity, swap_roles
|
||||
- Task 2: VM lifecycle (get_vm_status, start_vm, stop_vm, ensure_primary_running)
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
|
||||
from backend.services.encoding_worker_manager import (
|
||||
EncodingWorkerConfig,
|
||||
EncodingWorkerManager,
|
||||
CONFIG_COLLECTION,
|
||||
CONFIG_DOCUMENT,
|
||||
ENCODING_WORKER_PORT,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_firestore_data(**overrides):
|
||||
"""Create a realistic Firestore document dict for encoding-worker config."""
|
||||
data = {
|
||||
"primary_vm": "encoding-worker-blue",
|
||||
"primary_ip": "10.128.0.50",
|
||||
"primary_version": "1.0.0",
|
||||
"primary_deployed_at": "2026-03-20T10:00:00Z",
|
||||
"secondary_vm": "encoding-worker-green",
|
||||
"secondary_ip": "10.128.0.51",
|
||||
"secondary_version": "0.9.0",
|
||||
"secondary_deployed_at": "2026-03-19T08:00:00Z",
|
||||
"last_swap_at": "2026-03-20T10:00:00Z",
|
||||
"last_activity_at": "2026-03-24T12:00:00Z",
|
||||
"deploy_in_progress": False,
|
||||
"deploy_in_progress_since": None,
|
||||
}
|
||||
data.update(overrides)
|
||||
return data
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db():
|
||||
"""Return a mock Firestore client with a pre-configured config document."""
|
||||
db = MagicMock()
|
||||
snapshot = MagicMock()
|
||||
snapshot.exists = True
|
||||
snapshot.to_dict.return_value = _make_firestore_data()
|
||||
|
||||
doc_ref = MagicMock()
|
||||
doc_ref.get.return_value = snapshot
|
||||
|
||||
collection_ref = MagicMock()
|
||||
collection_ref.document.return_value = doc_ref
|
||||
|
||||
db.collection.return_value = collection_ref
|
||||
return db
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_compute():
|
||||
"""Return a mock Compute Engine InstancesClient."""
|
||||
return MagicMock()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager(mock_db, mock_compute):
|
||||
return EncodingWorkerManager(
|
||||
db=mock_db,
|
||||
compute_client=mock_compute,
|
||||
project_id="nomadkaraoke",
|
||||
zone="us-central1-c",
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 1: Config dataclass
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestEncodingWorkerConfig:
|
||||
"""Tests for the EncodingWorkerConfig dataclass."""
|
||||
|
||||
def test_primary_url(self):
|
||||
config = EncodingWorkerConfig(
|
||||
primary_vm="blue", primary_ip="10.0.0.1", primary_version="1.0",
|
||||
primary_deployed_at=None,
|
||||
secondary_vm="green", secondary_ip="10.0.0.2",
|
||||
secondary_version=None, secondary_deployed_at=None,
|
||||
last_swap_at=None, last_activity_at=None,
|
||||
deploy_in_progress=False, deploy_in_progress_since=None,
|
||||
)
|
||||
assert config.primary_url == "http://10.0.0.1:8080"
|
||||
|
||||
def test_secondary_url(self):
|
||||
config = EncodingWorkerConfig(
|
||||
primary_vm="blue", primary_ip="10.0.0.1", primary_version="1.0",
|
||||
primary_deployed_at=None,
|
||||
secondary_vm="green", secondary_ip="10.0.0.2",
|
||||
secondary_version=None, secondary_deployed_at=None,
|
||||
last_swap_at=None, last_activity_at=None,
|
||||
deploy_in_progress=False, deploy_in_progress_since=None,
|
||||
)
|
||||
assert config.secondary_url == "http://10.0.0.2:8080"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 1: get_config / update_activity / swap_roles
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestEncodingWorkerManager:
|
||||
"""Tests for Firestore config operations."""
|
||||
|
||||
def test_get_config_returns_dataclass(self, manager, mock_db):
|
||||
config = manager.get_config()
|
||||
assert isinstance(config, EncodingWorkerConfig)
|
||||
assert config.primary_vm == "encoding-worker-blue"
|
||||
assert config.primary_ip == "10.128.0.50"
|
||||
assert config.primary_version == "1.0.0"
|
||||
assert config.secondary_vm == "encoding-worker-green"
|
||||
assert config.deploy_in_progress is False
|
||||
|
||||
def test_get_config_document_not_found(self, manager, mock_db):
|
||||
snapshot = MagicMock()
|
||||
snapshot.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = snapshot
|
||||
|
||||
with pytest.raises(ValueError, match="not found"):
|
||||
manager.get_config()
|
||||
|
||||
def test_get_config_reads_correct_path(self, manager, mock_db):
|
||||
manager.get_config()
|
||||
mock_db.collection.assert_called_with(CONFIG_COLLECTION)
|
||||
mock_db.collection.return_value.document.assert_called_with(CONFIG_DOCUMENT)
|
||||
|
||||
def test_update_activity_sets_timestamp(self, manager, mock_db):
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
manager.update_activity()
|
||||
|
||||
doc_ref = mock_db.collection.return_value.document.return_value
|
||||
doc_ref.update.assert_called_once_with({
|
||||
"last_activity_at": "2026-03-24T15:00:00+00:00",
|
||||
})
|
||||
|
||||
def test_swap_roles_uses_transaction(self, manager, mock_db):
|
||||
"""swap_roles should use a Firestore transaction for atomicity."""
|
||||
# Set up the transaction mock
|
||||
mock_transaction = MagicMock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
# The transactional function is called with the transaction
|
||||
manager.swap_roles(
|
||||
new_primary_vm="encoding-worker-green",
|
||||
new_primary_ip="10.128.0.51",
|
||||
new_primary_version="2.0.0",
|
||||
old_primary_vm="encoding-worker-blue",
|
||||
old_primary_ip="10.128.0.50",
|
||||
old_primary_version="1.0.0",
|
||||
)
|
||||
|
||||
# Verify transaction was created and the doc was updated within it
|
||||
mock_db.transaction.assert_called_once()
|
||||
|
||||
def test_swap_roles_writes_correct_data(self, manager, mock_db):
|
||||
"""swap_roles should write the swapped primary/secondary fields."""
|
||||
mock_transaction = MagicMock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 3, 24, 16, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
|
||||
manager.swap_roles(
|
||||
new_primary_vm="encoding-worker-green",
|
||||
new_primary_ip="10.128.0.51",
|
||||
new_primary_version="2.0.0",
|
||||
old_primary_vm="encoding-worker-blue",
|
||||
old_primary_ip="10.128.0.50",
|
||||
old_primary_version="1.0.0",
|
||||
)
|
||||
|
||||
# The transaction.update call should contain the swapped values
|
||||
doc_ref = mock_db.collection.return_value.document.return_value
|
||||
update_call = mock_transaction.update.call_args
|
||||
assert update_call is not None
|
||||
data = update_call[0][1] # second positional arg is the data dict
|
||||
assert data["primary_vm"] == "encoding-worker-green"
|
||||
assert data["primary_ip"] == "10.128.0.51"
|
||||
assert data["primary_version"] == "2.0.0"
|
||||
assert data["secondary_vm"] == "encoding-worker-blue"
|
||||
assert data["secondary_ip"] == "10.128.0.50"
|
||||
assert data["secondary_version"] == "1.0.0"
|
||||
assert data["last_swap_at"] == "2026-03-24T16:00:00+00:00"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 2: VM lifecycle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestVMLifecycle:
|
||||
"""Tests for Compute Engine VM operations."""
|
||||
|
||||
def test_get_vm_status_returns_status(self, manager, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "RUNNING"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
status = manager.get_vm_status("encoding-worker-blue")
|
||||
assert status == "RUNNING"
|
||||
mock_compute.get.assert_called_once_with(
|
||||
project="nomadkaraoke",
|
||||
zone="us-central1-c",
|
||||
instance="encoding-worker-blue",
|
||||
)
|
||||
|
||||
def test_get_vm_status_terminated(self, manager, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
assert manager.get_vm_status("encoding-worker-blue") == "TERMINATED"
|
||||
|
||||
def test_start_vm_calls_compute_start(self, manager, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
manager.start_vm("encoding-worker-blue")
|
||||
mock_compute.start.assert_called_once_with(
|
||||
project="nomadkaraoke",
|
||||
zone="us-central1-c",
|
||||
instance="encoding-worker-blue",
|
||||
)
|
||||
|
||||
def test_start_vm_skips_if_already_running(self, manager, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "RUNNING"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
manager.start_vm("encoding-worker-blue")
|
||||
mock_compute.start.assert_not_called()
|
||||
|
||||
def test_stop_vm_calls_compute_stop(self, manager, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "RUNNING"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
manager.stop_vm("encoding-worker-blue")
|
||||
mock_compute.stop.assert_called_once_with(
|
||||
project="nomadkaraoke",
|
||||
zone="us-central1-c",
|
||||
instance="encoding-worker-blue",
|
||||
)
|
||||
|
||||
def test_stop_vm_skips_if_already_terminated(self, manager, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
manager.stop_vm("encoding-worker-blue")
|
||||
mock_compute.stop.assert_not_called()
|
||||
|
||||
def test_ensure_primary_running_starts_stopped_vm(self, manager, mock_db, mock_compute):
|
||||
"""When primary is stopped, ensure_primary_running should start it."""
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
result = manager.ensure_primary_running()
|
||||
|
||||
assert result["started"] is True
|
||||
assert result["vm_name"] == "encoding-worker-blue"
|
||||
assert result["primary_url"] == "http://10.128.0.50:8080"
|
||||
mock_compute.start.assert_called_once()
|
||||
|
||||
def test_ensure_primary_running_already_running(self, manager, mock_db, mock_compute):
|
||||
"""When primary is already running, should not start and still update activity."""
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "RUNNING"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
result = manager.ensure_primary_running()
|
||||
|
||||
assert result["started"] is False
|
||||
assert result["vm_name"] == "encoding-worker-blue"
|
||||
assert result["primary_url"] == "http://10.128.0.50:8080"
|
||||
mock_compute.start.assert_not_called()
|
||||
|
||||
def test_ensure_primary_running_updates_activity(self, manager, mock_db, mock_compute):
|
||||
"""ensure_primary_running should always update last_activity_at."""
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "RUNNING"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
manager.ensure_primary_running()
|
||||
|
||||
doc_ref = mock_db.collection.return_value.document.return_value
|
||||
doc_ref.update.assert_called_once()
|
||||
|
||||
def test_start_vm_skips_if_staging(self, manager, mock_compute):
|
||||
"""start_vm should also skip if VM is in STAGING state (already starting)."""
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "STAGING"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
manager.start_vm("encoding-worker-blue")
|
||||
mock_compute.start.assert_not_called()
|
||||
|
||||
def test_stop_vm_skips_if_stopping(self, manager, mock_compute):
|
||||
"""stop_vm should skip if VM is already in STOPPING state."""
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "STOPPING"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
manager.stop_vm("encoding-worker-blue")
|
||||
mock_compute.stop.assert_not_called()
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
Unit tests for encoding worker lifecycle endpoints.
|
||||
|
||||
Tests the warmup and heartbeat API endpoints.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.api.routes.encoding_worker import router, get_worker_manager
|
||||
from backend.api.dependencies import require_admin
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
return ("admin-token", "admin", 0)
|
||||
|
||||
|
||||
class TestWarmupEndpoint:
|
||||
def setup_method(self):
|
||||
self.mock_manager = MagicMock()
|
||||
self.app = FastAPI()
|
||||
self.app.include_router(router, prefix="/api")
|
||||
self.app.dependency_overrides[require_admin] = get_mock_admin
|
||||
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
|
||||
self.client = TestClient(self.app)
|
||||
|
||||
def test_warmup_starts_stopped_vm(self):
|
||||
self.mock_manager.ensure_primary_running.return_value = {
|
||||
"started": True,
|
||||
"vm_name": "encoding-worker-a",
|
||||
"primary_url": "http://34.1.2.3:8080",
|
||||
}
|
||||
response = self.client.post("/api/internal/encoding-worker/warmup")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["started"] is True
|
||||
assert data["vm_name"] == "encoding-worker-a"
|
||||
|
||||
def test_warmup_already_running(self):
|
||||
self.mock_manager.ensure_primary_running.return_value = {
|
||||
"started": False,
|
||||
"vm_name": "encoding-worker-a",
|
||||
"primary_url": "http://34.1.2.3:8080",
|
||||
}
|
||||
response = self.client.post("/api/internal/encoding-worker/warmup")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
|
||||
def test_warmup_handles_error(self):
|
||||
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
|
||||
"VM not found"
|
||||
)
|
||||
response = self.client.post("/api/internal/encoding-worker/warmup")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
assert "error" in response.json()
|
||||
|
||||
|
||||
class TestHeartbeatEndpoint:
|
||||
def setup_method(self):
|
||||
self.mock_manager = MagicMock()
|
||||
self.app = FastAPI()
|
||||
self.app.include_router(router, prefix="/api")
|
||||
self.app.dependency_overrides[require_admin] = get_mock_admin
|
||||
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
|
||||
self.client = TestClient(self.app)
|
||||
|
||||
def test_heartbeat_updates_activity(self):
|
||||
response = self.client.post("/api/internal/encoding-worker/heartbeat")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "ok"
|
||||
self.mock_manager.update_activity.assert_called_once()
|
||||
|
||||
def test_heartbeat_handles_error(self):
|
||||
self.mock_manager.update_activity.side_effect = RuntimeError(
|
||||
"Firestore error"
|
||||
)
|
||||
response = self.client.post("/api/internal/encoding-worker/heartbeat")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "error"
|
||||
@@ -698,21 +698,21 @@ class TestSignedUrlGCSPathGeneration:
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "style_params", "style.json")
|
||||
assert path == "uploads/test123/style/style_params.json"
|
||||
assert path == "jobs/test123/style/style_params.json"
|
||||
|
||||
def test_style_background_gcs_path(self):
|
||||
"""Test GCS path generation for style background images."""
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "style_intro_background", "bg.png")
|
||||
assert path == "uploads/test123/style/intro_background.png"
|
||||
assert path == "jobs/test123/style/intro_background.png"
|
||||
|
||||
def test_style_font_gcs_path(self):
|
||||
"""Test GCS path generation for font file."""
|
||||
from backend.api.routes.file_upload import _get_gcs_path_for_file
|
||||
|
||||
path = _get_gcs_path_for_file("test123", "style_font", "font.ttf")
|
||||
assert path == "uploads/test123/style/font.ttf"
|
||||
assert path == "jobs/test123/style/font.ttf"
|
||||
|
||||
def test_lyrics_file_gcs_path(self):
|
||||
"""Test GCS path generation for lyrics file."""
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
"""
|
||||
Tests for IP geolocation service.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from datetime import datetime
|
||||
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
|
||||
|
||||
|
||||
class TestIsPrivateIp:
|
||||
def test_private_ipv4(self):
|
||||
from backend.services.ip_geolocation_service import _is_private_ip
|
||||
assert _is_private_ip("10.0.0.1") is True
|
||||
assert _is_private_ip("192.168.1.1") is True
|
||||
assert _is_private_ip("172.16.0.1") is True
|
||||
assert _is_private_ip("169.254.169.126") is True
|
||||
assert _is_private_ip("127.0.0.1") is True
|
||||
|
||||
def test_public_ipv4(self):
|
||||
from backend.services.ip_geolocation_service import _is_private_ip
|
||||
assert _is_private_ip("8.8.8.8") is False
|
||||
assert _is_private_ip("1.2.3.4") is False
|
||||
|
||||
def test_invalid_ip(self):
|
||||
from backend.services.ip_geolocation_service import _is_private_ip
|
||||
assert _is_private_ip("not-an-ip") is True
|
||||
assert _is_private_ip("") is True
|
||||
|
||||
def test_ipv6(self):
|
||||
from backend.services.ip_geolocation_service import _is_private_ip
|
||||
assert _is_private_ip("::1") is True # loopback
|
||||
assert _is_private_ip("2001:db8::1") is True # documentation range
|
||||
assert _is_private_ip("2402:800:63ac::1") is False # public
|
||||
|
||||
|
||||
class TestParseIpApiResponse:
|
||||
def test_success_response(self):
|
||||
from backend.services.ip_geolocation_service import _parse_ip_api_response
|
||||
data = {
|
||||
"status": "success",
|
||||
"country": "United States",
|
||||
"countryCode": "US",
|
||||
"regionName": "South Carolina",
|
||||
"city": "Lancaster",
|
||||
"isp": "Comporium Inc",
|
||||
"org": "Comporium Inc",
|
||||
"as": "AS14615 Comporium Inc",
|
||||
"timezone": "America/New_York",
|
||||
"query": "8.8.8.8",
|
||||
}
|
||||
result = _parse_ip_api_response(data)
|
||||
assert result["status"] == "success"
|
||||
assert result["country_code"] == "US"
|
||||
assert result["city"] == "Lancaster"
|
||||
assert result["isp"] == "Comporium Inc"
|
||||
assert result["as_number"] == "AS14615"
|
||||
assert result["as_name"] == "Comporium Inc"
|
||||
|
||||
def test_fail_response(self):
|
||||
from backend.services.ip_geolocation_service import _parse_ip_api_response
|
||||
result = _parse_ip_api_response({"status": "fail", "query": "bad"})
|
||||
assert result["status"] == "fail"
|
||||
|
||||
|
||||
class TestLookupIp:
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_private_ip_returns_immediately(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_fs.Client.return_value = MagicMock()
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
result = service.lookup_ip("192.168.1.1")
|
||||
assert result["status"] == "private"
|
||||
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_cache_hit_returns_cached(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
cached_data = {
|
||||
"status": "success",
|
||||
"ip": "8.8.8.8",
|
||||
"country_code": "US",
|
||||
"cached_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = cached_data
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
result = service.lookup_ip("8.8.8.8")
|
||||
assert result["status"] == "success"
|
||||
assert result["country_code"] == "US"
|
||||
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
@patch('backend.services.ip_geolocation_service.httpx')
|
||||
def test_cache_miss_fetches_from_api(self, mock_httpx, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# Cache miss
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
# Mock httpx response
|
||||
mock_response = MagicMock()
|
||||
mock_response.json.return_value = {
|
||||
"status": "success",
|
||||
"country": "Vietnam",
|
||||
"countryCode": "VN",
|
||||
"regionName": "Ho Chi Minh",
|
||||
"city": "Ho Chi Minh City",
|
||||
"isp": "Viettel",
|
||||
"org": "Viettel Group",
|
||||
"as": "AS7552 Viettel Group",
|
||||
"timezone": "Asia/Ho_Chi_Minh",
|
||||
"query": "14.191.152.247",
|
||||
}
|
||||
mock_client = MagicMock()
|
||||
mock_client.__enter__ = MagicMock(return_value=mock_client)
|
||||
mock_client.__exit__ = MagicMock(return_value=False)
|
||||
mock_client.get.return_value = mock_response
|
||||
mock_httpx.Client.return_value = mock_client
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
result = service.lookup_ip("14.191.152.247")
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["country_code"] == "VN"
|
||||
assert result["isp"] == "Viettel"
|
||||
# Should have cached the result
|
||||
mock_db.collection.return_value.document.return_value.set.assert_called_once()
|
||||
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_null_ip_returns_private(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_fs.Client.return_value = MagicMock()
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
result = service.lookup_ip("")
|
||||
assert result["status"] == "private"
|
||||
result2 = service.lookup_ip(None)
|
||||
assert result2["status"] == "private"
|
||||
|
||||
|
||||
class TestLookupBatch:
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_all_cached(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
cached_data = {
|
||||
"status": "success",
|
||||
"ip": "8.8.8.8",
|
||||
"country_code": "US",
|
||||
"cached_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = cached_data
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
results = service.lookup_ips_batch(["8.8.8.8"])
|
||||
assert "8.8.8.8" in results
|
||||
assert results["8.8.8.8"]["status"] == "success"
|
||||
|
||||
@patch('backend.services.ip_geolocation_service.get_settings')
|
||||
@patch('backend.services.ip_geolocation_service.firestore')
|
||||
def test_private_ips_in_batch(self, mock_fs, mock_settings):
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_fs.Client.return_value = MagicMock()
|
||||
|
||||
from backend.services.ip_geolocation_service import IpGeolocationService
|
||||
service = IpGeolocationService()
|
||||
results = service.lookup_ips_batch(["192.168.1.1", "10.0.0.1"])
|
||||
assert results["192.168.1.1"]["status"] == "private"
|
||||
assert results["10.0.0.1"]["status"] == "private"
|
||||
|
||||
|
||||
class TestAdminEndpoints:
|
||||
@pytest.fixture
|
||||
def admin_client(self):
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_admin
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
mock_auth = MagicMock()
|
||||
mock_auth.is_admin = True
|
||||
app.dependency_overrides[require_admin] = lambda: mock_auth
|
||||
|
||||
yield TestClient(app)
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
@patch('backend.api.routes.admin.get_ip_geolocation_service')
|
||||
def test_single_ip_endpoint(self, mock_get_svc, admin_client):
|
||||
mock_svc = MagicMock()
|
||||
mock_svc.lookup_ip.return_value = {
|
||||
"status": "success",
|
||||
"ip": "8.8.8.8",
|
||||
"country_code": "US",
|
||||
}
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
response = admin_client.get("/api/admin/abuse/ip-info/8.8.8.8")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["country_code"] == "US"
|
||||
|
||||
@patch('backend.api.routes.admin.get_ip_geolocation_service')
|
||||
def test_batch_endpoint(self, mock_get_svc, admin_client):
|
||||
mock_svc = MagicMock()
|
||||
mock_svc.lookup_ips_batch.return_value = {
|
||||
"8.8.8.8": {"status": "success", "country_code": "US"},
|
||||
"1.1.1.1": {"status": "success", "country_code": "AU"},
|
||||
}
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
response = admin_client.post(
|
||||
"/api/admin/abuse/ip-info/batch",
|
||||
json={"ips": ["8.8.8.8", "1.1.1.1"]},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["8.8.8.8"]["country_code"] == "US"
|
||||
assert data["1.1.1.1"]["country_code"] == "AU"
|
||||
@@ -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,514 @@
|
||||
"""
|
||||
Tests for Modal → GCP audio separation migration.
|
||||
|
||||
Covers:
|
||||
- Pipeline decoupling: separation no longer gates lyrics review
|
||||
- Preset-based model configuration
|
||||
- Custom output filenames (job_id prefix)
|
||||
- Screens worker prerequisites relaxation
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
|
||||
# ==================== Fixtures ====================
|
||||
|
||||
@pytest.fixture
|
||||
def mock_firestore_service():
|
||||
with patch('backend.services.job_manager.FirestoreService') as mock:
|
||||
service = Mock()
|
||||
mock.return_value = service
|
||||
yield service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(mock_firestore_service):
|
||||
return JobManager()
|
||||
|
||||
|
||||
def _make_job(job_id="test-001", state_data=None, **kwargs):
|
||||
defaults = dict(
|
||||
job_id=job_id,
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.DOWNLOADING,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
theme_id="default",
|
||||
)
|
||||
defaults.update(kwargs)
|
||||
if state_data is not None:
|
||||
defaults["state_data"] = state_data
|
||||
return Job(**defaults)
|
||||
|
||||
|
||||
# ==================== P0: Pipeline Decoupling ====================
|
||||
|
||||
class TestPipelineDecoupling:
|
||||
"""
|
||||
Critical: verify separation is decoupled from lyrics review path.
|
||||
|
||||
New behavior:
|
||||
- check_parallel_processing_complete() only checks lyrics_complete
|
||||
- mark_audio_complete() sets flag but does NOT trigger screens
|
||||
- mark_lyrics_complete() triggers screens on its own (no audio gate)
|
||||
"""
|
||||
|
||||
def test_check_parallel_only_requires_lyrics(self, job_manager, mock_firestore_service):
|
||||
"""lyrics_complete=True is sufficient, even without audio_complete."""
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
|
||||
assert job_manager.check_parallel_processing_complete("test-001") is True
|
||||
|
||||
def test_check_parallel_fails_without_lyrics(self, job_manager, mock_firestore_service):
|
||||
"""lyrics_complete=False means not ready, even if audio_complete=True."""
|
||||
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
|
||||
assert job_manager.check_parallel_processing_complete("test-001") is False
|
||||
|
||||
def test_check_parallel_fails_with_empty_state(self, job_manager, mock_firestore_service):
|
||||
"""Empty state_data means not ready."""
|
||||
job = _make_job(state_data={})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
|
||||
assert job_manager.check_parallel_processing_complete("test-001") is False
|
||||
|
||||
def test_mark_audio_complete_does_not_trigger_screens(self, job_manager, mock_firestore_service):
|
||||
"""Critical: audio completion must NOT trigger screens worker."""
|
||||
job = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
|
||||
def test_mark_lyrics_complete_triggers_screens_without_audio(self, job_manager, mock_firestore_service):
|
||||
"""Critical: lyrics completion triggers screens even if audio isn't done."""
|
||||
# After update_state_data sets lyrics_complete, get_job returns updated state
|
||||
job_after_update = _make_job(state_data={"audio_complete": False, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_after_update
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once_with("test-001")
|
||||
|
||||
def test_mark_lyrics_complete_triggers_screens_with_audio(self, job_manager, mock_firestore_service):
|
||||
"""Lyrics completion triggers screens when audio is already done too."""
|
||||
job_after_update = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_after_update
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once_with("test-001")
|
||||
|
||||
def test_ordering_audio_first_then_lyrics(self, job_manager, mock_firestore_service):
|
||||
"""Typical flow: audio finishes first, then lyrics triggers screens."""
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
# Audio completes first — get_job returns state without lyrics_complete
|
||||
job_audio_only = _make_job(state_data={"audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_audio_only
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
|
||||
# Now lyrics completes — get_job returns state with both flags
|
||||
job_both = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_both
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once()
|
||||
|
||||
def test_ordering_lyrics_first_then_audio(self, job_manager, mock_firestore_service):
|
||||
"""Less common: lyrics finishes first, triggers screens immediately."""
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
# Lyrics completes first — get_job returns state with lyrics_complete
|
||||
job_lyrics_only = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_lyrics_only
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once()
|
||||
|
||||
# Audio completes later — should NOT trigger screens again
|
||||
job_both = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_both
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
|
||||
|
||||
# ==================== P0: Preset Configuration ====================
|
||||
|
||||
class TestPresetConfiguration:
|
||||
"""
|
||||
Test that preset parameters flow through create_audio_processor correctly.
|
||||
"""
|
||||
|
||||
def test_create_audio_processor_sets_presets(self):
|
||||
"""Presets are set as attributes on the processor."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
processor = create_audio_processor(
|
||||
temp_dir,
|
||||
instrumental_preset="instrumental_clean",
|
||||
karaoke_preset="karaoke",
|
||||
)
|
||||
|
||||
# Verify presets are set on the returned object
|
||||
assert processor.instrumental_preset == "instrumental_clean"
|
||||
assert processor.karaoke_preset == "karaoke"
|
||||
|
||||
def test_create_audio_processor_default_presets(self):
|
||||
"""Default presets are used when not explicitly provided."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
|
||||
from backend.workers.audio_worker import (
|
||||
create_audio_processor,
|
||||
DEFAULT_INSTRUMENTAL_PRESET,
|
||||
DEFAULT_KARAOKE_PRESET,
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
processor = create_audio_processor(temp_dir)
|
||||
|
||||
assert processor.instrumental_preset == DEFAULT_INSTRUMENTAL_PRESET
|
||||
assert processor.karaoke_preset == DEFAULT_KARAOKE_PRESET
|
||||
|
||||
def test_default_other_models_is_empty(self):
|
||||
"""Demucs 6-stem is dropped — DEFAULT_OTHER_MODELS should be empty."""
|
||||
from backend.workers.audio_worker import DEFAULT_OTHER_MODELS
|
||||
assert DEFAULT_OTHER_MODELS == []
|
||||
|
||||
def test_create_audio_processor_with_explicit_models(self):
|
||||
"""Explicit model names still work (legacy per-job override)."""
|
||||
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
|
||||
from backend.workers.audio_worker import create_audio_processor
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
processor = create_audio_processor(
|
||||
temp_dir,
|
||||
clean_instrumental_model="custom_model.ckpt",
|
||||
backing_vocals_models=["custom_bv.ckpt"],
|
||||
)
|
||||
|
||||
call_kwargs = MockProcessor.call_args[1]
|
||||
assert call_kwargs["clean_instrumental_model"] == "custom_model.ckpt"
|
||||
assert call_kwargs["backing_vocals_models"] == ["custom_bv.ckpt"]
|
||||
|
||||
|
||||
# ==================== P0: Custom Output Names Contract ====================
|
||||
|
||||
class TestCustomOutputNames:
|
||||
"""
|
||||
Test that AudioProcessor uses job_id-based custom_output_names
|
||||
and organizes results by known filenames.
|
||||
"""
|
||||
|
||||
def test_job_id_used_as_file_prefix(self):
|
||||
"""When job_id is set, it's used as the filename prefix in custom_output_names."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[], # No stage 2
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None # No stage 2
|
||||
processor.job_id = "abc123"
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
# Create expected output files
|
||||
for name in ["abc123_mixed_vocals.flac", "abc123_mixed_instrumental.flac"]:
|
||||
with open(os.path.join(stems_dir, name), "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [
|
||||
os.path.join(stems_dir, "abc123_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "abc123_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "test.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
result = processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify custom_output_names used job_id prefix
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert call_kwargs["custom_output_names"]["Vocals"] == "abc123_mixed_vocals"
|
||||
assert call_kwargs["custom_output_names"]["Instrumental"] == "abc123_mixed_instrumental"
|
||||
|
||||
# Verify results found by known filenames
|
||||
assert result["clean_instrumental"]["vocals"].endswith("abc123_mixed_vocals.flac")
|
||||
assert "abc123_mixed_instrumental" in result["clean_instrumental"]["instrumental"]
|
||||
|
||||
def test_stage1_results_found_by_known_filenames(self):
|
||||
"""Stage 1 results are located by predictable filenames, not parsed from model names."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None # No stage 2
|
||||
processor.job_id = "job42"
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
# Create the files the API would produce
|
||||
vocals_path = os.path.join(stems_dir, "job42_mixed_vocals.flac")
|
||||
instrumental_path = os.path.join(stems_dir, "job42_mixed_instrumental.flac")
|
||||
with open(vocals_path, "w") as f:
|
||||
f.write("fake vocals")
|
||||
with open(instrumental_path, "w") as f:
|
||||
f.write("fake instrumental")
|
||||
|
||||
mock_client = Mock()
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [vocals_path, instrumental_path],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
# Write a fake input file
|
||||
input_file = os.path.join(temp_dir, "input.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
result = processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Should find vocals and instrumental by known filenames
|
||||
assert result["clean_instrumental"]["vocals"] == vocals_path
|
||||
assert "mixed_instrumental" in result["clean_instrumental"]["instrumental"]
|
||||
|
||||
|
||||
# ==================== P1: Screens Worker Prerequisites ====================
|
||||
|
||||
class TestScreensWorkerPrerequisites:
|
||||
"""
|
||||
Test that screens worker no longer requires audio_complete.
|
||||
"""
|
||||
|
||||
def test_validate_prerequisites_passes_without_audio(self):
|
||||
"""Screens can generate with only lyrics_complete (audio still in progress)."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
|
||||
assert _validate_prerequisites(job) is True
|
||||
|
||||
def test_validate_prerequisites_passes_with_both(self):
|
||||
"""Normal case: both audio and lyrics complete."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
|
||||
assert _validate_prerequisites(job) is True
|
||||
|
||||
def test_validate_prerequisites_fails_without_lyrics(self):
|
||||
"""Missing lyrics_complete should fail."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
def test_validate_prerequisites_fails_with_empty_state(self):
|
||||
"""Empty state_data should fail."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={})
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
def test_validate_prerequisites_fails_without_theme(self):
|
||||
"""Missing theme_id should fail."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True}, theme_id=None)
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
def test_validate_prerequisites_fails_without_artist_title(self):
|
||||
"""Missing artist or title should fail."""
|
||||
from backend.workers.screens_worker import _validate_prerequisites
|
||||
|
||||
job = _make_job(state_data={"lyrics_complete": True}, artist="", title="Test")
|
||||
assert _validate_prerequisites(job) is False
|
||||
|
||||
|
||||
# ==================== GCS URI Passthrough ====================
|
||||
|
||||
class TestGCSURIPassthrough:
|
||||
"""
|
||||
Test that Stage 1 uses gcs_uri when input_gcs_uri is set on the processor.
|
||||
Fixes 413 Request Entity Too Large for large FLAC files.
|
||||
"""
|
||||
|
||||
def test_stage1_uses_gcs_uri_when_set(self):
|
||||
"""When input_gcs_uri is set, Stage 1 passes gcs_uri instead of file_path."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None
|
||||
processor.job_id = "gcs-test-001"
|
||||
processor.input_gcs_uri = "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
for name in ["gcs-test-001_mixed_vocals.flac", "gcs-test-001_mixed_instrumental.flac"]:
|
||||
with open(os.path.join(stems_dir, name), "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [
|
||||
os.path.join(stems_dir, "gcs-test-001_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "gcs-test-001_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "song.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify gcs_uri was passed instead of file_path
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert call_kwargs["gcs_uri"] == "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
|
||||
# Verify file_path was NOT passed as a positional arg
|
||||
call_args = mock_client.separate_audio_and_wait.call_args[0]
|
||||
assert len(call_args) == 0
|
||||
|
||||
def test_stage1_uses_file_upload_when_no_gcs_uri(self):
|
||||
"""When input_gcs_uri is not set, Stage 1 uses file upload as before."""
|
||||
from karaoke_gen.audio_processor import AudioProcessor
|
||||
import logging
|
||||
|
||||
processor = AudioProcessor(
|
||||
logger=logging.getLogger("test"),
|
||||
log_level=logging.INFO,
|
||||
log_formatter=None,
|
||||
model_file_dir=None,
|
||||
lossless_output_format="FLAC",
|
||||
clean_instrumental_model="test.ckpt",
|
||||
backing_vocals_models=[],
|
||||
other_stems_models=[],
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
)
|
||||
processor.instrumental_preset = "instrumental_clean"
|
||||
processor.karaoke_preset = None
|
||||
processor.job_id = "file-test-001"
|
||||
# No input_gcs_uri set
|
||||
|
||||
mock_client = Mock()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
stems_dir = os.path.join(temp_dir, "stems")
|
||||
os.makedirs(stems_dir)
|
||||
|
||||
for name in ["file-test-001_mixed_vocals.flac", "file-test-001_mixed_instrumental.flac"]:
|
||||
with open(os.path.join(stems_dir, name), "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
mock_client.separate_audio_and_wait.return_value = {
|
||||
"status": "completed",
|
||||
"downloaded_files": [
|
||||
os.path.join(stems_dir, "file-test-001_mixed_vocals.flac"),
|
||||
os.path.join(stems_dir, "file-test-001_mixed_instrumental.flac"),
|
||||
],
|
||||
"files": {},
|
||||
}
|
||||
|
||||
input_file = os.path.join(temp_dir, "song.flac")
|
||||
with open(input_file, "w") as f:
|
||||
f.write("fake input")
|
||||
|
||||
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
|
||||
with patch.object(processor, '_normalize_audio_files'):
|
||||
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
|
||||
processor._process_audio_separation_remote(
|
||||
input_file, "Test - Song", temp_dir, "http://fake-api",
|
||||
)
|
||||
|
||||
# Verify file_path was passed as positional arg (old behavior)
|
||||
call_args = mock_client.separate_audio_and_wait.call_args[0]
|
||||
assert call_args[0] == input_file
|
||||
# Verify gcs_uri was NOT in kwargs
|
||||
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
|
||||
assert "gcs_uri" not in call_kwargs
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,781 @@
|
||||
"""
|
||||
Tests for processing_metadata field and related functionality.
|
||||
|
||||
Covers:
|
||||
- Job model has processing_metadata field
|
||||
- processing_metadata is in SUMMARY_FIELD_PATHS (regression test)
|
||||
- update_processing_metadata helper works correctly
|
||||
- AudioShake transcriber stores asset_id in metadata
|
||||
- Corrector passes through transcription metadata
|
||||
- extract_request_metadata includes auth context when provided
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from datetime import datetime
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
class TestProcessingMetadataField:
|
||||
"""Test the processing_metadata field on the Job model."""
|
||||
|
||||
def test_job_has_processing_metadata_field(self):
|
||||
"""processing_metadata should exist and default to empty dict."""
|
||||
job = Job(
|
||||
job_id="test-123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
assert hasattr(job, 'processing_metadata')
|
||||
assert job.processing_metadata == {}
|
||||
|
||||
def test_processing_metadata_serializes(self):
|
||||
"""processing_metadata should serialize to JSON correctly."""
|
||||
job = Job(
|
||||
job_id="test-123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
processing_metadata={
|
||||
"transcription": {
|
||||
"provider": "audioshake",
|
||||
"audioshake_task_id": "task-abc",
|
||||
"audioshake_asset_id": "asset-xyz",
|
||||
},
|
||||
},
|
||||
)
|
||||
data = job.model_dump(mode='json')
|
||||
assert data['processing_metadata']['transcription']['audioshake_task_id'] == "task-abc"
|
||||
assert data['processing_metadata']['transcription']['audioshake_asset_id'] == "asset-xyz"
|
||||
|
||||
def test_processing_metadata_deserializes(self):
|
||||
"""processing_metadata should deserialize from dict correctly."""
|
||||
data = {
|
||||
"job_id": "test-123",
|
||||
"status": "pending",
|
||||
"created_at": datetime.utcnow(),
|
||||
"updated_at": datetime.utcnow(),
|
||||
"processing_metadata": {
|
||||
"separation": {
|
||||
"provider": "modal",
|
||||
"duration_seconds": 420.5,
|
||||
},
|
||||
},
|
||||
}
|
||||
job = Job(**data)
|
||||
assert job.processing_metadata["separation"]["provider"] == "modal"
|
||||
assert job.processing_metadata["separation"]["duration_seconds"] == 420.5
|
||||
|
||||
|
||||
class TestSummaryFieldPaths:
|
||||
"""Regression tests for SUMMARY_FIELD_PATHS."""
|
||||
|
||||
def test_processing_metadata_in_summary_field_paths(self):
|
||||
"""processing_metadata must be in SUMMARY_FIELD_PATHS for dashboard queries."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
assert 'processing_metadata' in FirestoreService.SUMMARY_FIELD_PATHS
|
||||
|
||||
|
||||
class TestUpdateProcessingMetadata:
|
||||
"""Test the JobManager.update_processing_metadata helper."""
|
||||
|
||||
@patch('backend.services.job_manager.FirestoreService')
|
||||
@patch('backend.services.job_manager.StorageService')
|
||||
def test_update_processing_metadata_uses_dot_notation(self, mock_storage_cls, mock_firestore_cls):
|
||||
"""update_processing_metadata should use Firestore dot-notation for nested updates."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore_cls.return_value = mock_firestore
|
||||
|
||||
jm = JobManager()
|
||||
jm.update_processing_metadata("job-123", "transcription", {
|
||||
"provider": "audioshake",
|
||||
"audioshake_task_id": "task-abc",
|
||||
})
|
||||
|
||||
# Should call update_job with dot-notation key
|
||||
mock_firestore.update_job.assert_called_once()
|
||||
call_args = mock_firestore.update_job.call_args
|
||||
assert call_args[0][0] == "job-123"
|
||||
updates = call_args[0][1]
|
||||
assert "processing_metadata.transcription" in updates
|
||||
assert updates["processing_metadata.transcription"]["provider"] == "audioshake"
|
||||
|
||||
@patch('backend.services.job_manager.FirestoreService')
|
||||
@patch('backend.services.job_manager.StorageService')
|
||||
def test_update_processing_metadata_deep_dot_notation(self, mock_storage_cls, mock_firestore_cls):
|
||||
"""Deeper dot-notation paths (e.g. timing.worker_seconds) avoid overwriting sibling fields."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore_cls.return_value = mock_firestore
|
||||
|
||||
jm = JobManager()
|
||||
jm.update_processing_metadata("job-123", "timing.lyrics_worker_seconds", 42.5)
|
||||
|
||||
call_args = mock_firestore.update_job.call_args
|
||||
updates = call_args[0][1]
|
||||
assert "processing_metadata.timing.lyrics_worker_seconds" in updates
|
||||
assert updates["processing_metadata.timing.lyrics_worker_seconds"] == 42.5
|
||||
|
||||
@patch('backend.services.job_manager.FirestoreService')
|
||||
@patch('backend.services.job_manager.StorageService')
|
||||
def test_update_processing_metadata_swallows_errors(self, mock_storage_cls, mock_firestore_cls):
|
||||
"""update_processing_metadata should not raise on failure."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.update_job.side_effect = Exception("Firestore error")
|
||||
mock_firestore_cls.return_value = mock_firestore
|
||||
|
||||
jm = JobManager()
|
||||
# Should not raise
|
||||
jm.update_processing_metadata("job-123", "timing", {"foo": 1})
|
||||
|
||||
|
||||
class TestAudioShakeAssetId:
|
||||
"""Test that AudioShake transcriber stores asset_id in metadata."""
|
||||
|
||||
def test_convert_result_format_includes_asset_id(self):
|
||||
"""_convert_result_format should include asset_id from task_data.assetId."""
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
|
||||
|
||||
# Create a minimal transcriber instance
|
||||
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
|
||||
transcriber.logger = MagicMock()
|
||||
transcriber._last_asset_id = "fallback-asset-id"
|
||||
|
||||
raw_data = {
|
||||
"task_data": {
|
||||
"id": "task-123",
|
||||
"assetId": "asset-456",
|
||||
"duration": 120.5,
|
||||
"targets": [],
|
||||
},
|
||||
"transcription": {
|
||||
"text": "hello world",
|
||||
"lines": [
|
||||
{
|
||||
"text": "hello world",
|
||||
"words": [
|
||||
{"text": "hello", "start": 0.0, "end": 0.5},
|
||||
{"text": "world", "start": 0.6, "end": 1.0},
|
||||
],
|
||||
}
|
||||
],
|
||||
"metadata": {"language": "en"},
|
||||
},
|
||||
}
|
||||
|
||||
result = transcriber._convert_result_format(raw_data)
|
||||
assert result.metadata["task_id"] == "task-123"
|
||||
assert result.metadata["asset_id"] == "asset-456"
|
||||
assert result.metadata["language"] == "en"
|
||||
|
||||
def test_convert_result_format_fallback_asset_id(self):
|
||||
"""asset_id should fall back to _last_asset_id if not in task_data."""
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
|
||||
|
||||
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
|
||||
transcriber.logger = MagicMock()
|
||||
transcriber._last_asset_id = "fallback-asset-id"
|
||||
|
||||
raw_data = {
|
||||
"task_data": {
|
||||
"id": "task-123",
|
||||
# No assetId in task_data
|
||||
"targets": [],
|
||||
},
|
||||
"transcription": {
|
||||
"text": "hello",
|
||||
"lines": [
|
||||
{
|
||||
"text": "hello",
|
||||
"words": [{"text": "hello", "start": 0.0, "end": 0.5}],
|
||||
}
|
||||
],
|
||||
"metadata": {},
|
||||
},
|
||||
}
|
||||
|
||||
result = transcriber._convert_result_format(raw_data)
|
||||
assert result.metadata["asset_id"] == "fallback-asset-id"
|
||||
|
||||
|
||||
class TestCorrectorMetadataPassthrough:
|
||||
"""Test that corrector passes through transcription metadata."""
|
||||
|
||||
def test_correction_result_includes_transcription_metadata(self):
|
||||
"""CorrectionResult.metadata should include transcription_metadata from primary transcription."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
|
||||
from karaoke_gen.lyrics_transcriber.types import (
|
||||
TranscriptionResult, TranscriptionData, LyricsSegment, Word
|
||||
)
|
||||
|
||||
# Create a minimal corrector
|
||||
corrector = LyricsCorrector(cache_dir="/tmp", enabled_handlers=[])
|
||||
|
||||
# Create transcription result with metadata
|
||||
word = Word(id="w1", text="hello", start_time=0.0, end_time=0.5)
|
||||
segment = LyricsSegment(id="s1", text="hello", words=[word], start_time=0.0, end_time=0.5)
|
||||
transcription_data = TranscriptionData(
|
||||
text="hello",
|
||||
words=[word],
|
||||
segments=[segment],
|
||||
source="AudioShake",
|
||||
metadata={
|
||||
"task_id": "task-123",
|
||||
"asset_id": "asset-456",
|
||||
"language": "en",
|
||||
},
|
||||
)
|
||||
transcription_result = TranscriptionResult(
|
||||
name="AudioShake",
|
||||
priority=1,
|
||||
result=transcription_data,
|
||||
)
|
||||
|
||||
# Run corrector with no reference lyrics (will skip correction but still build result)
|
||||
result = corrector.run(
|
||||
transcription_results=[transcription_result],
|
||||
lyrics_results={},
|
||||
)
|
||||
|
||||
# Check that transcription_metadata is passed through
|
||||
assert "transcription_metadata" in result.metadata
|
||||
assert result.metadata["transcription_metadata"]["task_id"] == "task-123"
|
||||
assert result.metadata["transcription_metadata"]["asset_id"] == "asset-456"
|
||||
|
||||
|
||||
class TestExtractRequestMetadataAuthContext:
|
||||
"""Test that extract_request_metadata includes auth context."""
|
||||
|
||||
def _make_request(self):
|
||||
"""Create a minimal mock request."""
|
||||
request = MagicMock()
|
||||
request.headers = {
|
||||
"user-agent": "test-agent",
|
||||
"x-forwarded-for": "1.2.3.4",
|
||||
}
|
||||
request.client = MagicMock()
|
||||
request.client.host = "127.0.0.1"
|
||||
return request
|
||||
|
||||
def test_auth_context_included_when_provided(self):
|
||||
"""Auth context should be in metadata when auth_result is provided."""
|
||||
from backend.api.routes.file_upload import extract_request_metadata
|
||||
|
||||
auth_result = MagicMock()
|
||||
auth_result.auth_method = "session"
|
||||
auth_result.user_type = MagicMock()
|
||||
auth_result.user_type.value = "unlimited"
|
||||
auth_result.remaining_uses = 42
|
||||
|
||||
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
|
||||
assert metadata['auth_method'] == "session"
|
||||
assert metadata['user_type'] == "unlimited"
|
||||
assert metadata['credits_at_creation'] == 42
|
||||
|
||||
def test_no_auth_context_without_auth_result(self):
|
||||
"""No auth context should be added when auth_result is None."""
|
||||
from backend.api.routes.file_upload import extract_request_metadata
|
||||
|
||||
metadata = extract_request_metadata(self._make_request())
|
||||
assert 'auth_method' not in metadata
|
||||
assert 'user_type' not in metadata
|
||||
assert 'credits_at_creation' not in metadata
|
||||
|
||||
def test_audio_search_extract_includes_auth(self):
|
||||
"""audio_search extract_request_metadata should also support auth_result."""
|
||||
from backend.api.routes.audio_search import extract_request_metadata
|
||||
|
||||
auth_result = MagicMock()
|
||||
auth_result.auth_method = "api_key"
|
||||
auth_result.user_type = MagicMock()
|
||||
auth_result.user_type.value = "limited"
|
||||
auth_result.remaining_uses = 5
|
||||
|
||||
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
|
||||
assert metadata['auth_method'] == "api_key"
|
||||
assert metadata['user_type'] == "limited"
|
||||
assert metadata['credits_at_creation'] == 5
|
||||
|
||||
def test_auth_without_remaining_uses(self):
|
||||
"""Should handle auth_result with no remaining_uses (e.g., admin)."""
|
||||
from backend.api.routes.file_upload import extract_request_metadata
|
||||
|
||||
auth_result = MagicMock(spec=['auth_method', 'user_type'])
|
||||
auth_result.auth_method = "admin_token"
|
||||
auth_result.user_type = MagicMock()
|
||||
auth_result.user_type.value = "admin"
|
||||
|
||||
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
|
||||
assert metadata['auth_method'] == "admin_token"
|
||||
assert metadata['user_type'] == "admin"
|
||||
assert 'credits_at_creation' not in metadata
|
||||
|
||||
def test_auth_with_none_user_type(self):
|
||||
"""Should handle auth_result where user_type is None."""
|
||||
from backend.api.routes.file_upload import extract_request_metadata
|
||||
|
||||
auth_result = MagicMock()
|
||||
auth_result.auth_method = "session"
|
||||
auth_result.user_type = None
|
||||
auth_result.remaining_uses = 10
|
||||
|
||||
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
|
||||
assert metadata['auth_method'] == "session"
|
||||
assert metadata['user_type'] is None
|
||||
assert metadata['credits_at_creation'] == 10
|
||||
|
||||
|
||||
class TestStoreLyricsProcessingMetadata:
|
||||
"""Test the _store_lyrics_processing_metadata helper function."""
|
||||
|
||||
def test_extracts_audioshake_ids_from_corrections(self, tmp_path):
|
||||
"""Should extract task_id and asset_id from corrections.json metadata."""
|
||||
import json
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
# Create a mock corrections file
|
||||
lyrics_dir = tmp_path / "lyrics"
|
||||
lyrics_dir.mkdir()
|
||||
corrections_file = lyrics_dir / "Artist - Title (Lyrics Corrections).json"
|
||||
corrections_data = {
|
||||
"metadata": {
|
||||
"transcription_metadata": {
|
||||
"task_id": "task-abc",
|
||||
"asset_id": "asset-xyz",
|
||||
"language": "en",
|
||||
},
|
||||
"enabled_handlers": ["anchor_sequence", "gap_word_count"],
|
||||
"correction_ratio": 0.95,
|
||||
"total_words": 100,
|
||||
"agentic_routing": "rule-based",
|
||||
"anchor_sequences_count": 5,
|
||||
"gap_sequences_count": 3,
|
||||
},
|
||||
"corrections_made": 5,
|
||||
"corrected_segments": [
|
||||
{"words": [{"text": "w1"}, {"text": "w2"}]},
|
||||
{"words": [{"text": "w3"}]},
|
||||
],
|
||||
"reference_lyrics": {"genius": {}, "spotify": {}},
|
||||
}
|
||||
corrections_file.write_text(json.dumps(corrections_data))
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={"lyrics_dir": str(lyrics_dir)},
|
||||
transcription_duration=45.6,
|
||||
cache_stats={"downloaded": 2, "not_found": 1},
|
||||
job_log=job_log,
|
||||
)
|
||||
|
||||
# Check transcription metadata was stored
|
||||
transcription_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "transcription"
|
||||
]
|
||||
assert len(transcription_call) == 1
|
||||
trans_data = transcription_call[0][0][2]
|
||||
assert trans_data["provider"] == "audioshake"
|
||||
assert trans_data["audioshake_task_id"] == "task-abc"
|
||||
assert trans_data["audioshake_asset_id"] == "asset-xyz"
|
||||
assert trans_data["segment_count"] == 2
|
||||
assert trans_data["word_count"] == 3
|
||||
assert trans_data["duration_seconds"] == 45.6
|
||||
|
||||
# Check correction metadata was stored
|
||||
correction_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "correction"
|
||||
]
|
||||
assert len(correction_call) == 1
|
||||
corr_data = correction_call[0][0][2]
|
||||
assert corr_data["corrections_made"] == 5
|
||||
assert corr_data["handlers_applied"] == ["anchor_sequence", "gap_word_count"]
|
||||
assert corr_data["reference_sources_found"] == ["genius", "spotify"]
|
||||
|
||||
# Check cache stats were stored
|
||||
cache_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "cache"
|
||||
]
|
||||
assert len(cache_call) == 1
|
||||
cache_data = cache_call[0][0][2]
|
||||
assert cache_data["transcription_cache_downloaded"] == 2
|
||||
assert cache_data["transcription_cache_not_found"] == 1
|
||||
|
||||
def test_handles_missing_corrections_file(self):
|
||||
"""Should not raise when corrections file is not found."""
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={"lyrics_dir": "/nonexistent/path"},
|
||||
transcription_duration=30.0,
|
||||
cache_stats=None,
|
||||
job_log=job_log,
|
||||
)
|
||||
|
||||
# Should still store duration even without corrections file
|
||||
transcription_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "transcription"
|
||||
]
|
||||
assert len(transcription_call) == 1
|
||||
assert transcription_call[0][0][2]["duration_seconds"] == 30.0
|
||||
|
||||
def test_swallows_exceptions(self):
|
||||
"""Should not raise on unexpected errors."""
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.update_processing_metadata.side_effect = Exception("boom")
|
||||
job_log = MagicMock()
|
||||
|
||||
# Should not raise
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={"lyrics_dir": ""},
|
||||
transcription_duration=10.0,
|
||||
cache_stats=None,
|
||||
job_log=job_log,
|
||||
)
|
||||
job_log.warning.assert_called()
|
||||
|
||||
def test_no_audioshake_ids_when_lyrics_dir_missing(self):
|
||||
"""Without lyrics_dir, corrections.json can't be found — only duration is stored.
|
||||
|
||||
This is the exact bug that shipped in v0.142.0: transcribe_lyrics() didn't
|
||||
include lyrics_dir in its return dict, so _store_lyrics_processing_metadata
|
||||
could never find the corrections file and AudioShake IDs were silently lost.
|
||||
"""
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
# Simulate the pre-fix result dict — no lyrics_dir key at all
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={"lrc_filepath": "/tmp/output.lrc"}, # no lyrics_dir!
|
||||
transcription_duration=45.0,
|
||||
cache_stats=None,
|
||||
job_log=job_log,
|
||||
)
|
||||
|
||||
# Only duration should be stored — no AudioShake IDs, no correction stats
|
||||
transcription_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "transcription"
|
||||
]
|
||||
assert len(transcription_call) == 1
|
||||
trans_data = transcription_call[0][0][2]
|
||||
assert trans_data["duration_seconds"] == 45.0
|
||||
assert "audioshake_task_id" not in trans_data
|
||||
assert "provider" not in trans_data
|
||||
|
||||
# No correction metadata should be stored
|
||||
correction_calls = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "correction"
|
||||
]
|
||||
assert len(correction_calls) == 0
|
||||
|
||||
|
||||
class TestTranscribeLyricsReturnsLyricsDir:
|
||||
"""Contract test: transcribe_lyrics() must include lyrics_dir in its return dict.
|
||||
|
||||
This is the test that would have caught the v0.142.0 bug. The previous test suite
|
||||
only tested _store_lyrics_processing_metadata in isolation with a hand-crafted input
|
||||
that included lyrics_dir — it never verified the actual caller provides that key.
|
||||
|
||||
Testing lesson: When function A calls function B, don't just test B with ideal inputs.
|
||||
Also verify A actually produces those inputs. Test the contract between caller and callee.
|
||||
"""
|
||||
|
||||
@patch('karaoke_gen.lyrics_processor.LyricsTranscriber')
|
||||
@patch('karaoke_gen.lyrics_processor.load_dotenv')
|
||||
def test_transcribe_lyrics_returns_lyrics_dir(self, mock_dotenv, mock_transcriber_cls, tmp_path):
|
||||
"""transcribe_lyrics() result must contain lyrics_dir pointing to the lyrics subdirectory."""
|
||||
from karaoke_gen.lyrics_processor import LyricsProcessor
|
||||
|
||||
# Set up mock transcriber result
|
||||
mock_results = MagicMock()
|
||||
mock_results.lrc_filepath = str(tmp_path / "lyrics" / "output.lrc")
|
||||
mock_results.ass_filepath = str(tmp_path / "lyrics" / "output.ass")
|
||||
mock_results.video_filepath = str(tmp_path / "lyrics" / "output.mkv")
|
||||
mock_results.transcription_corrected = None # skip correction output
|
||||
mock_results.countdown_padding_added = False
|
||||
mock_results.countdown_padding_seconds = 0.0
|
||||
mock_results.padded_audio_filepath = None
|
||||
|
||||
mock_transcriber_cls.return_value.process.return_value = mock_results
|
||||
|
||||
# Create necessary dirs and a dummy audio file
|
||||
lyrics_dir = tmp_path / "lyrics"
|
||||
lyrics_dir.mkdir(exist_ok=True)
|
||||
(tmp_path / "lyrics" / "output.lrc").write_text("[00:00.00] test")
|
||||
(tmp_path / "lyrics" / "output.mkv").write_bytes(b"fake")
|
||||
lrc_dest = tmp_path / "Artist - Title (Karaoke).lrc"
|
||||
mkv_dest = tmp_path / "Artist - Title (With Vocals).mkv"
|
||||
|
||||
processor = LyricsProcessor.__new__(LyricsProcessor)
|
||||
processor.logger = MagicMock()
|
||||
processor.lyrics_file = None
|
||||
processor.render_video = False
|
||||
processor.skip_transcription = False
|
||||
processor.skip_transcription_review = True
|
||||
processor.style_params_json = None
|
||||
processor.subtitle_offset_ms = 0
|
||||
|
||||
with patch.dict('os.environ', {
|
||||
'AUDIOSHAKE_API_TOKEN': 'fake-token',
|
||||
}):
|
||||
result = processor.transcribe_lyrics(
|
||||
input_audio_wav=str(tmp_path / "audio.wav"),
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
track_output_dir=str(tmp_path),
|
||||
)
|
||||
|
||||
# THE KEY ASSERTION: lyrics_dir must be in the result
|
||||
assert "lyrics_dir" in result, (
|
||||
"transcribe_lyrics() must return lyrics_dir so _store_lyrics_processing_metadata "
|
||||
"can find corrections.json. This was the v0.142.0 bug."
|
||||
)
|
||||
assert result["lyrics_dir"] == str(tmp_path / "lyrics")
|
||||
|
||||
def test_lyrics_dir_matches_corrections_file_location(self, tmp_path):
|
||||
"""The lyrics_dir returned by transcribe_lyrics must be where corrections.json lives.
|
||||
|
||||
This verifies the contract: _store_lyrics_processing_metadata looks for corrections
|
||||
files in result['lyrics_dir'], and transcribe_lyrics writes them to {track_output_dir}/lyrics.
|
||||
"""
|
||||
import json
|
||||
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
|
||||
|
||||
# Simulate a result dict with lyrics_dir set correctly
|
||||
lyrics_dir = tmp_path / "lyrics"
|
||||
lyrics_dir.mkdir()
|
||||
|
||||
# Write a corrections file in the same location transcribe_lyrics would
|
||||
corrections_file = lyrics_dir / "Artist - Title (Lyrics Corrections).json"
|
||||
corrections_file.write_text(json.dumps({
|
||||
"metadata": {
|
||||
"transcription_metadata": {"task_id": "t1", "asset_id": "a1"},
|
||||
"enabled_handlers": [],
|
||||
},
|
||||
"corrections_made": 0,
|
||||
"corrected_segments": [],
|
||||
}))
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
# Use the result dict shape that transcribe_lyrics now produces
|
||||
_store_lyrics_processing_metadata(
|
||||
job_manager=job_manager,
|
||||
job_id="test-job",
|
||||
transcription_result={
|
||||
"lyrics_dir": str(lyrics_dir),
|
||||
"lrc_filepath": str(tmp_path / "output.lrc"),
|
||||
},
|
||||
transcription_duration=30.0,
|
||||
cache_stats=None,
|
||||
job_log=job_log,
|
||||
)
|
||||
|
||||
# AudioShake IDs should be extracted successfully
|
||||
transcription_call = [
|
||||
c for c in job_manager.update_processing_metadata.call_args_list
|
||||
if c[0][1] == "transcription"
|
||||
]
|
||||
assert len(transcription_call) == 1
|
||||
trans_data = transcription_call[0][0][2]
|
||||
assert trans_data["provider"] == "audioshake"
|
||||
assert trans_data["audioshake_task_id"] == "t1"
|
||||
assert trans_data["audioshake_asset_id"] == "a1"
|
||||
|
||||
|
||||
class TestStoreAudioSourceMetadata:
|
||||
"""Test the _store_audio_source_metadata helper function."""
|
||||
|
||||
@patch('subprocess.run')
|
||||
def test_parses_ffprobe_output(self, mock_run):
|
||||
"""Should parse ffprobe JSON output and store audio properties."""
|
||||
import json
|
||||
from backend.workers.audio_worker import _store_audio_source_metadata
|
||||
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=0,
|
||||
stdout=json.dumps({
|
||||
"format": {
|
||||
"format_name": "flac",
|
||||
"duration": "210.4",
|
||||
"size": "26541900",
|
||||
"bit_rate": "1008000",
|
||||
},
|
||||
"streams": [
|
||||
{
|
||||
"codec_type": "audio",
|
||||
"codec_name": "flac",
|
||||
"sample_rate": "44100",
|
||||
"channels": 2,
|
||||
"bits_per_raw_sample": "16",
|
||||
}
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_audio_source_metadata(job_manager, "job-123", "/fake/audio.flac", job_log)
|
||||
|
||||
job_manager.update_processing_metadata.assert_called_once()
|
||||
call_args = job_manager.update_processing_metadata.call_args
|
||||
assert call_args[0][1] == "audio_source"
|
||||
data = call_args[0][2]
|
||||
assert data["input_format"] == "flac"
|
||||
assert data["input_codec"] == "flac"
|
||||
assert data["input_sample_rate"] == 44100
|
||||
assert data["input_channels"] == 2
|
||||
assert data["input_bit_depth"] == 16
|
||||
assert data["input_duration_seconds"] == 210.4
|
||||
assert data["input_file_size_bytes"] == 26541900
|
||||
assert data["input_bitrate_kbps"] == 1008
|
||||
|
||||
@patch('subprocess.run')
|
||||
def test_handles_ffprobe_failure(self, mock_run):
|
||||
"""Should not raise when ffprobe fails."""
|
||||
from backend.workers.audio_worker import _store_audio_source_metadata
|
||||
|
||||
mock_run.return_value = MagicMock(returncode=1, stderr="No such file")
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_audio_source_metadata(job_manager, "job-123", "/bad/path", job_log)
|
||||
job_manager.update_processing_metadata.assert_not_called()
|
||||
job_log.warning.assert_called()
|
||||
|
||||
@patch('subprocess.run')
|
||||
def test_handles_missing_audio_stream(self, mock_run):
|
||||
"""Should handle files with no audio stream gracefully."""
|
||||
import json
|
||||
from backend.workers.audio_worker import _store_audio_source_metadata
|
||||
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=0,
|
||||
stdout=json.dumps({
|
||||
"format": {"format_name": "mp4", "duration": "30.0", "size": "1000"},
|
||||
"streams": [{"codec_type": "video", "codec_name": "h264"}],
|
||||
}),
|
||||
)
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_log = MagicMock()
|
||||
|
||||
_store_audio_source_metadata(job_manager, "job-123", "/fake/video.mp4", job_log)
|
||||
job_manager.update_processing_metadata.assert_called_once()
|
||||
data = job_manager.update_processing_metadata.call_args[0][2]
|
||||
# Should have format-level data but no audio stream data
|
||||
assert data["input_format"] == "mp4"
|
||||
assert "input_codec" not in data
|
||||
|
||||
|
||||
class TestStoreVideoProcessingMetadata:
|
||||
"""Test the _store_video_processing_metadata helper function."""
|
||||
|
||||
def test_stores_encoding_and_distribution_metadata(self, tmp_path):
|
||||
"""Should store encoding time, formats, and distribution info."""
|
||||
from backend.workers.video_worker import _store_video_processing_metadata
|
||||
|
||||
# Create mock result with some files existing
|
||||
result = MagicMock()
|
||||
result.encoding_time_seconds = 180.5
|
||||
result.youtube_url = "https://youtube.com/watch?v=abc"
|
||||
result.youtube_upload_queued = False
|
||||
result.dropbox_link = "https://dropbox.com/s/xxx"
|
||||
result.gdrive_files = {"4k": "file-id-1"}
|
||||
result.brand_code = "NOMAD0001"
|
||||
|
||||
# Create a temp file to simulate output
|
||||
lossless = tmp_path / "output.mp4"
|
||||
lossless.write_bytes(b"x" * 1000)
|
||||
result.final_video = str(lossless)
|
||||
result.final_video_mkv = None
|
||||
result.final_video_lossy = None
|
||||
result.final_video_720p = None
|
||||
|
||||
job_manager = MagicMock()
|
||||
|
||||
_store_video_processing_metadata(job_manager, "job-123", result, 300.0)
|
||||
|
||||
calls = {c[0][1]: c[0][2] for c in job_manager.update_processing_metadata.call_args_list}
|
||||
|
||||
# Check encoding
|
||||
assert "encoding" in calls
|
||||
assert calls["encoding"]["encoding_time_seconds"] == 180.5
|
||||
assert "lossless_4k_mp4" in calls["encoding"]["output_formats"]
|
||||
assert calls["encoding"]["output_sizes_bytes"]["lossless_4k_mp4"] == 1000
|
||||
|
||||
# Check distribution
|
||||
assert "distribution" in calls
|
||||
assert calls["distribution"]["youtube_video_url"] == "https://youtube.com/watch?v=abc"
|
||||
assert calls["distribution"]["brand_code"] == "NOMAD0001"
|
||||
assert calls["distribution"]["gdrive_file_count"] == 1
|
||||
|
||||
# Check timing (uses deep dot-notation to avoid overwriting other workers' timing)
|
||||
assert "timing.video_worker_seconds" in calls
|
||||
assert calls["timing.video_worker_seconds"] == 300.0
|
||||
|
||||
def test_swallows_exceptions(self):
|
||||
"""Should not raise on errors."""
|
||||
from backend.workers.video_worker import _store_video_processing_metadata
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.update_processing_metadata.side_effect = Exception("boom")
|
||||
result = MagicMock()
|
||||
result.encoding_time_seconds = None
|
||||
|
||||
# Should not raise
|
||||
_store_video_processing_metadata(job_manager, "job-123", result, 100.0)
|
||||
|
||||
|
||||
class TestAudioShakeStartTranscriptionAssetId:
|
||||
"""Test that start_transcription stores _last_asset_id."""
|
||||
|
||||
def test_start_transcription_stores_last_asset_id(self):
|
||||
"""start_transcription should store _last_asset_id for metadata fallback."""
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
|
||||
|
||||
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
|
||||
transcriber.logger = MagicMock()
|
||||
|
||||
# Mock the API and upload optimizer
|
||||
transcriber.api = MagicMock()
|
||||
transcriber.api.upload_file.return_value = "asset-from-upload"
|
||||
transcriber.api.create_task.return_value = "task-from-create"
|
||||
transcriber.upload_optimizer = MagicMock()
|
||||
transcriber.upload_optimizer.prepare_for_upload.return_value = ("/fake/path", None)
|
||||
|
||||
task_id = transcriber.start_transcription("/fake/audio.flac")
|
||||
|
||||
assert task_id == "task-from-create"
|
||||
assert transcriber._last_asset_id == "asset-from-upload"
|
||||
@@ -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"] == []
|
||||
@@ -224,7 +224,38 @@ class TestRetryEndpoint:
|
||||
assert has_video and has_instrumental_selection
|
||||
|
||||
def test_retry_checkpoint_detection_render_stage(self):
|
||||
"""Test retry detects render stage checkpoint."""
|
||||
"""Test retry detects render stage checkpoint when review was completed."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
file_urls={
|
||||
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
|
||||
'screens': {'title': 'gs://bucket/path/title.mov'}
|
||||
},
|
||||
state_data={
|
||||
'instrumental_selection': 'clean'
|
||||
}
|
||||
)
|
||||
|
||||
# This job has corrections, screens, AND completed review - should retry from render
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
has_screens = job.file_urls.get('screens', {}).get('title')
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
has_review = (job.state_data or {}).get('instrumental_selection')
|
||||
assert has_corrections and has_screens and not has_video and has_review
|
||||
|
||||
def test_retry_checkpoint_returns_to_review_when_not_completed(self):
|
||||
"""Test retry returns to awaiting_review when corrections and screens exist
|
||||
but user never completed the review (no instrumental_selection).
|
||||
|
||||
Regression test: previously, retry would skip to REVIEW_COMPLETE based solely
|
||||
on corrections.json + title.mov existing, but these are auto-generated artifacts
|
||||
that exist BEFORE the user reviews anything.
|
||||
"""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
@@ -236,13 +267,15 @@ class TestRetryEndpoint:
|
||||
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
|
||||
'screens': {'title': 'gs://bucket/path/title.mov'}
|
||||
}
|
||||
# No state_data.instrumental_selection — review was never completed
|
||||
)
|
||||
|
||||
# This job has corrections and screens - should retry from render
|
||||
# Has corrections and screens but NO review completion
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
has_screens = job.file_urls.get('screens', {}).get('title')
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
assert has_corrections and has_screens and not has_video
|
||||
has_review = (job.state_data or {}).get('instrumental_selection')
|
||||
# Should match the "awaiting_review" checkpoint, NOT "render"
|
||||
assert has_corrections and has_screens and not has_review
|
||||
|
||||
def test_retry_checkpoint_detection_from_beginning(self):
|
||||
"""Test retry detects need to restart from beginning."""
|
||||
@@ -382,6 +415,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
|
||||
@@ -425,6 +479,20 @@ class TestSummaryEndpoint:
|
||||
assert _prune_state_data({}) == {}
|
||||
assert _prune_state_data({'state_data': None}) == {'state_data': None}
|
||||
|
||||
def test_summary_projection_includes_source_fields(self):
|
||||
"""Verify SUMMARY_FIELD_PATHS includes audio source tracking fields.
|
||||
|
||||
These fields are required for the Source column in the admin dashboard
|
||||
and the source details modal. Without them, the dashboard incorrectly
|
||||
shows audio search jobs as file uploads when audio_search_artist/title
|
||||
are null.
|
||||
"""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
paths = FirestoreService.SUMMARY_FIELD_PATHS
|
||||
for field in ['url', 'filename', 'audio_search_artist', 'audio_search_title',
|
||||
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url']:
|
||||
assert field in paths, f"{field} must be in summary projection for source details modal"
|
||||
|
||||
def test_prune_file_urls_keeps_allowed_keys(self):
|
||||
"""Verify _prune_file_urls keeps only dashboard-required keys."""
|
||||
from backend.api.routes.jobs import _prune_file_urls
|
||||
@@ -603,3 +671,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"
|
||||
|
||||
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user