mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 17:21:26 +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.
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/bin/bash
|
||||
# Auto-translate when English translation files change.
|
||||
# Uses GCS cache so this is near-instant for small changes.
|
||||
# Skip with: git commit --no-verify
|
||||
|
||||
set -e
|
||||
|
||||
STAGED_EN=$(git diff --cached --name-only --diff-filter=ACM | grep -E '(messages|translations)/en\.json$' || true)
|
||||
|
||||
if [ -z "$STAGED_EN" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "i18n: English translations changed — running translation pipeline..."
|
||||
|
||||
for en_file in $STAGED_EN; do
|
||||
dir=$(dirname "$en_file")
|
||||
|
||||
if [[ "$dir" == frontend/messages ]]; then
|
||||
script="frontend/scripts/translate.py"
|
||||
elif [[ "$dir" == backend/translations ]]; then
|
||||
script="frontend/scripts/translate.py"
|
||||
else
|
||||
echo " Warning: Unknown messages dir $dir, skipping"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo " Translating $dir..."
|
||||
if python "$script" --messages-dir "$dir" --target all --skip-review 2>&1 | tail -5; then
|
||||
git add "$dir"/*.json
|
||||
echo " Done: $dir"
|
||||
else
|
||||
echo " Warning: Translation failed for $dir (GCP auth may be missing). CI will catch this."
|
||||
fi
|
||||
done
|
||||
|
||||
echo "i18n: Translation complete."
|
||||
+474
-122
@@ -90,6 +90,26 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: npm run lint
|
||||
|
||||
translation-check:
|
||||
name: "Translation Validation"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && needs.changes.outputs.frontend == 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Validate frontend translations (key parity)
|
||||
run: |
|
||||
python frontend/scripts/validate-translations.py --messages-dir frontend/messages --keys-only || echo "::warning::Frontend translation validation failed — run translate.py to fix"
|
||||
|
||||
- name: Validate backend translations (key parity)
|
||||
run: python frontend/scripts/validate-translations.py --messages-dir backend/translations --keys-only
|
||||
|
||||
frontend-unit-tests:
|
||||
name: "Frontend - Unit Tests"
|
||||
runs-on: ubuntu-latest
|
||||
@@ -628,7 +648,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
|
||||
@@ -677,7 +714,7 @@ jobs:
|
||||
# frontend-lint IS required - catches React hooks violations that cause runtime crashes
|
||||
# frontend-e2e-happy-path is required ONLY when 'e2e-happy-path' label is present
|
||||
# frontend-e2e-full is optional (requires 'e2e' label) so not enforced here
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path]
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path, translation-check]
|
||||
if: github.ref != 'refs/heads/main' && always()
|
||||
steps:
|
||||
- name: Check results
|
||||
@@ -701,6 +738,14 @@ jobs:
|
||||
fi
|
||||
done
|
||||
|
||||
# Translation check: warn but don't block (pre-existing placeholder issues)
|
||||
translation_result="${{ needs.translation-check.result }}"
|
||||
if [[ "$translation_result" == "failure" ]]; then
|
||||
echo "⚠️ Translation validation failed — run translate.py to fix"
|
||||
elif [[ "$translation_result" == "success" ]]; then
|
||||
echo "✅ Translation validation passed"
|
||||
fi
|
||||
|
||||
# E2E Happy Path: enforced when 'e2e-happy-path' label is on the PR
|
||||
e2e_result="${{ needs.frontend-e2e-happy-path.result }}"
|
||||
has_label="${{ contains(github.event.pull_request.labels.*.name, 'e2e-happy-path') }}"
|
||||
@@ -885,6 +930,22 @@ jobs:
|
||||
# - / (main app)
|
||||
# - /app/jobs/{id}/lyrics (lyrics review)
|
||||
# - /app/jobs/{id}/instrumental (instrumental review)
|
||||
- name: Capture build metadata
|
||||
id: frontend-meta
|
||||
run: |
|
||||
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
|
||||
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
|
||||
if [ -n "$PR_NUM" ]; then
|
||||
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
|
||||
else
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
@@ -894,6 +955,10 @@ jobs:
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
|
||||
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
|
||||
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
|
||||
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
|
||||
run: npm run build
|
||||
|
||||
- name: Deploy consumer to Cloudflare Pages
|
||||
@@ -912,6 +977,10 @@ jobs:
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
NEXT_PUBLIC_TENANT_PORTAL: "true"
|
||||
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
|
||||
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
|
||||
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
|
||||
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
|
||||
run: npm run build
|
||||
|
||||
- name: Deploy tenant portal to Cloudflare Pages
|
||||
@@ -942,6 +1011,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: |
|
||||
@@ -986,6 +1060,23 @@ jobs:
|
||||
echo "📋 Current version: $VERSION"
|
||||
echo "🚀 Deploying on every push to main"
|
||||
|
||||
- name: Capture build metadata
|
||||
id: build-meta
|
||||
run: |
|
||||
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
|
||||
# For squash-merge commits, PR number is in the commit message as (#NNN)
|
||||
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
|
||||
if [ -n "$PR_NUM" ]; then
|
||||
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
|
||||
else
|
||||
PR_NUM=""
|
||||
PR_TITLE=""
|
||||
fi
|
||||
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Authenticate to Google Cloud (Workload Identity)
|
||||
id: auth
|
||||
uses: google-github-actions/auth@v2
|
||||
@@ -999,14 +1090,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 +1109,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 +1122,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 +1135,280 @@ 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)
|
||||
|
||||
DEPLOY_TEST_PATH="gs://karaoke-gen-storage-nomadkaraoke/deploy-test"
|
||||
|
||||
echo "Uploading test assets to GCS..."
|
||||
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
|
||||
"${DEPLOY_TEST_PATH}/test-preview.ass"
|
||||
gsutil cp infrastructure/encoding-worker/test-assets/test-audio.flac \
|
||||
"${DEPLOY_TEST_PATH}/test-audio.flac"
|
||||
|
||||
echo "Submitting test encode to $SECONDARY_IP..."
|
||||
HTTP_CODE=$(curl -s -o /tmp/encode-response.json -w '%{http_code}' \
|
||||
-X POST "http://${SECONDARY_IP}:8080/encode-preview" \
|
||||
-H "X-API-Key: $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"job_id\": \"deploy-health-check\",
|
||||
\"ass_gcs_path\": \"${DEPLOY_TEST_PATH}/test-preview.ass\",
|
||||
\"audio_gcs_path\": \"${DEPLOY_TEST_PATH}/test-audio.flac\",
|
||||
\"output_gcs_path\": \"${DEPLOY_TEST_PATH}/output-preview.mp4\"
|
||||
}") || HTTP_CODE="000"
|
||||
RESPONSE=$(cat /tmp/encode-response.json 2>/dev/null || echo "{}")
|
||||
|
||||
echo "Encode response (HTTP $HTTP_CODE): $RESPONSE"
|
||||
if [ "$HTTP_CODE" != "200" ] && [ "$HTTP_CODE" != "202" ]; then
|
||||
echo "::error::Encode request failed with HTTP $HTTP_CODE"
|
||||
echo "passed=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
|
||||
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
|
||||
|
||||
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "cached" ] && [ "$STATUS" != "in_progress" ]; 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 -s \
|
||||
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
|
||||
-H "X-API-Key: $API_KEY" 2>/dev/null | jq -r '.status // "unknown"' 2>/dev/null) || JOB_STATUS="unknown"
|
||||
echo "Encode status: $JOB_STATUS (attempt $i/12)"
|
||||
if [ "$JOB_STATUS" = "complete" ]; 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 != 'true'
|
||||
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 +1527,88 @@ 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 + poetry.lock (resolved deps that affect GPU image)
|
||||
# Using poetry.lock instead of pyproject.toml so that version-only bumps
|
||||
# (which don't change dependencies) don't trigger expensive GPU base rebuilds
|
||||
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base poetry.lock | 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
|
||||
# ============================================
|
||||
@@ -1305,20 +1627,50 @@ jobs:
|
||||
--region us-central1 \
|
||||
--platform managed \
|
||||
--allow-unauthenticated \
|
||||
--memory 16Gi \
|
||||
--cpu 8 \
|
||||
--memory 2Gi \
|
||||
--cpu 2 \
|
||||
--cpu-boost \
|
||||
--no-cpu-throttling \
|
||||
--cpu-throttling \
|
||||
--execution-environment gen2 \
|
||||
--timeout 1800 \
|
||||
--concurrency 1 \
|
||||
--max-instances 50 \
|
||||
--min-instances 4 \
|
||||
--concurrency 80 \
|
||||
--max-instances 20 \
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,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,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
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
|
||||
|
||||
# Lyrics transcription job (CPU, us-central1)
|
||||
gcloud run jobs update lyrics-transcription-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 }}"
|
||||
|
||||
@@ -67,6 +67,16 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
# testmail.app is used for E2E testing but gets flagged as disposable
|
||||
# by external APIs. Ensure it's in the allowlist before the test runs.
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: failed to allowlist domain (may already exist)"
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: inputs.use_test_token == true
|
||||
|
||||
@@ -232,3 +232,4 @@ flacfetch
|
||||
|
||||
# Test output directories
|
||||
Rick Astley*/
|
||||
.superpowers/
|
||||
@@ -0,0 +1 @@
|
||||
[{"name":"generate-buildid","duration":272,"timestamp":244518298649,"id":4,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"load-custom-routes","duration":314,"timestamp":244518299029,"id":5,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"create-dist-dir","duration":333,"timestamp":244518299363,"id":6,"parentId":1,"tags":{},"startTime":1775262331362,"traceId":"b3ef0d179e8acedf"},{"name":"clean","duration":358,"timestamp":244518300558,"id":7,"parentId":1,"tags":{},"startTime":1775262331363,"traceId":"b3ef0d179e8acedf"},{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
|
||||
@@ -0,0 +1 @@
|
||||
[{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
|
||||
@@ -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
|
||||
@@ -96,6 +97,20 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
|
||||
- `gcloud` CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
|
||||
- Stop and notify user on auth issues
|
||||
|
||||
### Internationalization (i18n)
|
||||
|
||||
- All user-facing strings live in `frontend/messages/{locale}.json` (33 locales), NOT in components
|
||||
- Backend strings live in `backend/translations/{locale}.json` (currently 3 locales: en, es, de)
|
||||
- Components use `useTranslations('namespace')` from next-intl
|
||||
- Pages are under `frontend/src/app/[locale]/` — locale-aware routing
|
||||
- Admin pages (under `/admin/`, `/app/`) use DefaultIntlProvider (English-only, excluded from i18n)
|
||||
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
|
||||
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
|
||||
- Translation uses Gemini 3.1 Pro via Vertex AI with GCS cache for efficiency
|
||||
- CI validates all locale files have matching keys — **PR will fail if translations are missing**
|
||||
- Pre-commit hook auto-translates when en.json changes (enable: `git config core.hooksPath .githooks`)
|
||||
- Don't hardcode user-facing strings — add to `messages/en.json` and use `t('key')`
|
||||
|
||||
## API Authentication (for Agents)
|
||||
|
||||
When you need to call backend APIs programmatically:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -29,6 +29,8 @@ tmp/
|
||||
# Google Cloud
|
||||
.gcloud/
|
||||
*.json
|
||||
# Allow i18n translation files
|
||||
!translations/*.json
|
||||
|
||||
# Testing
|
||||
.pytest_cache/
|
||||
|
||||
+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
|
||||
|
||||
@@ -23,6 +23,7 @@ RUN apt-get update && apt-get install -y \
|
||||
build-essential \
|
||||
curl \
|
||||
xz-utils \
|
||||
chromium \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install comprehensive font support for international lyrics and symbols
|
||||
|
||||
@@ -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(
|
||||
|
||||
+928
-12
File diff suppressed because it is too large.
Load diff
@@ -50,8 +50,10 @@ 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
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -239,24 +241,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 +268,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:
|
||||
"""
|
||||
@@ -297,17 +310,17 @@ def _validate_and_prepare_selection(
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
|
||||
|
||||
# Get search results from state_data
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="No search results available")
|
||||
raise HTTPException(status_code=400, detail=t("en", "audioSearch.noSearchResults"))
|
||||
|
||||
if selection_index < 0 or selection_index >= len(search_results):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid selection index {selection_index}. Valid range: 0-{len(search_results)-1}"
|
||||
detail=t("en", "audioSearch.invalidSelectionIndex", selection_index=selection_index, max=len(search_results)-1)
|
||||
)
|
||||
|
||||
selected = search_results[selection_index]
|
||||
@@ -582,12 +595,14 @@ async def search_audio(
|
||||
- Interactive mode (default): Returns results, user calls /select endpoint
|
||||
- Auto mode (auto_download=True): Automatically selects and downloads best
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.audio_search:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Audio search is not available for this portal"
|
||||
detail=t(locale, "audioSearch.notEnabled")
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -632,8 +647,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 +703,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 +769,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 +854,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",
|
||||
@@ -949,12 +969,14 @@ async def search_audio_standalone(
|
||||
Credits are checked here (early feedback) but NOT deducted — deduction
|
||||
happens when the job is created via create-from-search.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.audio_search:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Audio search is not available for this portal"
|
||||
detail=t(locale, "audioSearch.notEnabled")
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -1030,7 +1052,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 +1066,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)
|
||||
@@ -1079,14 +1103,14 @@ async def get_audio_search_results(
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
|
||||
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
|
||||
|
||||
if not search_results:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="No search results available for this job"
|
||||
detail=t("en", "audioSearch.noSearchResults")
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -1117,7 +1141,7 @@ async def select_audio_source(
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id))
|
||||
|
||||
# Verify job is awaiting selection
|
||||
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
|
||||
@@ -1156,13 +1180,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",
|
||||
|
||||
+41
-35
@@ -9,7 +9,7 @@ Provides endpoints for:
|
||||
import logging
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.services.credential_manager import (
|
||||
@@ -18,6 +18,7 @@ from backend.services.credential_manager import (
|
||||
CredentialCheckResult,
|
||||
)
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
@@ -125,15 +126,16 @@ async def get_credentials_status():
|
||||
|
||||
|
||||
@router.get("/status/{service}", response_model=CredentialStatusResponse)
|
||||
async def get_service_credential_status(service: str):
|
||||
async def get_service_credential_status(service: str, request: Request):
|
||||
"""
|
||||
Get the status of a specific service's OAuth credentials.
|
||||
|
||||
|
||||
Args:
|
||||
service: One of "youtube", "gdrive", "dropbox"
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
manager = get_credential_manager()
|
||||
|
||||
|
||||
if service == "youtube":
|
||||
result = manager.check_youtube_credentials()
|
||||
elif service == "gdrive":
|
||||
@@ -141,7 +143,7 @@ async def get_service_credential_status(service: str):
|
||||
elif service == "dropbox":
|
||||
result = manager.check_dropbox_credentials()
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail=f"Unknown service: {service}")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "auth.unknownService", service=service))
|
||||
|
||||
return CredentialStatusResponse(
|
||||
service=result.service,
|
||||
@@ -153,42 +155,43 @@ async def get_service_credential_status(service: str):
|
||||
|
||||
|
||||
@router.post("/validate", response_model=CredentialValidationResponse)
|
||||
async def validate_credentials(request: CredentialValidationRequest):
|
||||
async def validate_credentials(request: CredentialValidationRequest, http_request: Request):
|
||||
"""
|
||||
Validate that credentials are available for requested services.
|
||||
|
||||
|
||||
Use this before submitting a job to ensure all required
|
||||
credentials are valid.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
manager = get_credential_manager()
|
||||
invalid_services = []
|
||||
|
||||
|
||||
if request.youtube:
|
||||
result = manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append("youtube")
|
||||
|
||||
|
||||
if request.gdrive:
|
||||
result = manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append("gdrive")
|
||||
|
||||
|
||||
if request.dropbox:
|
||||
result = manager.check_dropbox_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append("dropbox")
|
||||
|
||||
|
||||
if invalid_services:
|
||||
return CredentialValidationResponse(
|
||||
valid=False,
|
||||
invalid_services=invalid_services,
|
||||
message=f"The following services need re-authorization: {', '.join(invalid_services)}"
|
||||
message=t(locale, "auth.invalidCredentials", services=", ".join(invalid_services))
|
||||
)
|
||||
|
||||
|
||||
return CredentialValidationResponse(
|
||||
valid=True,
|
||||
invalid_services=[],
|
||||
message="All requested credentials are valid"
|
||||
message=t(locale, "auth.validCredentials")
|
||||
)
|
||||
|
||||
|
||||
@@ -197,40 +200,41 @@ async def validate_credentials(request: CredentialValidationRequest):
|
||||
# ===========================================================================
|
||||
|
||||
@router.post("/youtube/device", response_model=DeviceAuthStartResponse)
|
||||
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None):
|
||||
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
"""
|
||||
Start YouTube device authorization flow.
|
||||
|
||||
|
||||
This initiates a device auth flow that allows authorization
|
||||
from any device. The user must visit the verification URL
|
||||
and enter the user code.
|
||||
|
||||
|
||||
Client credentials are loaded from Secret Manager ('youtube-client-credentials')
|
||||
unless explicitly provided in the request body.
|
||||
|
||||
|
||||
After starting, poll /auth/youtube/device/{device_code} to
|
||||
check for completion.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request) if http_request else "en"
|
||||
manager = get_credential_manager()
|
||||
|
||||
|
||||
try:
|
||||
device_info = manager.start_youtube_device_auth(
|
||||
client_id=request.client_id if request else None,
|
||||
client_secret=request.client_secret if request else None
|
||||
)
|
||||
|
||||
|
||||
return DeviceAuthStartResponse(
|
||||
device_code=device_info.device_code,
|
||||
user_code=device_info.user_code,
|
||||
verification_url=device_info.verification_url,
|
||||
expires_in=device_info.expires_in,
|
||||
interval=device_info.interval,
|
||||
instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}"
|
||||
instructions=t(locale, "auth.youtubeAuthInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code)
|
||||
)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start YouTube device auth: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "auth.youtubeAuthStartFailed", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/youtube/device/{device_code}", response_model=DeviceAuthPollResponse)
|
||||
@@ -259,35 +263,36 @@ async def poll_youtube_device_auth(device_code: str):
|
||||
|
||||
|
||||
@router.post("/gdrive/device", response_model=DeviceAuthStartResponse)
|
||||
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None):
|
||||
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
"""
|
||||
Start Google Drive device authorization flow.
|
||||
|
||||
|
||||
Client credentials are loaded from Secret Manager ('gdrive-client-credentials')
|
||||
unless explicitly provided in the request body.
|
||||
|
||||
|
||||
After starting, poll /auth/gdrive/device/{device_code} to check for completion.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request) if http_request else "en"
|
||||
manager = get_credential_manager()
|
||||
|
||||
|
||||
try:
|
||||
device_info = manager.start_gdrive_device_auth(
|
||||
client_id=request.client_id if request else None,
|
||||
client_secret=request.client_secret if request else None
|
||||
)
|
||||
|
||||
|
||||
return DeviceAuthStartResponse(
|
||||
device_code=device_info.device_code,
|
||||
user_code=device_info.user_code,
|
||||
verification_url=device_info.verification_url,
|
||||
expires_in=device_info.expires_in,
|
||||
interval=device_info.interval,
|
||||
instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}"
|
||||
instructions=t(locale, "auth.gdriveLinkInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code)
|
||||
)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to start Google Drive device auth: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail=t(locale, "auth.gdriveAuthStartFailed", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/gdrive/device/{device_code}", response_model=DeviceAuthPollResponse)
|
||||
@@ -311,19 +316,20 @@ async def poll_gdrive_device_auth(device_code: str):
|
||||
# ===========================================================================
|
||||
|
||||
@router.post("/test-alert")
|
||||
async def test_credential_alert(background_tasks: BackgroundTasks):
|
||||
async def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
|
||||
"""
|
||||
Test the credential alert mechanism.
|
||||
|
||||
|
||||
Sends a test alert to Discord if configured.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
settings = get_settings()
|
||||
discord_url = settings.get_secret("discord-alert-webhook")
|
||||
|
||||
|
||||
if not discord_url:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Discord alert webhook not configured"
|
||||
detail=t(locale, "auth.discordAlertNotConfigured")
|
||||
)
|
||||
|
||||
manager = get_credential_manager()
|
||||
|
||||
@@ -14,6 +14,7 @@ from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -26,7 +27,7 @@ RATE_LIMIT_MAX_REQUESTS = 20
|
||||
RATE_LIMIT_WINDOW_SECONDS = 60
|
||||
|
||||
|
||||
def _check_rate_limit(user_email: str) -> None:
|
||||
def _check_rate_limit(user_email: str, locale: str = "en") -> None:
|
||||
"""Check per-user rate limit. Raises 429 if exceeded."""
|
||||
now = time.monotonic()
|
||||
window_start = now - RATE_LIMIT_WINDOW_SECONDS
|
||||
@@ -37,12 +38,12 @@ def _check_rate_limit(user_email: str) -> None:
|
||||
|
||||
# Remove expired entries
|
||||
timestamps = _rate_limit_windows[user_email]
|
||||
_rate_limit_windows[user_email] = [t for t in timestamps if t > window_start]
|
||||
_rate_limit_windows[user_email] = [ts for ts in timestamps if ts > window_start]
|
||||
|
||||
if len(_rate_limit_windows[user_email]) >= RATE_LIMIT_MAX_REQUESTS:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=f"Rate limit exceeded. Maximum {RATE_LIMIT_MAX_REQUESTS} catalog requests per minute.",
|
||||
detail=t(locale, "catalog.rateLimitExceeded", max_requests=RATE_LIMIT_MAX_REQUESTS),
|
||||
)
|
||||
|
||||
_rate_limit_windows[user_email].append(now)
|
||||
@@ -107,6 +108,7 @@ class CommunityCheckResponse(BaseModel):
|
||||
|
||||
@router.get("/artists", response_model=list[ArtistResult])
|
||||
async def search_artists(
|
||||
request: Request,
|
||||
q: str = Query(..., min_length=2, description="Artist name search query"),
|
||||
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
@@ -115,7 +117,8 @@ async def search_artists(
|
||||
Search for artists by name. Returns canonical MusicBrainz/Spotify artist data
|
||||
for autocomplete in job creation forms.
|
||||
"""
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.catalog_proxy_service import search_artists
|
||||
results = await search_artists(q, limit)
|
||||
@@ -124,6 +127,7 @@ async def search_artists(
|
||||
|
||||
@router.get("/tracks", response_model=list[TrackResult])
|
||||
async def search_tracks(
|
||||
request: Request,
|
||||
q: str = Query(..., min_length=2, description="Track name search query"),
|
||||
artist: Optional[str] = Query(None, description="Filter by artist name"),
|
||||
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
|
||||
@@ -133,7 +137,8 @@ async def search_tracks(
|
||||
Search for tracks by name, optionally filtered by artist.
|
||||
Returns canonical Spotify track data for autocomplete in job creation forms.
|
||||
"""
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.catalog_proxy_service import search_tracks
|
||||
results = await search_tracks(q, artist, limit)
|
||||
@@ -142,6 +147,7 @@ async def search_tracks(
|
||||
|
||||
@router.post("/community-check", response_model=CommunityCheckResponse)
|
||||
async def check_community_versions(
|
||||
request: Request,
|
||||
body: CommunityCheckRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
@@ -149,7 +155,8 @@ async def check_community_versions(
|
||||
Check if a song already has community-approved karaoke versions on YouTube
|
||||
via karaokenerds.com. Non-blocking — just informs the user.
|
||||
"""
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.karaokenerds_service import check_community_versions
|
||||
result = await check_community_versions(body.artist, body.title)
|
||||
|
||||
@@ -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,10 +40,12 @@ 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,
|
||||
)
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -56,6 +58,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 +163,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 +269,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 +281,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 +320,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'}
|
||||
@@ -287,7 +351,8 @@ async def _trigger_audio_worker_only(job_id: str) -> None:
|
||||
def _prepare_theme_for_job(
|
||||
job_id: str,
|
||||
theme_id: str,
|
||||
color_overrides: Optional[Dict[str, str]] = None
|
||||
color_overrides: Optional[Dict[str, str]] = None,
|
||||
locale: str = "en"
|
||||
) -> Tuple[str, Dict[str, str], Optional[str]]:
|
||||
"""
|
||||
Prepare theme style files for a job.
|
||||
@@ -296,6 +361,7 @@ def _prepare_theme_for_job(
|
||||
job_id: The job ID
|
||||
theme_id: Theme identifier
|
||||
color_overrides: Optional color override dict
|
||||
locale: Locale for error messages
|
||||
|
||||
Returns:
|
||||
Tuple of (style_params_gcs_path, style_assets, youtube_description)
|
||||
@@ -309,7 +375,7 @@ def _prepare_theme_for_job(
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Theme not found: {theme_id}. Use GET /api/themes to list available themes."
|
||||
detail=t(locale, "fileUpload.invalidTheme", theme_id=theme_id)
|
||||
)
|
||||
|
||||
# Convert dict to ColorOverrides model if provided
|
||||
@@ -381,6 +447,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.
|
||||
@@ -400,6 +468,8 @@ async def upload_and_create_job(
|
||||
The style_params JSON can reference the uploaded images/fonts by their original
|
||||
filenames, and the backend will update the paths to GCS locations.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.file_upload:
|
||||
@@ -510,9 +580,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 +604,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 +676,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
|
||||
@@ -617,7 +704,7 @@ async def upload_and_create_job(
|
||||
if effective_theme_id and not has_custom_style_files:
|
||||
try:
|
||||
theme_style_params_path, theme_style_assets, theme_youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, parsed_color_overrides or None
|
||||
job_id, effective_theme_id, parsed_color_overrides or None, locale=locale
|
||||
)
|
||||
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
|
||||
except HTTPException:
|
||||
@@ -640,7 +727,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 +746,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 +757,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,
|
||||
@@ -814,7 +901,7 @@ async def upload_and_create_job(
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"message": "Files uploaded successfully. Processing started.",
|
||||
"message": t(locale, "fileUpload.uploadSuccess"),
|
||||
"filename": file.filename,
|
||||
"style_assets_uploaded": list(style_assets.keys()) if style_assets else [],
|
||||
"server_version": VERSION,
|
||||
@@ -827,7 +914,7 @@ async def upload_and_create_job(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error uploading files: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadError", error=str(e))) from e
|
||||
|
||||
|
||||
# ============================================================================
|
||||
@@ -994,11 +1081,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':
|
||||
@@ -1028,6 +1115,8 @@ async def create_job_with_upload_urls(
|
||||
- Works with any HTTP client (no HTTP/2 required)
|
||||
- Resumable uploads possible with GCS
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.file_upload:
|
||||
@@ -1039,14 +1128,14 @@ async def create_job_with_upload_urls(
|
||||
try:
|
||||
# Validate files list
|
||||
if not body.files:
|
||||
raise HTTPException(status_code=400, detail="At least one file is required")
|
||||
|
||||
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
|
||||
|
||||
# Check that audio file is included
|
||||
audio_files = [f for f in body.files if f.file_type == 'audio']
|
||||
if not audio_files:
|
||||
raise HTTPException(status_code=400, detail="An audio file is required")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
|
||||
if len(audio_files) > 1:
|
||||
raise HTTPException(status_code=400, detail="Only one audio file is allowed")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.multipleAudioFilesNotAllowed"))
|
||||
|
||||
# Validate file types and extensions
|
||||
for file_info in body.files:
|
||||
@@ -1077,12 +1166,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 +1198,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 +1215,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 +1258,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")
|
||||
|
||||
@@ -1176,7 +1278,7 @@ async def create_job_with_upload_urls(
|
||||
# If theme is set and no style_params uploaded, prepare theme style now
|
||||
if effective_theme_id and not has_style_params_upload:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, body.color_overrides
|
||||
job_id, effective_theme_id, body.color_overrides, locale=locale
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
@@ -1212,7 +1314,7 @@ async def create_job_with_upload_urls(
|
||||
return CreateJobWithUploadUrlsResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Job created. Upload files to the provided URLs, then call /api/jobs/{job_id}/uploads-complete",
|
||||
message=t(locale, "fileUpload.urlCreationSuccess"),
|
||||
upload_urls=upload_urls,
|
||||
server_version=VERSION
|
||||
)
|
||||
@@ -1223,12 +1325,13 @@ async def create_job_with_upload_urls(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job with upload URLs: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.urlCreationError", error=str(e))) from e
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/uploads-complete")
|
||||
async def mark_uploads_complete(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: UploadsCompleteRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
@@ -1247,22 +1350,23 @@ async def mark_uploads_complete(
|
||||
- Update job with GCS paths
|
||||
- Trigger audio and lyrics workers
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
# Get job and verify it exists
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# Verify job is in pending state
|
||||
if job.status != JobStatus.PENDING:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job {job_id} is not in pending state (current: {job.status}). Cannot complete uploads."
|
||||
detail=t(locale, "jobs.notCompleted", status=job.status)
|
||||
)
|
||||
|
||||
|
||||
# Validate required files
|
||||
if 'audio' not in body.uploaded_files:
|
||||
raise HTTPException(status_code=400, detail="Audio file upload is required")
|
||||
raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided"))
|
||||
|
||||
# Build GCS paths for uploaded files and validate they exist
|
||||
update_data = {}
|
||||
@@ -1278,10 +1382,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':
|
||||
@@ -1400,7 +1504,7 @@ async def mark_uploads_complete(
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"message": "Uploads validated. Processing started.",
|
||||
"message": t(locale, "fileUpload.uploadsCompleteSuccess"),
|
||||
"files_validated": body.uploaded_files,
|
||||
"style_assets": list(style_assets.keys()) if style_assets else [],
|
||||
"server_version": VERSION,
|
||||
@@ -1411,7 +1515,7 @@ async def mark_uploads_complete(
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error completing uploads for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadsCompleteError", error=str(e))) from e
|
||||
|
||||
|
||||
# ============================================================================
|
||||
@@ -1494,6 +1598,8 @@ async def create_job_from_url(
|
||||
Note: YouTube rate limiting may cause occasional download failures.
|
||||
The backend will retry automatically.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.youtube_url:
|
||||
@@ -1510,6 +1616,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 +1687,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,18 +1739,23 @@ 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")
|
||||
|
||||
# If theme is set, prepare theme style now
|
||||
if effective_theme_id:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, body.color_overrides
|
||||
job_id, effective_theme_id, body.color_overrides, locale=locale
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
@@ -1630,6 +1767,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}")
|
||||
@@ -1673,7 +1814,7 @@ async def create_job_from_url(
|
||||
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"YouTube download failed: {e}"
|
||||
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
|
||||
)
|
||||
else:
|
||||
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
|
||||
@@ -1740,7 +1881,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}"
|
||||
|
||||
@@ -1767,6 +1908,8 @@ async def create_finalise_only_job(
|
||||
|
||||
The endpoint returns signed URLs for uploading all the prep files.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
# Check tenant feature flag - finalise-only requires file upload capability
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.file_upload:
|
||||
@@ -1866,7 +2009,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 +2052,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")
|
||||
|
||||
@@ -1922,7 +2070,7 @@ async def create_finalise_only_job(
|
||||
# If theme is set and no style_params uploaded, prepare theme style now
|
||||
if effective_theme_id and not has_style_params_upload:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, body.color_overrides
|
||||
job_id, effective_theme_id, body.color_overrides, locale=locale
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
@@ -2067,7 +2215,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 +2468,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 +2499,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 +2509,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
|
||||
|
||||
|
||||
@@ -5,10 +5,12 @@ import os
|
||||
import logging
|
||||
import subprocess
|
||||
import platform
|
||||
from fastapi import APIRouter
|
||||
from typing import Dict, Any, Optional
|
||||
from fastapi import APIRouter, Depends
|
||||
from typing import Dict, Any, Optional, Tuple
|
||||
|
||||
from backend.version import VERSION
|
||||
from backend.version import VERSION, COMMIT_SHA, PR_NUMBER, PR_TITLE, STARTUP_TIME
|
||||
from backend.api.dependencies import optional_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.services.flacfetch_client import get_flacfetch_client
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.stripe_service import get_stripe_service
|
||||
@@ -308,6 +310,175 @@ async def flacfetch_health() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def check_audio_separator_status() -> Dict[str, Any]:
|
||||
"""Check audio separator availability without calling the remote GPU service."""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
except Exception:
|
||||
pkg_version = None
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": pkg_version,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
def _get_encoding_worker_manager():
|
||||
"""Get the EncodingWorkerManager instance. Separated for testability."""
|
||||
try:
|
||||
encoding_service = get_encoding_service()
|
||||
if hasattr(encoding_service, '_worker_manager') and encoding_service._worker_manager:
|
||||
return encoding_service._worker_manager
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/health/system-status")
|
||||
async def system_status(
|
||||
auth: Optional[Tuple] = Depends(optional_auth),
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Aggregated system status for all services.
|
||||
|
||||
Returns basic info for everyone. Admin users get additional
|
||||
blue-green deployment details for the encoder.
|
||||
"""
|
||||
is_admin = auth is not None and len(auth) >= 2 and auth[1] == UserType.ADMIN
|
||||
|
||||
# Fetch all health statuses concurrently
|
||||
import asyncio
|
||||
encoding_task = check_encoding_worker_status()
|
||||
flacfetch_task = check_flacfetch_service_status()
|
||||
encoding_status, flacfetch_status = await asyncio.gather(
|
||||
encoding_task, flacfetch_task
|
||||
)
|
||||
separator_status = check_audio_separator_status()
|
||||
|
||||
# Build frontend service info (from env vars baked at build time — returned as-is)
|
||||
frontend_svc = {
|
||||
"status": "ok",
|
||||
"version": VERSION, # Frontend and backend share the same version from pyproject.toml
|
||||
}
|
||||
|
||||
# Build backend service info
|
||||
backend_svc = {
|
||||
"status": "ok",
|
||||
"version": VERSION,
|
||||
"deployed_at": STARTUP_TIME,
|
||||
}
|
||||
if COMMIT_SHA:
|
||||
backend_svc["commit_sha"] = COMMIT_SHA
|
||||
if PR_NUMBER:
|
||||
backend_svc["pr_number"] = PR_NUMBER
|
||||
if PR_TITLE:
|
||||
backend_svc["pr_title"] = PR_TITLE
|
||||
|
||||
# Build encoder service info
|
||||
encoder_svc = {
|
||||
"status": "ok" if encoding_status.get("available") else "offline",
|
||||
"version": encoding_status.get("wheel_version"),
|
||||
"active_jobs": encoding_status.get("active_jobs", 0),
|
||||
}
|
||||
|
||||
# Build flacfetch service info
|
||||
flacfetch_svc = {
|
||||
"status": "ok" if flacfetch_status.get("available") else "offline",
|
||||
"version": flacfetch_status.get("version"),
|
||||
}
|
||||
|
||||
# Build separator service info
|
||||
separator_svc = {
|
||||
"status": "ok" if separator_status.get("available") else "offline",
|
||||
"version": separator_status.get("version"),
|
||||
}
|
||||
|
||||
# Admin-only: blue-green encoder details from Firestore
|
||||
if is_admin:
|
||||
manager = _get_encoding_worker_manager()
|
||||
if manager:
|
||||
try:
|
||||
config = manager.get_config()
|
||||
encoder_svc["admin_details"] = {
|
||||
"primary_vm": config.primary_vm,
|
||||
"primary_ip": config.primary_ip,
|
||||
"primary_version": config.primary_version,
|
||||
"primary_deployed_at": config.primary_deployed_at,
|
||||
"secondary_vm": config.secondary_vm,
|
||||
"secondary_ip": config.secondary_ip,
|
||||
"secondary_version": config.secondary_version,
|
||||
"secondary_deployed_at": config.secondary_deployed_at,
|
||||
"last_swap_at": config.last_swap_at,
|
||||
"deploy_in_progress": config.deploy_in_progress,
|
||||
"active_jobs": encoding_status.get("active_jobs", 0),
|
||||
"queue_length": encoding_status.get("queue_length", 0),
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to get blue-green config: {e}")
|
||||
|
||||
# Add error details for offline services
|
||||
if not flacfetch_status.get("available"):
|
||||
flacfetch_svc["admin_details"] = {"error": flacfetch_status.get("error")}
|
||||
if not separator_status.get("available"):
|
||||
separator_svc["admin_details"] = {"error": separator_status.get("error")}
|
||||
if not encoding_status.get("available") and "admin_details" not in encoder_svc:
|
||||
encoder_svc["admin_details"] = {"error": encoding_status.get("error")}
|
||||
|
||||
return {
|
||||
"services": {
|
||||
"frontend": frontend_svc,
|
||||
"backend": backend_svc,
|
||||
"encoder": encoder_svc,
|
||||
"flacfetch": flacfetch_svc,
|
||||
"separator": separator_svc,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/detailed")
|
||||
async def detailed_health_check() -> Dict[str, Any]:
|
||||
"""
|
||||
|
||||
@@ -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)
|
||||
|
||||
+646
-226
File diff suppressed because it is too large.
Load diff
+43
-18
@@ -11,13 +11,14 @@ 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
|
||||
from backend.api.dependencies import require_auth, require_admin
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.push_notification_service import get_push_notification_service
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -37,6 +38,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 +113,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,39 +122,53 @@ 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)
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.enable_push_notifications:
|
||||
raise HTTPException(status_code=503, detail="Push notifications are not enabled")
|
||||
raise HTTPException(status_code=503, detail=t(locale, "push.disabled"))
|
||||
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
|
||||
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
# Validate keys
|
||||
if "p256dh" not in request.keys or "auth" not in request.keys:
|
||||
raise HTTPException(status_code=400, detail="Missing required keys (p256dh, auth)")
|
||||
if "p256dh" not in subscribe_request.keys or "auth" not in subscribe_request.keys:
|
||||
raise HTTPException(status_code=400, detail=t(locale, "push.missingEncryptionKeys"))
|
||||
|
||||
# Resolve tenant_id: prefer explicit from body, fall back to middleware
|
||||
tenant_id = subscribe_request.tenant_id
|
||||
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:
|
||||
raise HTTPException(status_code=500, detail="Failed to save subscription")
|
||||
raise HTTPException(status_code=500, detail=t(locale, "push.subscriptionSaveFailed"))
|
||||
|
||||
return SubscribeResponse(
|
||||
status="success",
|
||||
message="Push subscription registered successfully"
|
||||
message=t(locale, "push.subscriptionRegistered")
|
||||
)
|
||||
|
||||
|
||||
@router.post("/unsubscribe", response_model=UnsubscribeResponse)
|
||||
async def unsubscribe_push(
|
||||
request: UnsubscribeRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
@@ -159,8 +176,10 @@ async def unsubscribe_push(
|
||||
|
||||
Requires authentication. Users can only remove their own subscriptions.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
|
||||
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
@@ -173,17 +192,18 @@ async def unsubscribe_push(
|
||||
# Don't error if subscription wasn't found - might already be removed
|
||||
return UnsubscribeResponse(
|
||||
status="success",
|
||||
message="Subscription removed (or was not found)"
|
||||
message=t(locale, "push.subscriptionNotFound")
|
||||
)
|
||||
|
||||
return UnsubscribeResponse(
|
||||
status="success",
|
||||
message="Push subscription removed successfully"
|
||||
message=t(locale, "push.subscriptionRemoved")
|
||||
)
|
||||
|
||||
|
||||
@router.get("/subscriptions", response_model=SubscriptionsListResponse)
|
||||
async def list_subscriptions(
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
@@ -191,8 +211,10 @@ async def list_subscriptions(
|
||||
|
||||
Requires authentication.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
|
||||
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
@@ -207,6 +229,7 @@ async def list_subscriptions(
|
||||
@router.post("/test", response_model=TestNotificationResponse)
|
||||
async def send_test_notification(
|
||||
request: TestNotificationRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
@@ -214,12 +237,14 @@ async def send_test_notification(
|
||||
|
||||
Admin only. Useful for testing push notification setup.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.enable_push_notifications:
|
||||
raise HTTPException(status_code=503, detail="Push notifications are not enabled")
|
||||
raise HTTPException(status_code=503, detail=t(locale, "push.disabled"))
|
||||
|
||||
if not auth_result.user_email:
|
||||
raise HTTPException(status_code=401, detail="User email not available")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable"))
|
||||
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
@@ -234,5 +259,5 @@ async def send_test_notification(
|
||||
return TestNotificationResponse(
|
||||
status="success",
|
||||
sent_count=sent_count,
|
||||
message=f"Test notification sent to {sent_count} device(s)"
|
||||
message=t(locale, "push.testNotificationSent", sent_count=sent_count)
|
||||
)
|
||||
@@ -10,12 +10,13 @@ import logging
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.email_validation_service import get_email_validation_service, EmailValidationService
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/admin/rate-limits", tags=["admin", "rate-limits"])
|
||||
@@ -49,12 +50,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 +91,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)
|
||||
@@ -130,13 +107,13 @@ async def add_disposable_domain(
|
||||
|
||||
domain = request.domain.lower().strip()
|
||||
if not domain or "." not in domain:
|
||||
raise HTTPException(status_code=400, detail="Invalid domain format")
|
||||
raise HTTPException(status_code=400, detail=t("en", "admin.invalidDomainFormat"))
|
||||
|
||||
email_validation.add_disposable_domain(domain, auth_result.user_email)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Domain '{domain}' added to disposable domains blocklist"
|
||||
message=t("en", "admin.domainAddedToBl", domain=domain)
|
||||
)
|
||||
|
||||
|
||||
@@ -150,11 +127,62 @@ async def remove_disposable_domain(
|
||||
|
||||
domain = domain.lower().strip()
|
||||
if not email_validation.remove_disposable_domain(domain, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="Domain not found in blocklist")
|
||||
raise HTTPException(status_code=404, detail=t("en", "admin.domainNotFoundInBl"))
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Domain '{domain}' removed from disposable domains blocklist"
|
||||
message=t("en", "admin.domainRemovedFromBl", domain=domain)
|
||||
)
|
||||
|
||||
|
||||
@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=t("en", "admin.invalidDomainFormat"))
|
||||
email_validation.add_allowlisted_domain(domain, auth_result.user_email)
|
||||
return SuccessResponse(success=True, message=t("en", "admin.domainAddedToAllowlist", domain=domain))
|
||||
|
||||
|
||||
@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=t("en", "admin.domainNotFoundInAllowlist"))
|
||||
return SuccessResponse(success=True, message=t("en", "admin.domainRemovedFromAllowlist", domain=domain))
|
||||
|
||||
|
||||
@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=t("en", "admin.syncComplete", external_count=result['external_count'], added=result['added'], removed=result['removed'])
|
||||
)
|
||||
|
||||
|
||||
@@ -168,13 +196,13 @@ async def add_blocked_email(
|
||||
|
||||
email = request.email.lower().strip()
|
||||
if not email or "@" not in email:
|
||||
raise HTTPException(status_code=400, detail="Invalid email format")
|
||||
raise HTTPException(status_code=400, detail=t("en", "admin.invalidEmailFormat"))
|
||||
|
||||
email_validation.add_blocked_email(email, auth_result.user_email)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Email '{email}' added to blocked emails list"
|
||||
message=t("en", "admin.emailAddedToBl", email=email)
|
||||
)
|
||||
|
||||
|
||||
@@ -188,11 +216,11 @@ async def remove_blocked_email(
|
||||
|
||||
email = email.lower().strip()
|
||||
if not email_validation.remove_blocked_email(email, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="Email not found in blocklist")
|
||||
raise HTTPException(status_code=404, detail=t("en", "admin.emailNotFoundInBl"))
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Email '{email}' removed from blocked emails list"
|
||||
message=t("en", "admin.emailRemovedFromBl", email=email)
|
||||
)
|
||||
|
||||
|
||||
@@ -206,13 +234,13 @@ async def add_blocked_ip(
|
||||
|
||||
ip_address = request.ip_address.strip()
|
||||
if not ip_address:
|
||||
raise HTTPException(status_code=400, detail="Invalid IP address")
|
||||
raise HTTPException(status_code=400, detail=t("en", "admin.invalidIPAddress"))
|
||||
|
||||
email_validation.add_blocked_ip(ip_address, auth_result.user_email)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"IP '{ip_address}' added to blocked IPs list"
|
||||
message=t("en", "admin.ipAddedToBl", ip_address=ip_address)
|
||||
)
|
||||
|
||||
|
||||
@@ -226,11 +254,11 @@ async def remove_blocked_ip(
|
||||
|
||||
ip_address = ip_address.strip()
|
||||
if not email_validation.remove_blocked_ip(ip_address, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="IP not found in blocklist")
|
||||
raise HTTPException(status_code=404, detail=t("en", "admin.ipNotFoundInBl"))
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"IP '{ip_address}' removed from blocked IPs list"
|
||||
message=t("en", "admin.ipRemovedFromBl", ip_address=ip_address)
|
||||
)
|
||||
|
||||
|
||||
@@ -276,12 +304,12 @@ async def retry_youtube_upload(
|
||||
if not queue_service.retry_upload(job_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Upload not found or not in retryable state for job {job_id}"
|
||||
detail=t("en", "admin.youtubeUploadNotFound", job_id=job_id)
|
||||
)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"YouTube upload for job {job_id} queued for retry"
|
||||
message=t("en", "admin.youtubeUploadQueuedForRetry", job_id=job_id)
|
||||
)
|
||||
|
||||
|
||||
@@ -314,5 +342,5 @@ async def trigger_youtube_queue_processing(
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message="YouTube queue processing started in background"
|
||||
message=t("en", "admin.youtubeQueueProcessingStarted")
|
||||
)
|
||||
@@ -0,0 +1,374 @@
|
||||
"""
|
||||
Referral API routes.
|
||||
|
||||
Handles:
|
||||
- Public referral interstitial (click tracking)
|
||||
- Authenticated referral dashboard
|
||||
- Stripe Connect onboarding
|
||||
- Admin vanity link creation and link management
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth, require_admin
|
||||
from backend.models.referral import (
|
||||
CreateReferralLinkRequest,
|
||||
UpdateReferralLinkRequest,
|
||||
ReferralInterstitialResponse,
|
||||
)
|
||||
from backend.services.flyer_service import get_flyer_service, FlyerError
|
||||
from backend.services.referral_service import get_referral_service
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/referrals", tags=["referrals"])
|
||||
|
||||
|
||||
class GenerateFlyerRequest(BaseModel):
|
||||
theme: str = Field(..., pattern="^(light|dark)$")
|
||||
qr_data_url: str = Field(..., max_length=500_000)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Public endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/r/{code}", response_model=ReferralInterstitialResponse)
|
||||
async def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
"""
|
||||
Public endpoint: get interstitial data for a referral link.
|
||||
|
||||
Increments click count unless no_track=true. Returns valid=False if code not found.
|
||||
"""
|
||||
service = get_referral_service()
|
||||
link = service.get_link_by_code(code)
|
||||
|
||||
if not link:
|
||||
return ReferralInterstitialResponse(valid=False)
|
||||
|
||||
# Track the click (skip when fetching for display purposes)
|
||||
if not no_track:
|
||||
try:
|
||||
service.increment_clicks(code)
|
||||
except Exception:
|
||||
logger.warning("Failed to increment clicks for code %s", code, exc_info=True)
|
||||
|
||||
return ReferralInterstitialResponse(
|
||||
valid=True,
|
||||
referral_code=link.code,
|
||||
referrer_display_name=link.display_name,
|
||||
discount_percent=link.discount_percent,
|
||||
discount_duration_days=link.discount_duration_days,
|
||||
custom_message=link.custom_message,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Authenticated user endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_my_dashboard(auth=Depends(require_auth)):
|
||||
"""Get referral dashboard data for the authenticated user."""
|
||||
service = get_referral_service()
|
||||
return service.get_dashboard_data(auth.user_email)
|
||||
|
||||
|
||||
@router.put("/me")
|
||||
async def update_my_link(
|
||||
updates: UpdateReferralLinkRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
"""Update display_name and custom_message on the user's own referral link."""
|
||||
service = get_referral_service()
|
||||
link = service.get_or_create_link(auth.user_email)
|
||||
|
||||
update_fields = {}
|
||||
if updates.display_name is not None:
|
||||
update_fields["display_name"] = updates.display_name
|
||||
if updates.custom_message is not None:
|
||||
update_fields["custom_message"] = updates.custom_message
|
||||
|
||||
if not update_fields:
|
||||
return {"ok": True, "message": "No changes"}
|
||||
|
||||
success, message = service.update_link(link.code, **update_fields)
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail=message)
|
||||
|
||||
return {"ok": True, "message": message}
|
||||
|
||||
|
||||
@router.post("/me/connect")
|
||||
async def start_stripe_connect(auth=Depends(require_auth)):
|
||||
"""Start Stripe Connect onboarding for the authenticated user."""
|
||||
# Check if user already has a Connect account
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
user = user_service.get_user(auth.user_email)
|
||||
if user and user.stripe_connect_account_id:
|
||||
raise HTTPException(status_code=400, detail="Stripe Connect account already configured")
|
||||
|
||||
service = get_referral_service()
|
||||
account_id, onboarding_url = service.create_connect_account(auth.user_email)
|
||||
|
||||
if not account_id:
|
||||
raise HTTPException(status_code=500, detail="Failed to create Stripe Connect account")
|
||||
|
||||
user_service.update_user(auth.user_email, stripe_connect_account_id=account_id)
|
||||
|
||||
return {"account_id": account_id, "onboarding_url": onboarding_url}
|
||||
|
||||
|
||||
@router.post("/me/connect/dashboard-link")
|
||||
async def get_connect_dashboard_link(auth=Depends(require_auth)):
|
||||
"""Get a login link to the Stripe Express dashboard for managing payout settings."""
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(auth.user_email)
|
||||
if not user or not user.stripe_connect_account_id:
|
||||
raise HTTPException(status_code=400, detail="No Stripe Connect account configured")
|
||||
|
||||
service = get_referral_service()
|
||||
url = service.create_connect_login_link(user.stripe_connect_account_id)
|
||||
if not url:
|
||||
raise HTTPException(status_code=500, detail="Failed to create dashboard link")
|
||||
|
||||
return {"url": url}
|
||||
|
||||
|
||||
@router.post("/me/connect/update-link")
|
||||
async def get_connect_update_link(auth=Depends(require_auth)):
|
||||
"""Get a link to update Stripe Connect account info (re-onboarding)."""
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(auth.user_email)
|
||||
if not user or not user.stripe_connect_account_id:
|
||||
raise HTTPException(status_code=400, detail="No Stripe Connect account configured")
|
||||
|
||||
service = get_referral_service()
|
||||
url = service.create_connect_update_link(user.stripe_connect_account_id)
|
||||
if not url:
|
||||
raise HTTPException(status_code=500, detail="Failed to create update link")
|
||||
|
||||
return {"url": url}
|
||||
|
||||
|
||||
class VanityRequest(BaseModel):
|
||||
desired_code: str = Field(..., min_length=2, max_length=30, pattern="^[a-z0-9-]+$")
|
||||
|
||||
|
||||
@router.post("/me/vanity-request")
|
||||
async def request_vanity_url(
|
||||
request: VanityRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
"""Request a custom vanity referral URL. Sends email to admin for review."""
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
service = get_referral_service()
|
||||
link = service.get_or_create_link(auth.user_email)
|
||||
|
||||
# Check if code is already taken
|
||||
existing = service.get_link_by_code(request.desired_code)
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail="That code is already taken. Please try another.")
|
||||
|
||||
email_service = get_email_service()
|
||||
email_service.provider.send_email(
|
||||
to_email="andrew@nomadkaraoke.com",
|
||||
subject=f"Vanity referral URL request: {request.desired_code}",
|
||||
html_content=f"""
|
||||
<h2>Vanity Referral URL Request</h2>
|
||||
<p><strong>User:</strong> {auth.user_email}</p>
|
||||
<p><strong>Current code:</strong> {link.code}</p>
|
||||
<p><strong>Desired vanity code:</strong> {request.desired_code}</p>
|
||||
<p>To approve, create the vanity link in the <a href="https://gen.nomadkaraoke.com/admin/referrals">admin dashboard</a>.</p>
|
||||
""",
|
||||
text_content=f"Vanity URL request from {auth.user_email}: {request.desired_code} (current: {link.code})",
|
||||
)
|
||||
|
||||
logger.info("Vanity URL request from %s: %s", auth.user_email, request.desired_code)
|
||||
return {"ok": True, "message": "Request sent"}
|
||||
|
||||
|
||||
@router.post("/me/flyer")
|
||||
async def generate_flyer(
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
"""Generate a personalized referral flyer PDF."""
|
||||
service = get_referral_service()
|
||||
link = service.get_or_create_link(auth.user_email)
|
||||
|
||||
try:
|
||||
flyer_service = get_flyer_service()
|
||||
pdf_bytes = flyer_service.generate_pdf(
|
||||
theme=request.theme,
|
||||
referral_code=link.code,
|
||||
discount_percent=link.discount_percent,
|
||||
qr_data_url=request.qr_data_url,
|
||||
)
|
||||
except FlyerError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": 'attachment; filename="nomad-karaoke-referral-flyer.pdf"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Admin endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.post("/admin/vanity")
|
||||
async def create_vanity_link(
|
||||
request: CreateReferralLinkRequest,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
"""Admin: create a vanity referral link."""
|
||||
if not request.vanity_code:
|
||||
raise HTTPException(status_code=400, detail="vanity_code is required")
|
||||
|
||||
service = get_referral_service()
|
||||
success, link, message = service.create_vanity_link(
|
||||
code=request.vanity_code,
|
||||
owner_email=request.owner_email,
|
||||
display_name=request.display_name,
|
||||
custom_message=request.custom_message,
|
||||
discount_percent=request.discount_percent,
|
||||
kickback_percent=request.kickback_percent,
|
||||
discount_duration_days=request.discount_duration_days,
|
||||
earning_duration_days=request.earning_duration_days,
|
||||
)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail=message)
|
||||
|
||||
return {"ok": True, "code": link.code, "message": message}
|
||||
|
||||
|
||||
@router.get("/admin/links")
|
||||
async def list_links(
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
offset: int = Query(0, ge=0),
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
"""Admin: list all referral links."""
|
||||
service = get_referral_service()
|
||||
links = service.list_links(limit=limit, offset=offset)
|
||||
return {
|
||||
"links": [link.model_dump(mode="json") for link in links],
|
||||
"count": len(links),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/admin/apply-discount")
|
||||
async def admin_apply_discount(
|
||||
request: Request,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
"""Admin: apply a referral discount to any user, even without a referral link."""
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
body = await request.json()
|
||||
user_email = body.get("email", "").lower()
|
||||
discount_percent = body.get("discount_percent", 10)
|
||||
duration_days = body.get("duration_days", 30)
|
||||
referral_code = body.get("referral_code", "admin-grant")
|
||||
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=400, detail="Email is required")
|
||||
|
||||
user_service = get_user_service()
|
||||
user = user_service.get_user(user_email)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
now = datetime.utcnow()
|
||||
|
||||
user_service.update_user(
|
||||
user_email,
|
||||
referred_by_code=referral_code,
|
||||
referred_at=now,
|
||||
referral_discount_expires_at=now + timedelta(days=duration_days),
|
||||
)
|
||||
|
||||
# Create/ensure the Stripe coupon exists for this discount percent
|
||||
service = get_referral_service()
|
||||
service.get_or_create_stripe_coupon(discount_percent)
|
||||
|
||||
logger.info(f"Admin applied {discount_percent}% discount for {duration_days} days to {user_email}")
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"message": f"Applied {discount_percent}% discount for {duration_days} days",
|
||||
"discount_expires_at": (now + timedelta(days=duration_days)).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/admin/links/{code}")
|
||||
async def update_link(
|
||||
code: str,
|
||||
updates: UpdateReferralLinkRequest,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
"""Admin: update any referral link's settings."""
|
||||
service = get_referral_service()
|
||||
|
||||
update_fields = {
|
||||
k: v for k, v in updates.model_dump().items() if v is not None
|
||||
}
|
||||
|
||||
if not update_fields:
|
||||
return {"ok": True, "message": "No changes"}
|
||||
|
||||
success, message = service.update_link(code, **update_fields)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail=message)
|
||||
|
||||
return {"ok": True, "message": message}
|
||||
|
||||
|
||||
@router.post("/admin/links/{code}/flyer")
|
||||
async def admin_generate_flyer(
|
||||
code: str,
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
"""Admin: generate a personalized referral flyer PDF for any code."""
|
||||
service = get_referral_service()
|
||||
link = service.get_link_by_code(code)
|
||||
|
||||
if not link:
|
||||
raise HTTPException(status_code=404, detail=f"Referral link '{code}' not found")
|
||||
|
||||
try:
|
||||
flyer_service = get_flyer_service()
|
||||
pdf_bytes = flyer_service.generate_pdf(
|
||||
theme=request.theme,
|
||||
referral_code=link.code,
|
||||
discount_percent=link.discount_percent,
|
||||
qr_data_url=request.qr_data_url,
|
||||
)
|
||||
except FlyerError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="nomad-karaoke-flyer-{link.code}.pdf"',
|
||||
},
|
||||
)
|
||||
+1079
-39
File diff suppressed because it is too large.
Load diff
@@ -12,6 +12,7 @@ from fastapi import APIRouter, Query, Request
|
||||
|
||||
from backend.models.tenant import TenantConfigResponse, TenantPublicConfig
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -115,6 +116,6 @@ async def get_tenant_asset(tenant_id: str, asset_name: str):
|
||||
if not url:
|
||||
from fastapi import HTTPException
|
||||
|
||||
raise HTTPException(status_code=404, detail="Asset not found")
|
||||
raise HTTPException(status_code=404, detail=t("en", "tenant.assetNotFound"))
|
||||
|
||||
return RedirectResponse(url=url)
|
||||
@@ -9,10 +9,11 @@ before job creation.
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from backend.models.theme import ThemeDetailResponse, ThemesListResponse
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -20,7 +21,7 @@ router = APIRouter(prefix="/themes", tags=["themes"])
|
||||
|
||||
|
||||
@router.get("", response_model=ThemesListResponse)
|
||||
async def list_themes() -> ThemesListResponse:
|
||||
async def list_themes(request: Request) -> ThemesListResponse:
|
||||
"""
|
||||
List all available themes.
|
||||
|
||||
@@ -29,6 +30,7 @@ async def list_themes() -> ThemesListResponse:
|
||||
|
||||
This endpoint is public and does not require authentication.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
themes = theme_service.list_themes()
|
||||
@@ -37,12 +39,12 @@ async def list_themes() -> ThemesListResponse:
|
||||
logger.error(f"Error listing themes: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load themes"
|
||||
detail=t(locale, "themes.themesLoadError")
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
|
||||
async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
|
||||
"""
|
||||
Get detailed information about a specific theme.
|
||||
|
||||
@@ -58,6 +60,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
Raises:
|
||||
404: Theme not found
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
theme = theme_service.get_theme(theme_id)
|
||||
@@ -65,7 +68,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
if theme is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
detail=t(locale, "themes.themeNotFound", theme_id=theme_id)
|
||||
)
|
||||
|
||||
return ThemeDetailResponse(theme=theme)
|
||||
@@ -75,12 +78,12 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
logger.error(f"Error getting theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load theme"
|
||||
detail=t(locale, "themes.themeLoadError")
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}/preview")
|
||||
async def get_theme_preview(theme_id: str) -> dict:
|
||||
async def get_theme_preview(theme_id: str, request: Request) -> dict:
|
||||
"""
|
||||
Get a signed URL for the theme's preview image.
|
||||
|
||||
@@ -96,20 +99,21 @@ async def get_theme_preview(theme_id: str) -> dict:
|
||||
Raises:
|
||||
404: Theme not found or no preview available
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
detail=t(locale, "themes.themeNotFound", theme_id=theme_id)
|
||||
)
|
||||
|
||||
theme = theme_service.get_theme(theme_id)
|
||||
if theme is None or theme.preview_url is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"No preview available for theme: {theme_id}"
|
||||
detail=t(locale, "themes.previewNotAvailable", theme_id=theme_id)
|
||||
)
|
||||
|
||||
return {"preview_url": theme.preview_url}
|
||||
@@ -119,12 +123,12 @@ async def get_theme_preview(theme_id: str) -> dict:
|
||||
logger.error(f"Error getting preview for theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load theme preview"
|
||||
detail=t(locale, "themes.previewLoadError")
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}/youtube-description")
|
||||
async def get_theme_youtube_description(theme_id: str) -> dict:
|
||||
async def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
|
||||
"""
|
||||
Get the YouTube description template for a theme.
|
||||
|
||||
@@ -141,13 +145,14 @@ async def get_theme_youtube_description(theme_id: str) -> dict:
|
||||
Raises:
|
||||
404: Theme not found
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
detail=t(locale, "themes.youtubeDescriptionNotFound", theme_id=theme_id)
|
||||
)
|
||||
|
||||
description = theme_service.get_youtube_description(theme_id)
|
||||
@@ -158,5 +163,5 @@ async def get_theme_youtube_description(theme_id: str) -> dict:
|
||||
logger.error(f"Error getting YouTube description for theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load YouTube description"
|
||||
detail=t(locale, "themes.youtubeDescriptionLoadError")
|
||||
)
|
||||
+421
-88
@@ -10,6 +10,7 @@ Handles:
|
||||
"""
|
||||
import hashlib
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional, Tuple
|
||||
|
||||
@@ -34,6 +35,8 @@ def _mask_email(email: str) -> str:
|
||||
from fastapi import APIRouter, HTTPException, Depends, Request, Header
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.services.email_validation_service import get_email_validation_service
|
||||
from backend.models.user import (
|
||||
UserRole,
|
||||
UserPublic,
|
||||
@@ -57,14 +60,63 @@ 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
|
||||
|
||||
|
||||
def _build_user_public(user, role_override=None, feedback_eligible=False):
|
||||
"""Build UserPublic with computed referral discount status."""
|
||||
from datetime import datetime
|
||||
|
||||
has_discount = False
|
||||
discount_percent = None
|
||||
discount_expires = None
|
||||
|
||||
if user.referral_discount_expires_at:
|
||||
expires = user.referral_discount_expires_at
|
||||
if isinstance(expires, datetime):
|
||||
# Firestore returns timezone-aware datetimes; ensure comparison is compatible
|
||||
now = datetime.utcnow()
|
||||
if expires.tzinfo is not None:
|
||||
now = now.replace(tzinfo=expires.tzinfo)
|
||||
has_discount = expires > now
|
||||
discount_expires = expires.isoformat() if has_discount else None
|
||||
|
||||
if has_discount and user.referred_by_code:
|
||||
# Look up the discount percent from the referral link
|
||||
try:
|
||||
from backend.services.referral_service import get_referral_service
|
||||
link = get_referral_service().get_link_by_code(user.referred_by_code)
|
||||
if link:
|
||||
discount_percent = link.discount_percent
|
||||
except Exception:
|
||||
discount_percent = 10 # default fallback
|
||||
|
||||
return UserPublic(
|
||||
email=user.email,
|
||||
role=role_override or user.role,
|
||||
credits=user.credits,
|
||||
display_name=user.display_name,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
tenant_id=getattr(user, 'tenant_id', None),
|
||||
feedback_eligible=feedback_eligible,
|
||||
total_spent=getattr(user, 'total_spent', 0),
|
||||
referral_code=user.referral_code,
|
||||
has_active_referral_discount=has_discount,
|
||||
referral_discount_percent=discount_percent,
|
||||
referral_discount_expires_at=discount_expires,
|
||||
referred_by_code=user.referred_by_code,
|
||||
)
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
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 +180,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,16 +223,60 @@ 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()
|
||||
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
if email_validation.is_disposable_domain(email):
|
||||
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail=t(locale, "users.disposableEmailBlocked")
|
||||
)
|
||||
|
||||
if email_validation.is_email_blocked(email):
|
||||
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
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=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
# 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=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
# Check if email service is configured
|
||||
if not email_service.is_configured():
|
||||
logger.error("Email service not configured - cannot send magic links")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Email service is not available. Please contact support."
|
||||
detail=t(locale, "users.emailServiceNotConfigured")
|
||||
)
|
||||
|
||||
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)
|
||||
@@ -166,19 +288,20 @@ async def send_magic_link(
|
||||
# Return success anyway to prevent email enumeration
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
message="If this email is registered, you will receive a sign-in link shortly."
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
# Get client info for security logging
|
||||
ip_address = 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,
|
||||
referral_code=request.referral_code,
|
||||
)
|
||||
|
||||
# Get tenant-specific email configuration
|
||||
@@ -197,6 +320,8 @@ async def send_magic_link(
|
||||
sender_email=sender_email,
|
||||
tenant_frontend_url=tenant_frontend_url,
|
||||
tenant_name=tenant_name,
|
||||
locale=locale,
|
||||
referral_code=request.referral_code,
|
||||
)
|
||||
|
||||
if not sent:
|
||||
@@ -204,9 +329,21 @@ 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.
|
||||
# Skip for test emails — they get auto-granted without evaluation.
|
||||
if existing_user is None and not is_test_email(email):
|
||||
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."
|
||||
message=t(locale, "users.magicLinkSent")
|
||||
)
|
||||
|
||||
|
||||
@@ -223,12 +360,14 @@ async def verify_magic_link(
|
||||
Returns a session token that should be stored and used for subsequent requests.
|
||||
The session will be associated with the tenant from the magic link.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
# Reject empty tokens early to avoid invalid Firestore document paths
|
||||
if not token or not token.strip():
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.invalidToken"))
|
||||
|
||||
# Get client info
|
||||
ip_address = 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)
|
||||
@@ -249,30 +388,76 @@ async def verify_magic_link(
|
||||
success, user, message = user_service.verify_magic_link(token)
|
||||
|
||||
if not success or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.verifyError", message=message))
|
||||
|
||||
# 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)}")
|
||||
|
||||
# Referral attribution: try header first (cookie path), then magic link token (email path), then URL param
|
||||
referral_code = (
|
||||
http_request.headers.get("x-referral-code")
|
||||
or (magic_link_data.get("referral_code") if magic_link_doc.exists else None)
|
||||
)
|
||||
if referral_code and not user.referred_by_code:
|
||||
try:
|
||||
from backend.services.referral_service import get_referral_service
|
||||
referral_svc = get_referral_service()
|
||||
attr_success, attr_msg = referral_svc.attribute_referral(
|
||||
referred_email=user.email,
|
||||
referral_code=referral_code,
|
||||
)
|
||||
if attr_success:
|
||||
attr_data = referral_svc.get_attribution_data(referral_code)
|
||||
if attr_data:
|
||||
user_service.update_user(user.email, **attr_data)
|
||||
user = user_service.get_user(user.email) # Refresh to include referral data
|
||||
logger.info(f"Referral attributed for {_mask_email(user.email)} via code '{referral_code}'")
|
||||
except Exception as ref_err:
|
||||
logger.warning(f"Referral attribution failed for {_mask_email(user.email)}: {ref_err}")
|
||||
|
||||
# Persist user's locale preference (from Accept-Language header)
|
||||
if locale and locale != (user.locale or "en"):
|
||||
try:
|
||||
user_service.update_user(user.email, locale=locale)
|
||||
except Exception:
|
||||
pass # Non-critical — don't block login
|
||||
|
||||
# Create session with tenant context and device fingerprint from the magic link
|
||||
magic_link_fingerprint = magic_link_data.get('device_fingerprint') if magic_link_doc.exists else None
|
||||
session = user_service.create_session(
|
||||
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
|
||||
if is_first_login:
|
||||
email_service.send_welcome_email(user.email, user.credits)
|
||||
email_service.send_welcome_email(user.email, user.credits, locale=locale)
|
||||
|
||||
# Return user info with tenant_id
|
||||
user_public = UserPublic(
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
credits=user.credits,
|
||||
display_name=user.display_name,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
tenant_id=user.tenant_id,
|
||||
)
|
||||
user_public = _build_user_public(user)
|
||||
|
||||
# Resolve tenant subdomain for cross-domain redirect safety
|
||||
tenant_subdomain = None
|
||||
@@ -287,28 +472,32 @@ async def verify_magic_link(
|
||||
status="success",
|
||||
session_token=session.token,
|
||||
user=user_public,
|
||||
message="Successfully signed in",
|
||||
message=t(locale, "users.magicLinkSuccess"),
|
||||
tenant_subdomain=tenant_subdomain,
|
||||
credits_granted=credits_granted,
|
||||
credit_status=credit_status,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/auth/logout", response_model=LogoutResponse)
|
||||
async def logout(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Logout and invalidate the current session.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
if not authorization:
|
||||
return LogoutResponse(status="success", message="Already logged out")
|
||||
return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess"))
|
||||
|
||||
# Extract token from "Bearer <token>"
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
user_service.revoke_session(token)
|
||||
|
||||
return LogoutResponse(status="success", message="Successfully logged out")
|
||||
return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess"))
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -317,6 +506,7 @@ async def logout(
|
||||
|
||||
@router.get("/me", response_model=UserProfileResponse)
|
||||
async def get_current_user(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -325,10 +515,11 @@ async def get_current_user(
|
||||
|
||||
Requires a valid session token or admin token.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
from backend.services.auth_service import get_auth_service
|
||||
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
# Extract token
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
@@ -344,13 +535,9 @@ async def get_current_user(
|
||||
user.total_jobs_completed >= 2
|
||||
and not user.has_submitted_feedback
|
||||
)
|
||||
user_public = UserPublic(
|
||||
email=user.email,
|
||||
role=user.role if not auth_result.is_admin else UserRole.ADMIN,
|
||||
credits=user.credits,
|
||||
display_name=user.display_name,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
user_public = _build_user_public(
|
||||
user,
|
||||
role_override=UserRole.ADMIN if auth_result.is_admin else None,
|
||||
feedback_eligible=feedback_eligible,
|
||||
)
|
||||
return UserProfileResponse(user=user_public, has_session=True)
|
||||
@@ -359,21 +546,13 @@ async def get_current_user(
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
feedback_eligible = (
|
||||
user.total_jobs_completed >= 2
|
||||
and not user.has_submitted_feedback
|
||||
)
|
||||
user_public = UserPublic(
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
credits=user.credits,
|
||||
display_name=user.display_name,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
feedback_eligible=feedback_eligible,
|
||||
)
|
||||
user_public = _build_user_public(user, feedback_eligible=feedback_eligible)
|
||||
|
||||
return UserProfileResponse(user=user_public, has_session=True)
|
||||
|
||||
@@ -417,9 +596,21 @@ async def create_checkout(
|
||||
if not stripe_service.is_configured():
|
||||
raise HTTPException(status_code=503, detail="Payment processing is not available")
|
||||
|
||||
# Check for referral discount
|
||||
referral_coupon_id = None
|
||||
try:
|
||||
from backend.services.referral_service import get_referral_service
|
||||
referral_svc = get_referral_service()
|
||||
discount_info = referral_svc.get_discount_for_checkout(request.email)
|
||||
if discount_info:
|
||||
referral_coupon_id = discount_info["coupon_id"]
|
||||
except Exception as ref_err:
|
||||
logger.warning(f"Referral discount lookup failed: {ref_err}")
|
||||
|
||||
success, checkout_url, message = stripe_service.create_checkout_session(
|
||||
package_id=request.package_id,
|
||||
user_email=request.email,
|
||||
coupon_id=referral_coupon_id,
|
||||
)
|
||||
|
||||
if not success or not checkout_url:
|
||||
@@ -577,6 +768,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)
|
||||
@@ -883,6 +1079,25 @@ async def stripe_webhook(
|
||||
# Send confirmation email
|
||||
email_service.send_credits_added(user_email, credits, new_balance)
|
||||
logger.info(f"Added {credits} credits to {user_email}, new balance: {new_balance}")
|
||||
|
||||
# Record referral earning if applicable
|
||||
try:
|
||||
from backend.services.referral_service import get_referral_service
|
||||
referral_svc = get_referral_service()
|
||||
amount_charged = session.get("amount_total", 0)
|
||||
if amount_charged > 0:
|
||||
earning_result = referral_svc.record_earning(
|
||||
referred_email=user_email,
|
||||
stripe_session_id=session_id,
|
||||
purchase_amount_cents=amount_charged,
|
||||
)
|
||||
if earning_result:
|
||||
logger.info(
|
||||
f"Referral earning: ${earning_result['earning_amount_cents'] / 100:.2f} "
|
||||
f"for {earning_result['referrer_email']}"
|
||||
)
|
||||
except Exception as ref_err:
|
||||
logger.warning(f"Referral earning recording failed: {ref_err}")
|
||||
else:
|
||||
logger.error(f"Failed to add credits: {credit_msg}")
|
||||
|
||||
@@ -891,8 +1106,11 @@ async def stripe_webhook(
|
||||
if amount_total > 0 and customer_email:
|
||||
try:
|
||||
from google.cloud.firestore_v1 import Increment
|
||||
user_doc_ref = user_service.db.collection("users").document(customer_email.lower().strip())
|
||||
user_doc_ref.update({"total_spent": Increment(amount_total)})
|
||||
user_doc_ref = user_service.get_user_doc_ref(customer_email)
|
||||
if user_doc_ref:
|
||||
user_doc_ref.update({"total_spent": Increment(amount_total)})
|
||||
else:
|
||||
logger.warning(f"No user doc found for {customer_email} to update total_spent")
|
||||
except Exception as spend_err:
|
||||
logger.warning(f"Failed to update total_spent for {customer_email}: {spend_err}")
|
||||
|
||||
@@ -1024,6 +1242,7 @@ async def stripe_webhook(
|
||||
|
||||
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
|
||||
async def check_feedback_eligibility(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -1032,8 +1251,9 @@ async def check_feedback_eligibility(
|
||||
|
||||
Eligible if: total_jobs_completed >= 2 AND has not already submitted feedback.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
@@ -1048,7 +1268,7 @@ async def check_feedback_eligibility(
|
||||
else:
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
eligible = user.total_jobs_completed >= 2 and not user.has_submitted_feedback
|
||||
|
||||
@@ -1056,25 +1276,27 @@ 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,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/feedback", response_model=UserFeedbackResponse)
|
||||
async def submit_user_feedback(
|
||||
http_request: Request,
|
||||
request: UserFeedbackRequest,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
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
|
||||
must have >50 characters.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
@@ -1089,20 +1311,20 @@ async def submit_user_feedback(
|
||||
else:
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
# Check eligibility: must have completed 2+ jobs
|
||||
if user.total_jobs_completed < 2:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="You need to complete at least 2 karaoke videos before submitting feedback."
|
||||
detail=t(locale, "users.feedbackNotEligible")
|
||||
)
|
||||
|
||||
# Check if already submitted
|
||||
if user.has_submitted_feedback:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="You have already submitted feedback. Thank you!"
|
||||
detail=t(locale, "users.feedbackNotEligible")
|
||||
)
|
||||
|
||||
# Validate: at least one text field has >50 characters
|
||||
@@ -1145,8 +1367,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,
|
||||
@@ -1158,6 +1431,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.",
|
||||
@@ -1191,9 +1483,21 @@ 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
|
||||
# Referral fields
|
||||
referred_by_code: Optional[str] = None
|
||||
referral_discount_expires_at: Optional[str] = None
|
||||
referral_code: Optional[str] = None
|
||||
# Recent session details (IP, user agent, fingerprint)
|
||||
recent_sessions: list[dict] = []
|
||||
|
||||
|
||||
@router.get("/admin/users", response_model=UserListResponsePaginated)
|
||||
@@ -1234,6 +1538,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
|
||||
@@ -1241,16 +1546,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', ''))]
|
||||
@@ -1289,12 +1601,14 @@ async def list_users(
|
||||
@router.get("/admin/users/{email}/detail", response_model=UserDetailResponse)
|
||||
async def get_user_detail(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Get detailed user information including credit history and recent jobs (admin only).
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from urllib.parse import unquote
|
||||
@@ -1304,7 +1618,7 @@ async def get_user_detail(
|
||||
|
||||
user = user_service.get_user(email)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
db = user_service.db
|
||||
|
||||
@@ -1330,13 +1644,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 = []
|
||||
@@ -1358,16 +1683,25 @@ 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,
|
||||
referred_by_code=user.referred_by_code,
|
||||
referral_discount_expires_at=user.referral_discount_expires_at.isoformat() if user.referral_discount_expires_at and hasattr(user.referral_discount_expires_at, 'isoformat') else str(user.referral_discount_expires_at) if user.referral_discount_expires_at else None,
|
||||
referral_code=user.referral_code,
|
||||
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),
|
||||
):
|
||||
@@ -1376,12 +1710,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,
|
||||
@@ -1409,19 +1738,20 @@ 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),
|
||||
request: Request,
|
||||
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"
|
||||
locale = get_locale_from_request(request)
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success = user_service.disable_user(email, admin_email=admin_id)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
return {"status": "success", "message": f"User {email} has been disabled"}
|
||||
|
||||
@@ -1429,19 +1759,20 @@ 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),
|
||||
request: Request,
|
||||
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"
|
||||
locale = get_locale_from_request(request)
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success = user_service.enable_user(email, admin_email=admin_id)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
return {"status": "success", "message": f"User {email} has been enabled"}
|
||||
|
||||
@@ -1449,7 +1780,8 @@ async def enable_user(
|
||||
@router.delete("/admin/users/{email}")
|
||||
async def delete_user(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
@@ -1457,8 +1789,8 @@ 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"
|
||||
locale = get_locale_from_request(request)
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
try:
|
||||
success = user_service.delete_user(email, admin_email=admin_id)
|
||||
@@ -1466,7 +1798,7 @@ async def delete_user(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
return {"status": "success", "message": f"User {email} has been deleted"}
|
||||
|
||||
@@ -1475,19 +1807,20 @@ async def delete_user(
|
||||
async def set_user_role(
|
||||
email: str,
|
||||
role: UserRole,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
request: Request,
|
||||
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"
|
||||
locale = get_locale_from_request(request)
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
|
||||
success = user_service.set_user_role(email, role, admin_email=admin_id)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound"))
|
||||
|
||||
return {"status": "success", "message": f"User {email} role set to {role.value}"}
|
||||
|
||||
|
||||
@@ -0,0 +1,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
|
||||
@@ -32,6 +32,10 @@ class Settings(BaseSettings):
|
||||
|
||||
# Authentication
|
||||
admin_tokens: Optional[str] = os.getenv("ADMIN_TOKENS") # Comma-separated list
|
||||
scheduler_service_account: str = os.getenv(
|
||||
"SCHEDULER_SERVICE_ACCOUNT",
|
||||
"karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
|
||||
)
|
||||
|
||||
# Application
|
||||
environment: str = os.getenv("ENVIRONMENT", "development")
|
||||
@@ -57,6 +61,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)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
Lightweight i18n utility for backend translations.
|
||||
|
||||
Usage:
|
||||
from backend.i18n import t, get_locale_from_request, SUPPORTED_LOCALES
|
||||
|
||||
# In a route handler:
|
||||
locale = get_locale_from_request(request)
|
||||
message = t(locale, "auth.userNotFound")
|
||||
message = t(locale, "jobs.notFound", job_id="abc123")
|
||||
"""
|
||||
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from starlette.requests import Request
|
||||
|
||||
SUPPORTED_LOCALES = ("en", "es", "de")
|
||||
DEFAULT_LOCALE = "en"
|
||||
TRANSLATIONS_DIR = Path(__file__).parent / "translations"
|
||||
|
||||
|
||||
@lru_cache(maxsize=len(SUPPORTED_LOCALES))
|
||||
def _load_translations(locale: str) -> dict[str, Any]:
|
||||
"""Load and cache translation file for a locale."""
|
||||
path = TRANSLATIONS_DIR / f"{locale}.json"
|
||||
if not path.exists():
|
||||
if locale != DEFAULT_LOCALE:
|
||||
return _load_translations(DEFAULT_LOCALE)
|
||||
return {}
|
||||
with open(path, encoding="utf-8") as f:
|
||||
result: dict[str, Any] = json.load(f)
|
||||
return result
|
||||
|
||||
|
||||
def t(locale: str, key: str, **kwargs: Any) -> str:
|
||||
"""Get a translated string by dotted key path.
|
||||
|
||||
Args:
|
||||
locale: Language code (en, es, de)
|
||||
key: Dotted path like "auth.userNotFound" or "emails.magicLink.subject"
|
||||
**kwargs: Interpolation variables (e.g., job_id="abc123")
|
||||
|
||||
Returns:
|
||||
Translated string with variables interpolated, or the key itself if not found.
|
||||
"""
|
||||
if locale not in SUPPORTED_LOCALES:
|
||||
locale = DEFAULT_LOCALE
|
||||
|
||||
translations = _load_translations(locale)
|
||||
|
||||
# Walk the dotted path
|
||||
value: Any = translations
|
||||
for part in key.split("."):
|
||||
if isinstance(value, dict) and part in value:
|
||||
value = value[part]
|
||||
else:
|
||||
# Key not found — fall back to English
|
||||
if locale != DEFAULT_LOCALE:
|
||||
return t(DEFAULT_LOCALE, key, **kwargs)
|
||||
return key # Return the key itself as last resort
|
||||
|
||||
if not isinstance(value, str):
|
||||
return key
|
||||
|
||||
result: str = value
|
||||
# Interpolate variables
|
||||
if kwargs:
|
||||
try:
|
||||
result = result.format(**kwargs)
|
||||
except KeyError:
|
||||
pass # Missing variable — return template as-is
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_locale_from_request(request: Request) -> str:
|
||||
"""Extract locale from Accept-Language header.
|
||||
|
||||
Returns the first supported locale found, or DEFAULT_LOCALE.
|
||||
"""
|
||||
accept_lang = request.headers.get("accept-language", "")
|
||||
|
||||
# Simple parsing — Accept-Language can be "de", "de-DE", "en-US,en;q=0.9,de;q=0.8"
|
||||
for part in accept_lang.split(","):
|
||||
lang = part.split(";")[0].strip().split("-")[0].lower()
|
||||
if lang in SUPPORTED_LOCALES:
|
||||
return lang
|
||||
|
||||
return DEFAULT_LOCALE
|
||||
|
||||
|
||||
def get_locale_prefix(locale: str) -> str:
|
||||
"""Get URL locale prefix for frontend URLs (e.g., '/en', '/es')."""
|
||||
if locale not in SUPPORTED_LOCALES:
|
||||
locale = DEFAULT_LOCALE
|
||||
return f"/{locale}"
|
||||
+8
-3
@@ -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,11 +153,14 @@ 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)
|
||||
app.include_router(themes.router, prefix="/api") # Theme selection for styles
|
||||
app.include_router(users.router, prefix="/api") # User auth, credits, and Stripe webhooks
|
||||
from backend.api.routes import referrals
|
||||
app.include_router(referrals.router, prefix="/api") # Referral links and payouts
|
||||
app.include_router(admin.router, prefix="/api") # Admin dashboard and management
|
||||
app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management
|
||||
app.include_router(push.router, prefix="/api") # Push notification subscription management
|
||||
@@ -169,18 +172,20 @@ app.include_router(tenant.router) # Tenant/white-label configuration (no /api p
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
|
||||
@app.exception_handler(InsufficientCreditsError)
|
||||
async def insufficient_credits_exception_handler(request: Request, exc: InsufficientCreditsError):
|
||||
"""Handle insufficient credits errors with 402 Payment Required status."""
|
||||
locale = get_locale_from_request(request)
|
||||
return JSONResponse(
|
||||
status_code=402,
|
||||
content={
|
||||
"detail": exc.message,
|
||||
"detail": t(locale, "errors.insufficientCredits"),
|
||||
"credits_available": exc.credits_available,
|
||||
"credits_required": exc.credits_required,
|
||||
"buy_url": "/#pricing",
|
||||
"buy_url": t(locale, "errors.insufficientCreditsBuyUrl"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
"""
|
||||
Referral system models.
|
||||
|
||||
Supports:
|
||||
- Referral link creation and management
|
||||
- Earnings tracking from referred purchases
|
||||
- Payout processing via Stripe Connect
|
||||
- API request/response shapes for referral endpoints
|
||||
"""
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Firestore Document Models
|
||||
# ============================================================================
|
||||
|
||||
class ReferralLinkStats(BaseModel):
|
||||
"""Aggregated statistics for a referral link."""
|
||||
clicks: int = 0
|
||||
signups: int = 0
|
||||
purchases: int = 0
|
||||
total_earned_cents: int = 0
|
||||
|
||||
|
||||
class ReferralLink(BaseModel):
|
||||
"""
|
||||
Referral link stored in Firestore.
|
||||
|
||||
Each user can have one referral link. Vanity links use a custom code
|
||||
(e.g., "karaoke-king") while standard links use a generated code.
|
||||
"""
|
||||
code: str # Unique referral code (URL slug)
|
||||
owner_email: str # Email of the referrer
|
||||
display_name: Optional[str] = None # Public name shown on interstitial
|
||||
custom_message: Optional[str] = None # Optional message on interstitial
|
||||
|
||||
# Reward configuration
|
||||
discount_percent: int = 10 # Discount for referred user
|
||||
kickback_percent: int = 20 # Earnings for referrer
|
||||
discount_duration_days: int = 30 # How long the discount lasts
|
||||
earning_duration_days: int = 365 # How long referrer earns from this link
|
||||
|
||||
# Stripe
|
||||
stripe_coupon_id: Optional[str] = None # Stripe coupon for this link
|
||||
|
||||
# Flags
|
||||
is_vanity: bool = False # Custom vanity code vs generated
|
||||
enabled: bool = True # Can be disabled without deleting
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
# Aggregated stats
|
||||
stats: ReferralLinkStats = Field(default_factory=ReferralLinkStats)
|
||||
|
||||
|
||||
class ReferralEarning(BaseModel):
|
||||
"""
|
||||
Record of a single earning from a referred purchase.
|
||||
|
||||
Created when a referred user completes a Stripe checkout.
|
||||
"""
|
||||
id: str
|
||||
referrer_email: str
|
||||
referred_email: str
|
||||
referral_code: str
|
||||
stripe_session_id: str
|
||||
purchase_amount_cents: int
|
||||
earning_amount_cents: int
|
||||
status: str = "pending" # pending, paid, cancelled
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
paid_at: Optional[datetime] = None
|
||||
payout_id: Optional[str] = None
|
||||
|
||||
|
||||
class ReferralPayout(BaseModel):
|
||||
"""
|
||||
Record of a payout to a referrer via Stripe Connect.
|
||||
|
||||
Groups multiple earnings into a single transfer.
|
||||
"""
|
||||
id: str
|
||||
referrer_email: str
|
||||
stripe_transfer_id: str
|
||||
amount_cents: int
|
||||
earnings_included: List[str] # List of ReferralEarning IDs
|
||||
status: str = "processing" # processing, completed, failed
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# API Request Models
|
||||
# ============================================================================
|
||||
|
||||
class CreateReferralLinkRequest(BaseModel):
|
||||
"""Admin request to create a vanity referral link."""
|
||||
vanity_code: Optional[str] = None
|
||||
owner_email: str
|
||||
display_name: Optional[str] = None
|
||||
custom_message: Optional[str] = None
|
||||
discount_percent: int = 10
|
||||
kickback_percent: int = 20
|
||||
discount_duration_days: int = 30
|
||||
earning_duration_days: int = 365
|
||||
|
||||
|
||||
class UpdateReferralLinkRequest(BaseModel):
|
||||
"""Request to update a referral link (user: name/message only, admin: all fields)."""
|
||||
display_name: Optional[str] = None
|
||||
custom_message: Optional[str] = None
|
||||
discount_percent: Optional[int] = None
|
||||
kickback_percent: Optional[int] = None
|
||||
discount_duration_days: Optional[int] = None
|
||||
earning_duration_days: Optional[int] = None
|
||||
enabled: Optional[bool] = None
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# API Response Models
|
||||
# ============================================================================
|
||||
|
||||
class ReferralLinkResponse(BaseModel):
|
||||
"""Public referral link information."""
|
||||
code: str
|
||||
owner_email: str
|
||||
display_name: Optional[str] = None
|
||||
custom_message: Optional[str] = None
|
||||
discount_percent: int
|
||||
kickback_percent: int
|
||||
is_vanity: bool
|
||||
enabled: bool
|
||||
stats: ReferralLinkStats
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ReferralEarningResponse(BaseModel):
|
||||
"""Public earning information (for referrer dashboard)."""
|
||||
id: str
|
||||
referred_email: str
|
||||
referral_code: str
|
||||
purchase_amount_cents: int
|
||||
earning_amount_cents: int
|
||||
status: str
|
||||
created_at: datetime
|
||||
paid_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class ReferralPayoutResponse(BaseModel):
|
||||
"""Public payout information (for referrer dashboard)."""
|
||||
id: str
|
||||
amount_cents: int
|
||||
earnings_count: int
|
||||
status: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ReferralDashboardResponse(BaseModel):
|
||||
"""Full referral dashboard data for the referrer."""
|
||||
referral_link: ReferralLinkResponse
|
||||
recent_earnings: List[ReferralEarningResponse]
|
||||
recent_payouts: List[ReferralPayoutResponse]
|
||||
total_earned_cents: int
|
||||
total_paid_cents: int
|
||||
pending_balance_cents: int
|
||||
stripe_connect_onboarded: bool
|
||||
|
||||
|
||||
class ReferralInterstitialResponse(BaseModel):
|
||||
"""Data for the referral landing/interstitial page."""
|
||||
valid: bool = True
|
||||
referral_code: str = ""
|
||||
referrer_display_name: Optional[str] = None
|
||||
discount_percent: int = 0
|
||||
discount_duration_days: int = 0
|
||||
custom_message: Optional[str] = None
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
+43
-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
|
||||
|
||||
@@ -86,6 +91,9 @@ class User(BaseModel):
|
||||
# Optional profile fields for future use
|
||||
display_name: Optional[str] = None
|
||||
|
||||
# i18n locale preference (set from Accept-Language on login, used for emails/push)
|
||||
locale: Optional[str] = None
|
||||
|
||||
# Push notification subscriptions (Web Push API)
|
||||
# Users can subscribe from multiple devices/browsers
|
||||
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
|
||||
@@ -93,6 +101,20 @@ 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
|
||||
|
||||
# Referral system
|
||||
referral_code: Optional[str] = None # User's own referral code
|
||||
referred_by_code: Optional[str] = None # Code used when this user signed up
|
||||
referred_at: Optional[datetime] = None # When the referral was applied
|
||||
referral_discount_expires_at: Optional[datetime] = None # When referral discount ends
|
||||
stripe_connect_account_id: Optional[str] = None # For receiving referral payouts
|
||||
|
||||
|
||||
class MagicLinkToken(BaseModel):
|
||||
"""
|
||||
@@ -112,10 +134,19 @@ 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
|
||||
|
||||
# Referral attribution (travels with magic link for cross-device support)
|
||||
referral_code: 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 +164,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 +176,8 @@ class Session(BaseModel):
|
||||
class SendMagicLinkRequest(BaseModel):
|
||||
"""Request to send a magic link email."""
|
||||
email: str
|
||||
device_fingerprint: Optional[str] = None
|
||||
referral_code: Optional[str] = None # From referral interstitial
|
||||
|
||||
|
||||
class SendMagicLinkResponse(BaseModel):
|
||||
@@ -164,6 +198,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):
|
||||
@@ -177,6 +213,11 @@ class UserPublic(BaseModel):
|
||||
tenant_id: Optional[str] = None
|
||||
feedback_eligible: bool = False
|
||||
total_spent: int = 0
|
||||
referral_code: Optional[str] = None
|
||||
has_active_referral_discount: bool = False
|
||||
referral_discount_percent: Optional[int] = None
|
||||
referral_discount_expires_at: Optional[str] = None # ISO string
|
||||
referred_by_code: Optional[str] = None
|
||||
created_at: Optional[str] = None
|
||||
last_login_at: Optional[str] = None
|
||||
|
||||
@@ -212,7 +253,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 +308,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}")
|
||||
@@ -3,6 +3,7 @@ Authentication service for karaoke backend.
|
||||
|
||||
Provides token-based authentication with support for:
|
||||
- Admin tokens (hardcoded in environment)
|
||||
- Google OIDC tokens (from Cloud Scheduler / Cloud Tasks service accounts)
|
||||
- Admin by email domain (@nomadkaraoke.com)
|
||||
- User tokens (stored in Firestore auth_tokens collection)
|
||||
- Session tokens (stored in Firestore sessions collection, from magic link auth)
|
||||
@@ -19,6 +20,9 @@ from enum import Enum
|
||||
from typing import Optional, Tuple, Dict, Any, List
|
||||
from datetime import datetime
|
||||
|
||||
from google.auth.transport import requests as google_auth_requests
|
||||
from google.oauth2 import id_token as google_id_token
|
||||
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.config import get_settings
|
||||
from backend.models.user import UserRole
|
||||
@@ -72,6 +76,7 @@ class AuthService:
|
||||
self.firestore = FirestoreService()
|
||||
self.settings = get_settings()
|
||||
self._init_admin_tokens()
|
||||
self._scheduler_service_account = self.settings.scheduler_service_account
|
||||
|
||||
def _init_admin_tokens(self):
|
||||
"""Load admin tokens from environment variables."""
|
||||
@@ -83,6 +88,56 @@ class AuthService:
|
||||
logger.info(f"Loaded {len(self.admin_tokens)} admin token(s)")
|
||||
else:
|
||||
logger.warning("No admin tokens configured! Set ADMIN_TOKENS environment variable.")
|
||||
|
||||
def _validate_oidc_token(self, token: str) -> Optional[AuthResult]:
|
||||
"""
|
||||
Validate a Google OIDC token (from Cloud Scheduler or Cloud Tasks).
|
||||
|
||||
Returns AuthResult if token is a valid Google OIDC JWT from an allowed
|
||||
service account, None if the token is not a JWT or validation fails.
|
||||
"""
|
||||
# Quick check: JWTs have 3 dot-separated parts
|
||||
if token.count('.') != 2:
|
||||
return None
|
||||
|
||||
try:
|
||||
# Verify the token signature and claims with Google
|
||||
# audience=None skips audience check — Cloud Scheduler sets audience
|
||||
# to the endpoint URL, which varies per endpoint
|
||||
claims = google_id_token.verify_oauth2_token(
|
||||
token,
|
||||
google_auth_requests.Request(),
|
||||
audience=None,
|
||||
)
|
||||
|
||||
token_email = claims.get("email", "")
|
||||
|
||||
# Only accept tokens from the configured service account
|
||||
if token_email != self._scheduler_service_account:
|
||||
logger.warning(
|
||||
f"OIDC token from unexpected service account: {token_email} "
|
||||
f"(expected {self._scheduler_service_account})"
|
||||
)
|
||||
return None
|
||||
|
||||
logger.info(f"OIDC token validated for service account: {token_email}")
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=-1,
|
||||
message="OIDC service account access granted",
|
||||
user_email=token_email,
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
except ValueError as e:
|
||||
# verify_oauth2_token raises ValueError for invalid/expired tokens
|
||||
logger.debug(f"OIDC token validation failed: {e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
# Network errors fetching Google certs, etc.
|
||||
logger.warning(f"OIDC token verification error: {e}")
|
||||
return None
|
||||
|
||||
def validate_token(self, token: str) -> Tuple[bool, UserType, int, str]:
|
||||
"""
|
||||
@@ -213,6 +268,12 @@ class AuthService:
|
||||
is_admin=True
|
||||
)
|
||||
|
||||
# Check for Google OIDC tokens (Cloud Scheduler / Cloud Tasks)
|
||||
# Done before Firestore lookup to avoid wasting a read on JWT strings
|
||||
oidc_result = self._validate_oidc_token(token)
|
||||
if oidc_result is not None:
|
||||
return oidc_result
|
||||
|
||||
# Check stored tokens in Firestore (auth_tokens collection)
|
||||
token_data = self.firestore.get_token(token)
|
||||
|
||||
|
||||
@@ -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
|
||||
+633
-101
File diff suppressed because it is too large.
Load diff
@@ -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,30 @@ 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
|
||||
allowlisted = set()
|
||||
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,
|
||||
"allowlisted_domains": allowlisted,
|
||||
"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(),
|
||||
"allowlisted_domains": set(),
|
||||
"blocked_emails": set(),
|
||||
"blocked_ips": set(),
|
||||
"verified_clean_domains": {},
|
||||
}
|
||||
|
||||
# Update cache
|
||||
@@ -316,6 +240,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 +260,194 @@ 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 1.5: Explicitly allowlisted domains skip external API checks.
|
||||
# Without this, external APIs can override admin allowlist decisions
|
||||
# (e.g. inbox.testmail.app is a legitimate testing domain we allow).
|
||||
if domain in config.get("allowlisted_domains", set()):
|
||||
return False
|
||||
|
||||
# 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 +518,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 +552,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 +726,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."""
|
||||
@@ -86,6 +115,28 @@ class EncodingService:
|
||||
"""Check if GCE preview encoding is enabled and configured."""
|
||||
return self.settings.use_gce_preview_encoding and self.is_configured
|
||||
|
||||
def _warmup_encoding_worker_fallback(self, job_id: str) -> None:
|
||||
"""Safety net: try to start the encoding worker VM on first connection failure.
|
||||
|
||||
If the worker_manager is available, calls ensure_primary_running() so the VM
|
||||
starts booting during the retry window. If worker_manager is not set (e.g. dev
|
||||
mode with static URL), this is a no-op.
|
||||
"""
|
||||
if not self._worker_manager:
|
||||
return
|
||||
try:
|
||||
result = self._worker_manager.ensure_primary_running()
|
||||
if result["started"]:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Encoding worker unreachable — started VM {result['vm_name']} as fallback"
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Encoding worker unreachable — VM {result['vm_name']} already running/starting"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): {e}")
|
||||
|
||||
async def _request_with_retry(
|
||||
self,
|
||||
method: str,
|
||||
@@ -147,6 +198,8 @@ class EncodingService:
|
||||
}
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
|
||||
last_exception = e
|
||||
if attempt == 0:
|
||||
self._warmup_encoding_worker_fallback(job_id)
|
||||
if attempt < MAX_RETRIES:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] GCE worker connection failed (attempt {attempt + 1}/{MAX_RETRIES + 1}): {e}. "
|
||||
@@ -188,7 +241,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 +302,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 +490,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,
|
||||
@@ -531,6 +584,116 @@ class EncodingService:
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
async def submit_render_video_job(
|
||||
self,
|
||||
job_id: str,
|
||||
render_config: Dict[str, Any],
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Submit a render-video job to the GCE worker.
|
||||
|
||||
Args:
|
||||
job_id: Unique job identifier
|
||||
render_config: Configuration dict containing original_corrections_gcs_path,
|
||||
audio_gcs_path, output_gcs_prefix, artist, title, and any other render params.
|
||||
|
||||
Returns:
|
||||
Response from the encoding worker
|
||||
|
||||
Raises:
|
||||
RuntimeError: If submission fails
|
||||
"""
|
||||
self._load_credentials()
|
||||
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
url = f"{self._get_worker_url()}/render-video"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {"job_id": job_id, **render_config}
|
||||
|
||||
logger.info(f"[job:{job_id}] Submitting render-video job to GCE worker: {url}")
|
||||
|
||||
resp = await self._request_with_retry(
|
||||
method="POST",
|
||||
url=url,
|
||||
headers=headers,
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp["status"] == 409:
|
||||
# Job already exists on worker — check if it already completed
|
||||
logger.warning(f"[job:{job_id}] GCE worker returned 409, checking job status")
|
||||
try:
|
||||
status = await self.get_job_status(job_id)
|
||||
job_status = status.get("status", "unknown")
|
||||
if job_status == "complete":
|
||||
logger.info(f"[job:{job_id}] Render-video job already complete on GCE worker, returning cached result")
|
||||
return {
|
||||
"status": "cached",
|
||||
"job_id": job_id,
|
||||
"output_files": status.get("output_files"),
|
||||
"metadata": status.get("metadata"),
|
||||
}
|
||||
elif job_status in ("pending", "running"):
|
||||
logger.info(f"[job:{job_id}] Render-video job still in progress on GCE worker")
|
||||
return {"status": "in_progress", "job_id": job_id}
|
||||
else:
|
||||
raise RuntimeError(f"Render-video job {job_id} already exists with status: {job_status}")
|
||||
except RuntimeError as e:
|
||||
if "not found" in str(e).lower():
|
||||
raise RuntimeError(f"Render-video job {job_id} conflict: 409 but job not found on status check")
|
||||
raise
|
||||
if resp["status"] != 200:
|
||||
raise RuntimeError(f"Failed to submit render-video job: {resp['status']} - {resp['text']}")
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def render_video_on_gce(
|
||||
self,
|
||||
job_id: str,
|
||||
render_config: Dict[str, Any],
|
||||
progress_callback=None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Submit render-video job and wait for completion.
|
||||
|
||||
This is a convenience method that combines submit + wait.
|
||||
|
||||
Args:
|
||||
job_id: Unique job identifier
|
||||
render_config: Configuration dict for the render-video worker endpoint
|
||||
progress_callback: Optional callback for progress updates
|
||||
|
||||
Returns:
|
||||
Final job status with output files and metadata
|
||||
"""
|
||||
# Submit the job
|
||||
submit_result = await self.submit_render_video_job(job_id, render_config)
|
||||
|
||||
# If cached, return immediately — rendering already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Render-video already cached, returning immediately")
|
||||
return {
|
||||
"status": "complete",
|
||||
"output_files": submit_result.get("output_files"),
|
||||
"metadata": submit_result.get("metadata"),
|
||||
}
|
||||
|
||||
# If in_progress, another request is rendering it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
|
||||
|
||||
# Wait for completion
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback
|
||||
)
|
||||
|
||||
async def health_check(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Check the health of the encoding worker.
|
||||
@@ -543,7 +706,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 +728,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.
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Service for generating personalized referral flyer PDFs."""
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), "..", "templates", "printables")
|
||||
|
||||
CHROMIUM_PATHS = [
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
"/usr/bin/google-chrome",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
]
|
||||
|
||||
VALID_THEMES = {"light", "dark"}
|
||||
MAX_QR_DATA_URL_BYTES = 500_000
|
||||
|
||||
|
||||
class FlyerError(Exception):
|
||||
"""Error during flyer generation."""
|
||||
|
||||
|
||||
class FlyerService:
|
||||
"""Generates personalized referral flyer PDFs."""
|
||||
|
||||
def __init__(self):
|
||||
self._chromium_path: str | None = None
|
||||
|
||||
def _get_chromium(self) -> str:
|
||||
"""Lazily find Chromium binary. Only needed when generating PDFs."""
|
||||
if self._chromium_path:
|
||||
return self._chromium_path
|
||||
for path in CHROMIUM_PATHS:
|
||||
if os.path.exists(path):
|
||||
self._chromium_path = path
|
||||
return path
|
||||
for name in ["chromium", "chromium-browser", "google-chrome"]:
|
||||
found = shutil.which(name)
|
||||
if found:
|
||||
self._chromium_path = found
|
||||
return found
|
||||
raise FlyerError("Chromium not found. Install chromium to generate flyer PDFs.")
|
||||
|
||||
def _validate_qr_data_url(self, qr_data_url: str) -> None:
|
||||
if not qr_data_url.startswith("data:image/"):
|
||||
raise FlyerError("Invalid QR data URL: must be a data:image/ URL")
|
||||
if len(qr_data_url) > MAX_QR_DATA_URL_BYTES:
|
||||
raise FlyerError(f"QR data URL too large (>{MAX_QR_DATA_URL_BYTES} bytes)")
|
||||
|
||||
def _render_template(
|
||||
self,
|
||||
theme: str,
|
||||
referral_code: str,
|
||||
discount_percent: int,
|
||||
qr_data_url: str,
|
||||
) -> str:
|
||||
if theme not in VALID_THEMES:
|
||||
raise FlyerError(f"Invalid theme: {theme}. Must be one of: {VALID_THEMES}")
|
||||
|
||||
suffix = "-dark" if theme == "dark" else ""
|
||||
template_path = os.path.join(TEMPLATE_DIR, f"website-referral-flyer{suffix}.html")
|
||||
|
||||
with open(template_path) as f:
|
||||
html = f.read()
|
||||
|
||||
html = html.replace("{{REFERRAL_CODE}}", referral_code.upper())
|
||||
html = html.replace("{{REFERRAL_CODE_LOWER}}", referral_code.lower())
|
||||
html = html.replace("{{DISCOUNT_PERCENT}}", str(discount_percent))
|
||||
html = html.replace("{{QR_DATA_URL}}", qr_data_url)
|
||||
|
||||
return html
|
||||
|
||||
def generate_pdf(
|
||||
self,
|
||||
theme: str,
|
||||
referral_code: str,
|
||||
discount_percent: int,
|
||||
qr_data_url: str,
|
||||
) -> bytes:
|
||||
"""Generate a personalized flyer PDF. Returns raw PDF bytes."""
|
||||
self._validate_qr_data_url(qr_data_url)
|
||||
html = self._render_template(theme, referral_code, discount_percent, qr_data_url)
|
||||
|
||||
with tempfile.NamedTemporaryFile(
|
||||
suffix=".html", delete=False, mode="w", encoding="utf-8"
|
||||
) as tmp_html:
|
||||
tmp_html.write(html)
|
||||
tmp_html_path = tmp_html.name
|
||||
|
||||
tmp_pdf_path = tmp_html_path.replace(".html", ".pdf")
|
||||
|
||||
try:
|
||||
cmd = [
|
||||
self._get_chromium(),
|
||||
"--headless",
|
||||
f"--print-to-pdf={tmp_pdf_path}",
|
||||
"--no-margins",
|
||||
"--print-background",
|
||||
"--no-pdf-header-footer",
|
||||
"--virtual-time-budget=5000",
|
||||
"--paper-width=8.5",
|
||||
"--paper-height=11",
|
||||
"--disable-gpu",
|
||||
"--no-sandbox",
|
||||
tmp_html_path,
|
||||
]
|
||||
|
||||
result = subprocess.run(
|
||||
cmd, capture_output=True, text=True, timeout=30
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
logger.error("Chromium PDF generation failed: %s", result.stderr)
|
||||
raise FlyerError(f"PDF generation failed: {result.stderr[:200]}")
|
||||
|
||||
if not os.path.exists(tmp_pdf_path):
|
||||
raise FlyerError("PDF generation failed: no output file created")
|
||||
|
||||
with open(tmp_pdf_path, "rb") as f:
|
||||
return f.read()
|
||||
|
||||
finally:
|
||||
for path in [tmp_html_path, tmp_pdf_path]:
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
_flyer_service = None
|
||||
|
||||
|
||||
def get_flyer_service() -> FlyerService:
|
||||
global _flyer_service
|
||||
if _flyer_service is None:
|
||||
_flyer_service = FlyerService()
|
||||
return _flyer_service
|
||||
@@ -1,9 +1,11 @@
|
||||
import asyncio
|
||||
import glob as glob_module
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -59,12 +61,27 @@ class EncodePreviewRequest(BaseModel):
|
||||
font_gcs_path: Optional[str] = None # gs://bucket/path/to/custom-font.ttf
|
||||
|
||||
|
||||
class RenderVideoRequest(BaseModel):
|
||||
job_id: str
|
||||
original_corrections_gcs_path: str
|
||||
updated_corrections_gcs_path: Optional[str] = None
|
||||
audio_gcs_path: str
|
||||
style_params_gcs_path: Optional[str] = None
|
||||
style_assets: Optional[dict] = None
|
||||
output_gcs_prefix: str
|
||||
artist: str
|
||||
title: str
|
||||
subtitle_offset_ms: int = 0
|
||||
video_resolution: str = "4k"
|
||||
|
||||
|
||||
class JobStatus(BaseModel):
|
||||
job_id: str
|
||||
status: str # pending, running, complete, failed
|
||||
progress: int # 0-100
|
||||
error: Optional[str] = None
|
||||
output_files: Optional[list[str]] = None
|
||||
metadata: Optional[dict] = None
|
||||
|
||||
|
||||
def download_from_gcs(gcs_uri: str, local_path: Path):
|
||||
@@ -136,6 +153,59 @@ def upload_single_file_to_gcs(local_path: Path, gcs_uri: str):
|
||||
logger.info(f"Uploaded: {local_path} -> {gcs_uri}")
|
||||
|
||||
|
||||
# Style asset disk cache directory
|
||||
# Persists across jobs to avoid re-downloading the same theme assets (fonts, backgrounds)
|
||||
STYLE_CACHE_DIR = Path("/var/cache/karaoke-gen/styles")
|
||||
|
||||
|
||||
def download_with_cache(gcs_uri: str, local_path: Path, cache_dir: Optional[Path] = STYLE_CACHE_DIR):
|
||||
"""Download a file from GCS, using a local disk cache to skip repeated downloads.
|
||||
|
||||
Cache key is SHA-256 of the GCS URI. Cache hits are validated by comparing
|
||||
the cached file size against the GCS object size (via a lightweight metadata
|
||||
call). On size mismatch the stale entry is replaced.
|
||||
When cache_dir is None, downloads directly (no caching).
|
||||
"""
|
||||
if cache_dir is None:
|
||||
download_single_file_from_gcs(gcs_uri, local_path)
|
||||
return
|
||||
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache_key = hashlib.sha256(gcs_uri.encode()).hexdigest()
|
||||
cached_path = cache_dir / cache_key
|
||||
|
||||
if cached_path.exists():
|
||||
# Validate cached file against GCS object size
|
||||
try:
|
||||
parts = gcs_uri.replace("gs://", "").split("/", 1)
|
||||
bucket_name = parts[0]
|
||||
blob_name = parts[1] if len(parts) > 1 else ""
|
||||
blob = storage_client.bucket(bucket_name).blob(blob_name)
|
||||
blob.reload() # Fetch metadata (lightweight HEAD request)
|
||||
gcs_size = blob.size
|
||||
|
||||
cached_size = cached_path.stat().st_size
|
||||
if gcs_size is not None and cached_size != gcs_size:
|
||||
logger.warning(
|
||||
f"Cache stale for {gcs_uri}: cached={cached_size}B, GCS={gcs_size}B. Re-downloading."
|
||||
)
|
||||
cached_path.unlink()
|
||||
else:
|
||||
logger.info(f"Cache hit for {gcs_uri} -> {cached_path}")
|
||||
shutil.copy2(str(cached_path), str(local_path))
|
||||
return
|
||||
except Exception as e:
|
||||
# On transient GCS errors, serve from cache rather than failing the job
|
||||
logger.warning(f"Cache validation failed for {gcs_uri}: {e}. Serving from cache.")
|
||||
shutil.copy2(str(cached_path), str(local_path))
|
||||
return
|
||||
|
||||
logger.info(f"Cache miss for {gcs_uri}, downloading...")
|
||||
download_single_file_from_gcs(gcs_uri, local_path)
|
||||
# Store in cache
|
||||
shutil.copy2(str(local_path), str(cached_path))
|
||||
|
||||
|
||||
def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewRequest"):
|
||||
# Run FFmpeg encoding for preview video (480x270, fast settings)
|
||||
jobs[job_id]["status"] = "running"
|
||||
@@ -239,6 +309,192 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
|
||||
raise
|
||||
|
||||
|
||||
def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest"):
|
||||
"""Run video rendering using OutputGenerator from the karaoke-gen wheel.
|
||||
|
||||
Downloads corrections, audio, and style assets from GCS, runs OutputGenerator
|
||||
to produce with_vocals.mkv and subtitle files, then uploads results.
|
||||
Style assets use disk cache to avoid repeated downloads of the same theme.
|
||||
|
||||
This mirrors the logic in render_video_worker.py but runs on the GCE VM
|
||||
instead of Cloud Run, providing more memory and CPU for ffmpeg/libass.
|
||||
"""
|
||||
jobs[job_id]["status"] = "running"
|
||||
jobs[job_id]["progress"] = 5
|
||||
|
||||
try:
|
||||
# Import from installed karaoke-gen wheel
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
from karaoke_gen.style_loader import load_styles_from_gcs
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
# 1. Download original corrections
|
||||
corrections_path = work_dir / "corrections.json"
|
||||
download_single_file_from_gcs(request.original_corrections_gcs_path, corrections_path)
|
||||
jobs[job_id]["progress"] = 15
|
||||
|
||||
with open(corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# 2. Apply user corrections if available
|
||||
if request.updated_corrections_gcs_path:
|
||||
updated_path = work_dir / "corrections_updated.json"
|
||||
download_single_file_from_gcs(request.updated_corrections_gcs_path, updated_path)
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
if isinstance(updated_data, dict) and "corrections" in updated_data:
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
logger.info(f"[job:{job_id}] Applied user corrections")
|
||||
else:
|
||||
logger.warning(f"[job:{job_id}] corrections_updated.json exists but has no 'corrections' key, using base result")
|
||||
correction_result = base_result
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
jobs[job_id]["progress"] = 25
|
||||
|
||||
# 3. Download audio
|
||||
audio_path = work_dir / "audio.flac"
|
||||
download_single_file_from_gcs(request.audio_gcs_path, audio_path)
|
||||
jobs[job_id]["progress"] = 35
|
||||
|
||||
# 4. Process countdown intro
|
||||
countdown_processor = CountdownProcessor(cache_dir=str(work_dir), logger=logger)
|
||||
correction_result, audio_path_str, padding_added, padding_seconds = countdown_processor.process(
|
||||
correction_result=correction_result,
|
||||
audio_filepath=str(audio_path),
|
||||
)
|
||||
audio_path = Path(audio_path_str)
|
||||
jobs[job_id]["progress"] = 40
|
||||
|
||||
# 5. Download style assets (with disk cache for repeated themes)
|
||||
def cached_download(gcs_path, local_path):
|
||||
download_with_cache(gcs_path, Path(local_path), STYLE_CACHE_DIR)
|
||||
|
||||
styles_path, style_data = load_styles_from_gcs(
|
||||
style_params_gcs_path=request.style_params_gcs_path,
|
||||
style_assets=request.style_assets,
|
||||
temp_dir=str(work_dir),
|
||||
download_func=cached_download,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
# Register any downloaded fonts with fontconfig
|
||||
for asset_key, gcs_path in (request.style_assets or {}).items():
|
||||
if 'font' in asset_key.lower() and gcs_path.endswith(('.ttf', '.otf', '.woff', '.woff2')):
|
||||
fonts_dir = Path("/usr/local/share/fonts/custom")
|
||||
fonts_dir.mkdir(parents=True, exist_ok=True)
|
||||
font_filename = gcs_path.split("/")[-1]
|
||||
font_dest = fonts_dir / font_filename
|
||||
if not font_dest.exists():
|
||||
ext = os.path.splitext(gcs_path)[1]
|
||||
style_font = work_dir / "style" / f"{asset_key}{ext}"
|
||||
if style_font.exists():
|
||||
shutil.copy2(str(style_font), str(font_dest))
|
||||
subprocess.run(["fc-cache", "-fv"], capture_output=True)
|
||||
logger.info(f"Registered font: {font_filename}")
|
||||
|
||||
jobs[job_id]["progress"] = 50
|
||||
|
||||
# 6. Configure and run OutputGenerator
|
||||
output_dir = work_dir / "output"
|
||||
cache_dir = work_dir / "cache"
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
cache_dir.mkdir(exist_ok=True)
|
||||
|
||||
config = OutputConfig(
|
||||
output_dir=str(output_dir),
|
||||
cache_dir=str(cache_dir),
|
||||
output_styles_json=styles_path,
|
||||
render_video=True,
|
||||
generate_cdg=False,
|
||||
generate_plain_text=True,
|
||||
generate_lrc=True,
|
||||
video_resolution=request.video_resolution,
|
||||
subtitle_offset_ms=request.subtitle_offset_ms,
|
||||
)
|
||||
|
||||
output_generator = OutputGenerator(config, logger)
|
||||
|
||||
safe_artist = sanitize_filename(request.artist) if request.artist else "Unknown"
|
||||
safe_title = sanitize_filename(request.title) if request.title else "Unknown"
|
||||
output_prefix = f"{safe_artist} - {safe_title}"
|
||||
|
||||
logger.info(f"[job:{job_id}] Generating outputs with prefix '{output_prefix}'")
|
||||
jobs[job_id]["progress"] = 55
|
||||
|
||||
outputs = output_generator.generate_outputs(
|
||||
transcription_corrected=correction_result,
|
||||
lyrics_results={},
|
||||
output_prefix=output_prefix,
|
||||
audio_filepath=str(audio_path),
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
)
|
||||
|
||||
jobs[job_id]["progress"] = 85
|
||||
|
||||
# 7. Upload outputs to GCS
|
||||
output_prefix_gcs = request.output_gcs_prefix.rstrip("/")
|
||||
output_files = []
|
||||
|
||||
if outputs.video and os.path.exists(outputs.video):
|
||||
gcs_path = f"{output_prefix_gcs}/videos/with_vocals.mkv"
|
||||
upload_single_file_to_gcs(Path(outputs.video), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
logger.info(f"[job:{job_id}] Uploaded with_vocals.mkv ({os.path.getsize(outputs.video)} bytes)")
|
||||
else:
|
||||
raise RuntimeError("Video generation failed - no output file produced")
|
||||
|
||||
if outputs.ass and os.path.exists(outputs.ass):
|
||||
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.ass"
|
||||
upload_single_file_to_gcs(Path(outputs.ass), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
|
||||
if outputs.lrc and os.path.exists(outputs.lrc):
|
||||
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.lrc"
|
||||
upload_single_file_to_gcs(Path(outputs.lrc), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
|
||||
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
|
||||
gcs_path = f"{output_prefix_gcs}/lyrics/corrected.txt"
|
||||
upload_single_file_to_gcs(Path(outputs.corrected_txt), gcs_path)
|
||||
output_files.append(gcs_path)
|
||||
|
||||
jobs[job_id]["progress"] = 95
|
||||
jobs[job_id]["output_files"] = output_files
|
||||
jobs[job_id]["metadata"] = {
|
||||
"countdown_padding_added": padding_added,
|
||||
"countdown_padding_seconds": padding_seconds if padding_added else 0,
|
||||
}
|
||||
|
||||
logger.info(f"[job:{job_id}] Render video complete. Output files: {output_files}")
|
||||
|
||||
except ImportError as e:
|
||||
error_msg = (
|
||||
f"OutputGenerator not available: {e}. "
|
||||
"The karaoke-gen wheel must be installed. "
|
||||
"Check that ensure_latest_wheel() succeeded."
|
||||
)
|
||||
logger.error(error_msg)
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = error_msg
|
||||
raise RuntimeError(error_msg) from e
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Render video failed: {e}")
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
raise
|
||||
|
||||
|
||||
def ensure_latest_wheel():
|
||||
'''Download and install latest karaoke-gen wheel from GCS.
|
||||
|
||||
@@ -307,6 +563,43 @@ def find_file(work_dir: Path, *patterns):
|
||||
return None
|
||||
|
||||
|
||||
def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) -> Path:
|
||||
"""Generate a MOV video from a static PNG image using FFmpeg.
|
||||
|
||||
This runs on the GCE encoding worker (not Cloud Run) because 4K H.264
|
||||
encoding requires more memory than the right-sized Cloud Run container
|
||||
provides (2Gi). See PR #640 / #647.
|
||||
|
||||
Args:
|
||||
png_path: Path to input PNG image
|
||||
mov_path: Path for output MOV video
|
||||
duration: Video duration in seconds (default 5)
|
||||
|
||||
Returns:
|
||||
Path to generated MOV file
|
||||
|
||||
Raises:
|
||||
RuntimeError: If FFmpeg fails
|
||||
"""
|
||||
command = [
|
||||
"ffmpeg", "-hide_banner", "-loglevel", "error", "-nostats", "-y",
|
||||
"-loop", "1", "-framerate", "30", "-i", str(png_path),
|
||||
"-f", "lavfi", "-i", "anullsrc",
|
||||
"-c:v", "libx264", "-r", "30", "-t", str(duration),
|
||||
"-pix_fmt", "yuv420p", "-vf", "scale=3840:2160",
|
||||
"-c:a", "aac", "-shortest",
|
||||
str(mov_path),
|
||||
]
|
||||
logger.info(f"Generating MOV from PNG: {png_path.name} -> {mov_path.name}")
|
||||
result = subprocess.run(command, capture_output=True, text=True, timeout=120)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"FFmpeg failed to generate {mov_path.name}: {result.stderr}")
|
||||
if not mov_path.exists() or mov_path.stat().st_size < 1024:
|
||||
raise RuntimeError(f"FFmpeg produced invalid output for {mov_path.name}")
|
||||
logger.info(f"Generated MOV: {mov_path.name} ({mov_path.stat().st_size} bytes)")
|
||||
return mov_path
|
||||
|
||||
|
||||
def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
'''Run encoding using LocalEncodingService (single source of truth).
|
||||
|
||||
@@ -329,14 +622,43 @@ 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
|
||||
# Title/end screens are in screens/ subdirectory
|
||||
# Title/end screens: look for MOV first, fall back to generating from PNG.
|
||||
# Since PR #640 right-sized Cloud Run to 2Gi, the screens_worker only generates
|
||||
# PNG/JPG images — MOV video generation now happens here on the GCE worker.
|
||||
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov")
|
||||
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
|
||||
|
||||
# Get intro/end video durations from style config (default 5s)
|
||||
intro_duration = config.get("intro_video_duration", 5)
|
||||
end_duration = config.get("end_video_duration", 5)
|
||||
|
||||
# Generate title MOV from PNG if missing or invalid (< 1KB = empty shell)
|
||||
if not title_video or title_video.stat().st_size < 1024:
|
||||
title_png = find_file(work_dir, "screens/title.png", "*Title*.png", "*title*.png")
|
||||
if title_png:
|
||||
title_mov_path = title_png.parent / "title.mov"
|
||||
logger.info(f"Title MOV missing/invalid, generating from PNG: {title_png}")
|
||||
title_video = generate_mov_from_png(title_png, title_mov_path, duration=intro_duration)
|
||||
elif title_video:
|
||||
logger.warning(f"Title MOV is only {title_video.stat().st_size} bytes and no PNG found")
|
||||
|
||||
# Generate end MOV from PNG if missing or invalid
|
||||
if not end_video or (end_video and end_video.stat().st_size < 1024):
|
||||
end_png = find_file(work_dir, "screens/end.png", "*End*.png", "*end*.png")
|
||||
if end_png:
|
||||
end_mov_path = end_png.parent / "end.mov"
|
||||
logger.info(f"End MOV missing/invalid, generating from PNG: {end_png}")
|
||||
end_video = generate_mov_from_png(end_png, end_mov_path, duration=end_duration)
|
||||
elif end_video:
|
||||
logger.warning(f"End MOV is only {end_video.stat().st_size} bytes and no PNG found")
|
||||
|
||||
# Karaoke video - search for With Vocals or main karaoke video
|
||||
# IMPORTANT: Search order matters! Search specific paths first to avoid picking up
|
||||
# old encoding outputs from finals/ directory when re-encoding after reset
|
||||
@@ -370,10 +692,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 +824,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(
|
||||
@@ -560,6 +903,36 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
|
||||
jobs[job_id]["error"] = str(e)
|
||||
|
||||
|
||||
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
|
||||
# Process a render-video job asynchronously
|
||||
try:
|
||||
# Download and install latest wheel at job start (allows hot updates without restart)
|
||||
ensure_latest_wheel()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
work_dir = Path(temp_dir) / "work"
|
||||
work_dir.mkdir()
|
||||
|
||||
# Run render-video in thread pool (CPU-bound)
|
||||
loop = asyncio.get_event_loop()
|
||||
await loop.run_in_executor(
|
||||
executor,
|
||||
run_render_video,
|
||||
job_id,
|
||||
work_dir,
|
||||
request
|
||||
)
|
||||
|
||||
jobs[job_id]["status"] = "complete"
|
||||
jobs[job_id]["progress"] = 100
|
||||
logger.info(f"Render video job {job_id} complete")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Render video job {job_id} failed: {e}")
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
|
||||
|
||||
@app.post("/encode-preview")
|
||||
async def submit_preview_encode_job(request: EncodePreviewRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
|
||||
# Submit a preview encoding job
|
||||
@@ -591,6 +964,37 @@ async def submit_preview_encode_job(request: EncodePreviewRequest, background_ta
|
||||
return {"status": "accepted", "job_id": job_id}
|
||||
|
||||
|
||||
@app.post("/render-video")
|
||||
async def submit_render_video_job(request: RenderVideoRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
|
||||
# Submit a render-video job
|
||||
job_id = request.job_id
|
||||
|
||||
# If job already exists, return cached result or current status
|
||||
if job_id in jobs:
|
||||
existing_job = jobs[job_id]
|
||||
if existing_job["status"] == "complete":
|
||||
return {"status": "cached", "job_id": job_id, "output_files": existing_job.get("output_files"), "metadata": existing_job.get("metadata")}
|
||||
elif existing_job["status"] == "failed":
|
||||
# Previous attempt failed, allow retry by replacing the job
|
||||
pass
|
||||
else:
|
||||
# Job is still in progress
|
||||
return {"status": "in_progress", "job_id": job_id}
|
||||
|
||||
jobs[job_id] = {
|
||||
"job_id": job_id,
|
||||
"status": "pending",
|
||||
"progress": 0,
|
||||
"error": None,
|
||||
"output_files": None,
|
||||
"metadata": None,
|
||||
}
|
||||
|
||||
background_tasks.add_task(process_render_video_job, job_id, request)
|
||||
|
||||
return {"status": "accepted", "job_id": job_id}
|
||||
|
||||
|
||||
@app.post("/encode")
|
||||
async def submit_encode_job(request: EncodeRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
|
||||
# Submit an encoding job
|
||||
|
||||
@@ -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,
|
||||
],
|
||||
@@ -190,8 +213,10 @@ def get_worker_valid_statuses() -> Dict[str, List[JobStatus]]:
|
||||
"video_worker": [
|
||||
JobStatus.INSTRUMENTAL_SELECTED,
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
JobStatus.GENERATING_VIDEO,
|
||||
# Note: RENDERING_VIDEO and GENERATING_VIDEO are intentionally excluded.
|
||||
# If the job is already in those states, another worker is actively processing it.
|
||||
# Including them caused a race condition where Cloud Run Job retries + manual retries
|
||||
# could launch concurrent workers that corrupt each other's state transitions.
|
||||
],
|
||||
"render_video_worker": [
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
|
||||
+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:
|
||||
|
||||
@@ -12,8 +12,10 @@ import logging
|
||||
import os
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from backend.i18n import get_locale_prefix
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.template_service import get_template_service
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -51,15 +53,30 @@ class JobNotificationService:
|
||||
self.frontend_url = os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
|
||||
self.backend_url = os.getenv("BACKEND_URL", "https://api.nomadkaraoke.com")
|
||||
|
||||
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None) -> str:
|
||||
def _get_user_locale(self, user_email: str) -> str:
|
||||
"""Look up user's locale preference from Firestore, defaulting to 'en'."""
|
||||
try:
|
||||
user_service = get_user_service()
|
||||
user = user_service.get_user(user_email)
|
||||
if user and user.locale:
|
||||
return user.locale
|
||||
except Exception:
|
||||
pass # Fall back to English
|
||||
return "en"
|
||||
|
||||
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None, locale: str = "en") -> str:
|
||||
"""Build the lyrics review URL for a job."""
|
||||
# Use hash-based routing for static hosting compatibility
|
||||
return f"{self.frontend_url}/app/jobs#/{job_id}/review"
|
||||
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/review"
|
||||
|
||||
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None) -> str:
|
||||
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None, locale: str = "en") -> str:
|
||||
"""Build the instrumental selection URL for a job."""
|
||||
# Use hash-based routing for static hosting compatibility
|
||||
return f"{self.frontend_url}/app/jobs#/{job_id}/instrumental"
|
||||
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/instrumental"
|
||||
|
||||
def _build_audio_edit_url(self, job_id: str, locale: str = "en") -> str:
|
||||
"""Build the audio edit URL for a job."""
|
||||
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/audio-edit"
|
||||
|
||||
async def send_job_completion_email(
|
||||
self,
|
||||
@@ -101,6 +118,9 @@ class JobNotificationService:
|
||||
return False
|
||||
|
||||
try:
|
||||
# Get user locale for email
|
||||
user_locale = self._get_user_locale(user_email)
|
||||
|
||||
# Render the completion message using template service
|
||||
message_content = self.template_service.render_job_completion(
|
||||
name=user_name,
|
||||
@@ -112,6 +132,7 @@ class JobNotificationService:
|
||||
feedback_url=FEEDBACK_FORM_URL,
|
||||
is_private=is_private,
|
||||
youtube_queued=youtube_queued,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
# Send the email with CC to admin
|
||||
@@ -122,6 +143,7 @@ class JobNotificationService:
|
||||
title=title,
|
||||
brand_code=brand_code,
|
||||
cc_admin=True,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
if success:
|
||||
@@ -167,10 +189,14 @@ class JobNotificationService:
|
||||
return False
|
||||
|
||||
try:
|
||||
# Get user locale for email
|
||||
user_locale = self._get_user_locale(user_email)
|
||||
|
||||
message_content = self.template_service.render_youtube_upload_complete(
|
||||
artist=artist,
|
||||
title=title,
|
||||
youtube_url=youtube_url,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
success = self.email_service.send_youtube_upload_complete(
|
||||
@@ -179,6 +205,7 @@ class JobNotificationService:
|
||||
artist=artist,
|
||||
title=title,
|
||||
brand_code=brand_code,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
if success:
|
||||
@@ -213,6 +240,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
|
||||
@@ -232,22 +260,37 @@ class JobNotificationService:
|
||||
return False
|
||||
|
||||
try:
|
||||
# Get user locale for email
|
||||
user_locale = self._get_user_locale(user_email)
|
||||
|
||||
# Render the appropriate template
|
||||
if action_type == "lyrics":
|
||||
review_url = self._build_review_url(job_id, audio_hash, review_token)
|
||||
review_url = self._build_review_url(job_id, audio_hash, review_token, locale=user_locale)
|
||||
message_content = self.template_service.render_action_needed_lyrics(
|
||||
name=user_name,
|
||||
artist=artist,
|
||||
title=title,
|
||||
review_url=review_url,
|
||||
locale=user_locale,
|
||||
)
|
||||
elif action_type == "instrumental":
|
||||
instrumental_url = self._build_instrumental_url(job_id, instrumental_token)
|
||||
instrumental_url = self._build_instrumental_url(job_id, instrumental_token, locale=user_locale)
|
||||
message_content = self.template_service.render_action_needed_instrumental(
|
||||
name=user_name,
|
||||
artist=artist,
|
||||
title=title,
|
||||
instrumental_url=instrumental_url,
|
||||
locale=user_locale,
|
||||
)
|
||||
elif action_type == "audio_edit":
|
||||
audio_edit_url = self._build_audio_edit_url(job_id, locale=user_locale)
|
||||
# Reuse the lyrics template but with the audio edit URL and different subject
|
||||
message_content = self.template_service.render_action_needed_lyrics(
|
||||
name=user_name,
|
||||
artist=artist,
|
||||
title=title,
|
||||
review_url=audio_edit_url,
|
||||
locale=user_locale,
|
||||
)
|
||||
else:
|
||||
logger.error(f"Unknown action type: {action_type}")
|
||||
@@ -260,6 +303,7 @@ class JobNotificationService:
|
||||
action_type=action_type,
|
||||
artist=artist,
|
||||
title=title,
|
||||
locale=user_locale,
|
||||
)
|
||||
|
||||
if success:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -12,6 +12,7 @@ from pywebpush import webpush, WebPushException
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.models.user import User, PushSubscription
|
||||
from backend.i18n import t
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -85,10 +86,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 +101,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 +118,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 +226,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 +239,18 @@ 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
|
||||
locale = job.get("locale", "en")
|
||||
|
||||
if action_type == "lyrics":
|
||||
notif_title = "Review Lyrics"
|
||||
notif_body = f'"{title}" by {artist} needs lyrics review'
|
||||
url = f"/review/{job_id}"
|
||||
notif_title = t(locale, "pushNotifications.reviewLyricsTitle")
|
||||
notif_body = t(locale, "pushNotifications.reviewLyricsBody", title=title, artist=artist)
|
||||
url = f"/app/jobs#/{job_id}/review"
|
||||
tag = f"lyrics-{job_id}"
|
||||
else: # instrumental
|
||||
notif_title = "Select Instrumental"
|
||||
notif_body = f'"{title}" by {artist} needs instrumental selection'
|
||||
url = f"/instrumental/{job_id}"
|
||||
notif_title = t(locale, "pushNotifications.selectInstrumentalTitle")
|
||||
notif_body = t(locale, "pushNotifications.selectInstrumentalBody", title=title, artist=artist)
|
||||
url = f"/app/jobs#/{job_id}/instrumental"
|
||||
tag = f"instrumental-{job_id}"
|
||||
|
||||
return await self.send_push(
|
||||
@@ -226,7 +258,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 +267,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 +279,16 @@ 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
|
||||
locale = job.get("locale", "en")
|
||||
|
||||
return await self.send_push(
|
||||
user_email=user_email,
|
||||
title="Video Ready!",
|
||||
body=f'Your karaoke video for "{title}" by {artist} is ready to download',
|
||||
title=t(locale, "pushNotifications.videoReadyTitle"),
|
||||
body=t(locale, "pushNotifications.videoReadyBody", title=title, artist=artist),
|
||||
url=f"/app/?job={job_id}",
|
||||
tag=f"complete-{job_id}"
|
||||
tag=f"complete-{job_id}",
|
||||
tenant_id=tenant_id,
|
||||
)
|
||||
|
||||
async def add_subscription(
|
||||
@@ -260,10 +296,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 +309,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 +336,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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,526 @@
|
||||
"""
|
||||
Referral service for link management, earnings tracking, and payouts.
|
||||
|
||||
Handles:
|
||||
- Referral link creation (generated and vanity codes)
|
||||
- Link lookup and validation
|
||||
- Click tracking
|
||||
- Admin listing
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
import string
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.models.referral import (
|
||||
ReferralLink,
|
||||
ReferralLinkStats,
|
||||
ReferralEarning,
|
||||
ReferralPayout,
|
||||
)
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Constants
|
||||
# ============================================================================
|
||||
|
||||
REFERRAL_LINKS_COLLECTION = "referral_links"
|
||||
REFERRAL_EARNINGS_COLLECTION = "referral_earnings"
|
||||
REFERRAL_PAYOUTS_COLLECTION = "referral_payouts"
|
||||
|
||||
RESERVED_CODES = frozenset({
|
||||
"admin", "app", "api", "r", "pricing", "order", "payment",
|
||||
"login", "auth", "webhook", "webhooks", "internal", "health",
|
||||
"static", "assets", "public", "private",
|
||||
})
|
||||
|
||||
PAYOUT_THRESHOLD_CENTS = 2000
|
||||
|
||||
VANITY_CODE_PATTERN = re.compile(r"^[a-z0-9][a-z0-9\-]{1,28}[a-z0-9]$")
|
||||
|
||||
# Characters for generated codes
|
||||
_CODE_ALPHABET = string.ascii_lowercase + string.digits
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Service
|
||||
# ============================================================================
|
||||
|
||||
class ReferralService:
|
||||
"""Service for referral link management and earnings."""
|
||||
|
||||
def __init__(self, db=None, stripe_service=None):
|
||||
if db is None:
|
||||
db = firestore.Client()
|
||||
self.db = db
|
||||
self.stripe_service = stripe_service
|
||||
|
||||
# ========================================================================
|
||||
# Code Generation & Validation
|
||||
# ========================================================================
|
||||
|
||||
def _generate_code(self) -> str:
|
||||
"""Generate an 8-character lowercase alphanumeric referral code."""
|
||||
return "".join(secrets.choice(_CODE_ALPHABET) for _ in range(8))
|
||||
|
||||
def _validate_vanity_code(self, code: str) -> Tuple[bool, str]:
|
||||
"""Validate a vanity code against reserved words and pattern rules.
|
||||
|
||||
Returns (is_valid, message).
|
||||
"""
|
||||
if code.lower() in RESERVED_CODES:
|
||||
return False, f"'{code}' is a reserved code"
|
||||
if not VANITY_CODE_PATTERN.match(code.lower()):
|
||||
return False, (
|
||||
"Code must be 3-30 characters, start/end with alphanumeric, "
|
||||
"and contain only lowercase letters, digits, and hyphens"
|
||||
)
|
||||
return True, "Valid"
|
||||
|
||||
# ========================================================================
|
||||
# Link CRUD
|
||||
# ========================================================================
|
||||
|
||||
def get_link_by_code(self, code: str) -> Optional[ReferralLink]:
|
||||
"""Get a referral link by its code. Returns None if not found or disabled."""
|
||||
doc = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code).get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
data = doc.to_dict()
|
||||
if not data.get("enabled", True):
|
||||
return None
|
||||
return ReferralLink(**data)
|
||||
|
||||
def get_or_create_link(self, owner_email: str) -> ReferralLink:
|
||||
"""Get existing referral link for owner, or create a new one.
|
||||
|
||||
Retries up to 10 times if generated code collides with existing doc.
|
||||
"""
|
||||
# Check for existing link
|
||||
existing = (
|
||||
self.db.collection(REFERRAL_LINKS_COLLECTION)
|
||||
.where("owner_email", "==", owner_email)
|
||||
.limit(1)
|
||||
.stream()
|
||||
)
|
||||
for doc in existing:
|
||||
return ReferralLink(**doc.to_dict())
|
||||
|
||||
# Create new link with retry for code collision
|
||||
for attempt in range(10):
|
||||
code = self._generate_code()
|
||||
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code)
|
||||
doc_snapshot = doc_ref.get()
|
||||
if doc_snapshot.exists:
|
||||
logger.warning("Code collision on attempt %d: %s", attempt + 1, code)
|
||||
continue
|
||||
|
||||
now = datetime.utcnow()
|
||||
link = ReferralLink(
|
||||
code=code,
|
||||
owner_email=owner_email,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
doc_ref.set(link.model_dump())
|
||||
return link
|
||||
|
||||
raise RuntimeError("Failed to generate unique referral code after 10 attempts")
|
||||
|
||||
def create_vanity_link(
|
||||
self,
|
||||
code: str,
|
||||
owner_email: str,
|
||||
display_name: Optional[str] = None,
|
||||
custom_message: Optional[str] = None,
|
||||
discount_percent: int = 10,
|
||||
kickback_percent: int = 20,
|
||||
discount_duration_days: int = 30,
|
||||
earning_duration_days: int = 365,
|
||||
) -> Tuple[bool, Optional[ReferralLink], str]:
|
||||
"""Create a vanity referral link.
|
||||
|
||||
Returns (success, link_or_none, message).
|
||||
"""
|
||||
valid, msg = self._validate_vanity_code(code)
|
||||
if not valid:
|
||||
return False, None, msg
|
||||
|
||||
normalized = code.lower()
|
||||
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(normalized)
|
||||
doc_snapshot = doc_ref.get()
|
||||
if doc_snapshot.exists:
|
||||
return False, None, f"Code '{normalized}' is already taken"
|
||||
|
||||
now = datetime.utcnow()
|
||||
link = ReferralLink(
|
||||
code=normalized,
|
||||
owner_email=owner_email,
|
||||
display_name=display_name,
|
||||
custom_message=custom_message,
|
||||
discount_percent=discount_percent,
|
||||
kickback_percent=kickback_percent,
|
||||
discount_duration_days=discount_duration_days,
|
||||
earning_duration_days=earning_duration_days,
|
||||
is_vanity=True,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
doc_ref.set(link.model_dump())
|
||||
return True, link, "Vanity link created"
|
||||
|
||||
def update_link(self, code: str, **updates) -> Tuple[bool, str]:
|
||||
"""Update fields on an existing referral link.
|
||||
|
||||
Returns (success, message).
|
||||
"""
|
||||
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code)
|
||||
doc_snapshot = doc_ref.get()
|
||||
if not doc_snapshot.exists:
|
||||
return False, f"Link '{code}' not found"
|
||||
|
||||
updates["updated_at"] = datetime.utcnow()
|
||||
doc_ref.update(updates)
|
||||
return True, "Link updated"
|
||||
|
||||
def increment_clicks(self, code: str) -> None:
|
||||
"""Increment the click counter for a referral link."""
|
||||
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code)
|
||||
doc_ref.update({"stats.clicks": firestore.Increment(1)})
|
||||
|
||||
# ========================================================================
|
||||
# Attribution
|
||||
# ========================================================================
|
||||
|
||||
def attribute_referral(self, referred_email: str, referral_code: str) -> Tuple[bool, str]:
|
||||
"""Attribute a referral to a user. Called during first login/signup."""
|
||||
referred_email = referred_email.lower()
|
||||
referral_code = referral_code.lower()
|
||||
|
||||
link = self.get_link_by_code(referral_code)
|
||||
if not link:
|
||||
return False, "Invalid or disabled referral code"
|
||||
|
||||
if link.owner_email == referred_email:
|
||||
return False, "Cannot use your own referral code"
|
||||
|
||||
# Increment signup count
|
||||
self.db.collection(REFERRAL_LINKS_COLLECTION).document(referral_code).update({
|
||||
"stats.signups": firestore.Increment(1),
|
||||
})
|
||||
|
||||
return True, "Referral attributed"
|
||||
|
||||
def get_attribution_data(self, referral_code: str) -> Optional[dict]:
|
||||
"""Get the data to set on user doc for referral attribution."""
|
||||
link = self.get_link_by_code(referral_code)
|
||||
if not link:
|
||||
return None
|
||||
now = datetime.utcnow()
|
||||
return {
|
||||
"referred_by_code": referral_code.lower(),
|
||||
"referred_at": now,
|
||||
"referral_discount_expires_at": now + timedelta(days=link.discount_duration_days),
|
||||
}
|
||||
|
||||
def get_or_create_stripe_coupon(self, discount_percent: int) -> Optional[str]:
|
||||
if not self.stripe_service:
|
||||
return None
|
||||
return self.stripe_service.get_or_create_referral_coupon(discount_percent)
|
||||
|
||||
def should_apply_discount(self, user_data: dict) -> bool:
|
||||
if not user_data.get("referred_by_code"):
|
||||
return False
|
||||
expires_at = user_data.get("referral_discount_expires_at")
|
||||
if not expires_at:
|
||||
return False
|
||||
if isinstance(expires_at, datetime):
|
||||
now = datetime.utcnow()
|
||||
# Firestore returns timezone-aware datetimes; ensure comparison is compatible
|
||||
if expires_at.tzinfo is not None:
|
||||
now = now.replace(tzinfo=expires_at.tzinfo)
|
||||
return expires_at > now
|
||||
return False
|
||||
|
||||
def get_discount_for_checkout(self, user_email: str) -> Optional[dict]:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
user = user_service.get_user(user_email)
|
||||
if not user or not user.referred_by_code:
|
||||
return None
|
||||
user_data = {
|
||||
"referred_by_code": user.referred_by_code,
|
||||
"referral_discount_expires_at": user.referral_discount_expires_at,
|
||||
}
|
||||
if not self.should_apply_discount(user_data):
|
||||
return None
|
||||
link = self.get_link_by_code(user.referred_by_code)
|
||||
if not link:
|
||||
return None
|
||||
coupon_id = self.get_or_create_stripe_coupon(link.discount_percent)
|
||||
if not coupon_id:
|
||||
return None
|
||||
return {"coupon_id": coupon_id, "discount_percent": link.discount_percent}
|
||||
|
||||
# ========================================================================
|
||||
# Earnings
|
||||
# ========================================================================
|
||||
|
||||
def record_earning(self, referred_email: str, stripe_session_id: str, purchase_amount_cents: int) -> Optional[dict]:
|
||||
"""Record a referral earning after a credit purchase."""
|
||||
referred_email = referred_email.lower()
|
||||
|
||||
# Look up the referred user
|
||||
user_doc = self.db.collection("gen_users").document(referred_email).get()
|
||||
if not user_doc.exists:
|
||||
return None
|
||||
|
||||
user_data = user_doc.to_dict()
|
||||
referral_code = user_data.get("referred_by_code")
|
||||
if not referral_code:
|
||||
return None
|
||||
|
||||
referred_at = user_data.get("referred_at")
|
||||
if not referred_at:
|
||||
return None
|
||||
|
||||
link = self.get_link_by_code(referral_code)
|
||||
if not link:
|
||||
return None
|
||||
|
||||
# Check earning window
|
||||
earning_expires = referred_at + timedelta(days=link.earning_duration_days)
|
||||
if datetime.utcnow() > earning_expires:
|
||||
return None
|
||||
|
||||
# Calculate earning
|
||||
earning_amount = int(purchase_amount_cents * link.kickback_percent / 100)
|
||||
if earning_amount <= 0:
|
||||
return None
|
||||
|
||||
import uuid
|
||||
earning_id = str(uuid.uuid4())
|
||||
earning = ReferralEarning(
|
||||
id=earning_id,
|
||||
referrer_email=link.owner_email,
|
||||
referred_email=referred_email,
|
||||
referral_code=referral_code,
|
||||
stripe_session_id=stripe_session_id,
|
||||
purchase_amount_cents=purchase_amount_cents,
|
||||
earning_amount_cents=earning_amount,
|
||||
)
|
||||
|
||||
self.db.collection(REFERRAL_EARNINGS_COLLECTION).document(earning_id).set(
|
||||
earning.model_dump(mode="json")
|
||||
)
|
||||
|
||||
self.db.collection(REFERRAL_LINKS_COLLECTION).document(referral_code).update({
|
||||
"stats.purchases": firestore.Increment(1),
|
||||
"stats.total_earned_cents": firestore.Increment(earning_amount),
|
||||
})
|
||||
|
||||
logger.info(f"Referral earning recorded: ${earning_amount / 100:.2f} for {link.owner_email}")
|
||||
return {"earning_id": earning_id, "referrer_email": link.owner_email, "earning_amount_cents": earning_amount}
|
||||
|
||||
# ========================================================================
|
||||
# Stripe Connect & Payouts
|
||||
# ========================================================================
|
||||
|
||||
def create_connect_account(self, email: str) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""Create Stripe Connect account for a referrer."""
|
||||
if not self.stripe_service:
|
||||
return None, None
|
||||
return self.stripe_service.create_connect_account(email)
|
||||
|
||||
def get_connect_account_status(self, account_id: str) -> Optional[dict]:
|
||||
"""Get Stripe Connect account status."""
|
||||
if not self.stripe_service:
|
||||
return None
|
||||
return self.stripe_service.get_connect_account_status(account_id)
|
||||
|
||||
def create_connect_login_link(self, account_id: str) -> Optional[str]:
|
||||
"""Create login link for Stripe Express dashboard."""
|
||||
if not self.stripe_service:
|
||||
return None
|
||||
return self.stripe_service.create_connect_login_link(account_id)
|
||||
|
||||
def create_connect_update_link(self, account_id: str) -> Optional[str]:
|
||||
"""Create account link for updating Connect info."""
|
||||
if not self.stripe_service:
|
||||
return None
|
||||
return self.stripe_service.create_connect_update_link(account_id)
|
||||
|
||||
def get_pending_earnings(self, referrer_email: str) -> List[dict]:
|
||||
"""Get all pending earnings for a referrer."""
|
||||
query = (
|
||||
self.db.collection(REFERRAL_EARNINGS_COLLECTION)
|
||||
.where("referrer_email", "==", referrer_email.lower())
|
||||
.where("status", "==", "pending")
|
||||
)
|
||||
return [
|
||||
{**doc.to_dict(), "_ref": doc.reference}
|
||||
for doc in query.get()
|
||||
]
|
||||
|
||||
def check_and_trigger_payout(self, referrer_email: str, stripe_connect_account_id: str) -> bool:
|
||||
"""Check if pending earnings meet threshold and trigger payout."""
|
||||
pending = self.get_pending_earnings(referrer_email)
|
||||
total_pending = sum(e.get("earning_amount_cents", 0) for e in pending)
|
||||
|
||||
if total_pending < PAYOUT_THRESHOLD_CENTS:
|
||||
return False
|
||||
|
||||
if not self.stripe_service:
|
||||
return False
|
||||
|
||||
transfer_id = self.stripe_service.create_transfer(
|
||||
amount_cents=total_pending,
|
||||
destination_account_id=stripe_connect_account_id,
|
||||
)
|
||||
if not transfer_id:
|
||||
return False
|
||||
|
||||
import uuid
|
||||
payout_id = str(uuid.uuid4())
|
||||
earning_ids = [e["id"] for e in pending]
|
||||
|
||||
payout = ReferralPayout(
|
||||
id=payout_id,
|
||||
referrer_email=referrer_email.lower(),
|
||||
stripe_transfer_id=transfer_id,
|
||||
amount_cents=total_pending,
|
||||
earnings_included=earning_ids,
|
||||
)
|
||||
self.db.collection(REFERRAL_PAYOUTS_COLLECTION).document(payout_id).set(
|
||||
payout.model_dump(mode="json")
|
||||
)
|
||||
|
||||
for earning in pending:
|
||||
if "_ref" in earning:
|
||||
earning["_ref"].update({
|
||||
"status": "paid",
|
||||
"paid_at": datetime.utcnow(),
|
||||
"payout_id": payout_id,
|
||||
})
|
||||
|
||||
logger.info(f"Payout triggered: ${total_pending / 100:.2f} to {referrer_email} (transfer: {transfer_id})")
|
||||
return True
|
||||
|
||||
def get_dashboard_data(self, user_email: str) -> dict:
|
||||
"""Get full referral dashboard data for a user."""
|
||||
user_email = user_email.lower()
|
||||
link = self.get_or_create_link(user_email)
|
||||
|
||||
# Get recent earnings (last 20)
|
||||
earnings_query = (
|
||||
self.db.collection(REFERRAL_EARNINGS_COLLECTION)
|
||||
.where("referrer_email", "==", user_email)
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(20)
|
||||
)
|
||||
earnings = [doc.to_dict() for doc in earnings_query.stream()]
|
||||
|
||||
# Get recent payouts (last 10)
|
||||
payouts_query = (
|
||||
self.db.collection(REFERRAL_PAYOUTS_COLLECTION)
|
||||
.where("referrer_email", "==", user_email)
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(10)
|
||||
)
|
||||
payouts = [doc.to_dict() for doc in payouts_query.stream()]
|
||||
|
||||
# Compute pending balance from ALL pending earnings (not limited to recent)
|
||||
pending_earnings = self.get_pending_earnings(user_email)
|
||||
pending_balance = sum(e.get("earning_amount_cents", 0) for e in pending_earnings)
|
||||
total_earned = link.stats.total_earned_cents
|
||||
# total_paid = total_earned - pending (since total_earned tracks all time)
|
||||
total_paid = total_earned - pending_balance
|
||||
|
||||
# Check Connect status and fetch account details
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(user_email)
|
||||
has_connect = bool(user and user.stripe_connect_account_id)
|
||||
|
||||
connect_account = None
|
||||
if has_connect and self.stripe_service:
|
||||
connect_account = self.stripe_service.get_connect_account_status(
|
||||
user.stripe_connect_account_id
|
||||
)
|
||||
|
||||
return {
|
||||
"link": {
|
||||
"code": link.code,
|
||||
"display_name": link.display_name,
|
||||
"custom_message": link.custom_message,
|
||||
"discount_percent": link.discount_percent,
|
||||
"kickback_percent": link.kickback_percent,
|
||||
"discount_duration_days": link.discount_duration_days,
|
||||
"earning_duration_days": link.earning_duration_days,
|
||||
"stats": link.stats.model_dump(),
|
||||
"enabled": link.enabled,
|
||||
"is_vanity": link.is_vanity,
|
||||
},
|
||||
"pending_balance_cents": pending_balance,
|
||||
"total_earned_cents": total_earned,
|
||||
"total_paid_cents": total_paid,
|
||||
"recent_earnings": [
|
||||
{
|
||||
"id": e["id"],
|
||||
"referred_email": e.get("referred_email", ""),
|
||||
"purchase_amount_cents": e.get("purchase_amount_cents", 0),
|
||||
"earning_amount_cents": e.get("earning_amount_cents", 0),
|
||||
"status": e.get("status", "pending"),
|
||||
"created_at": str(e.get("created_at", "")),
|
||||
}
|
||||
for e in earnings
|
||||
],
|
||||
"recent_payouts": [
|
||||
{
|
||||
"id": p["id"],
|
||||
"amount_cents": p.get("amount_cents", 0),
|
||||
"status": p.get("status", "processing"),
|
||||
"created_at": str(p.get("created_at", "")),
|
||||
}
|
||||
for p in payouts
|
||||
],
|
||||
"stripe_connect_configured": has_connect,
|
||||
"stripe_connect_account": connect_account,
|
||||
}
|
||||
|
||||
def list_links(self, limit: int = 50, offset: int = 0) -> list[ReferralLink]:
|
||||
"""List referral links for admin view."""
|
||||
query = (
|
||||
self.db.collection(REFERRAL_LINKS_COLLECTION)
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
)
|
||||
links = []
|
||||
for doc in query.stream():
|
||||
try:
|
||||
links.append(ReferralLink(**doc.to_dict()))
|
||||
except Exception:
|
||||
logger.warning("Skipping malformed referral link doc: %s", doc.id)
|
||||
return links
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Singleton accessor
|
||||
# ============================================================================
|
||||
|
||||
_referral_service = None
|
||||
|
||||
|
||||
def get_referral_service() -> ReferralService:
|
||||
global _referral_service
|
||||
if _referral_service is None:
|
||||
from backend.services.stripe_service import get_stripe_service
|
||||
_referral_service = ReferralService(stripe_service=get_stripe_service())
|
||||
return _referral_service
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -22,25 +22,25 @@ logger = logging.getLogger(__name__)
|
||||
CREDIT_PACKAGES = {
|
||||
"1_credit": {
|
||||
"credits": 1,
|
||||
"price_cents": 500, # $5.00
|
||||
"price_cents": 1000, # $10.00
|
||||
"name": "1 Karaoke Credit",
|
||||
"description": "Create 1 professional karaoke video",
|
||||
},
|
||||
"3_credits": {
|
||||
"credits": 3,
|
||||
"price_cents": 1200, # $12.00 (20% discount)
|
||||
"price_cents": 2400, # $24.00 (20% discount)
|
||||
"name": "3 Karaoke Credits",
|
||||
"description": "Create 3 professional karaoke videos (Save 20%)",
|
||||
},
|
||||
"5_credits": {
|
||||
"credits": 5,
|
||||
"price_cents": 1750, # $17.50 (30% discount)
|
||||
"price_cents": 3500, # $35.00 (30% discount)
|
||||
"name": "5 Karaoke Credits",
|
||||
"description": "Create 5 professional karaoke videos (Save 30%)",
|
||||
},
|
||||
"10_credits": {
|
||||
"credits": 10,
|
||||
"price_cents": 3000, # $30.00 (40% discount)
|
||||
"price_cents": 6000, # $60.00 (40% discount)
|
||||
"name": "10 Karaoke Credits",
|
||||
"description": "Create 10 professional karaoke videos (Save 40%)",
|
||||
},
|
||||
@@ -96,6 +96,7 @@ class StripeService:
|
||||
user_email: str,
|
||||
success_url: Optional[str] = None,
|
||||
cancel_url: Optional[str] = None,
|
||||
coupon_id: Optional[str] = None,
|
||||
) -> Tuple[bool, Optional[str], str]:
|
||||
"""
|
||||
Create a Stripe Checkout session for purchasing credits.
|
||||
@@ -151,6 +152,11 @@ class StripeService:
|
||||
'allow_promotion_codes': True,
|
||||
}
|
||||
|
||||
# If a referral coupon is applied, use discounts instead of allow_promotion_codes
|
||||
if coupon_id:
|
||||
session_params.pop('allow_promotion_codes', None)
|
||||
session_params['discounts'] = [{'coupon': coupon_id}]
|
||||
|
||||
# Add payment method configuration if set (enables Google Pay, Link, etc.)
|
||||
if self.payment_method_config:
|
||||
session_params['payment_method_configuration'] = self.payment_method_config
|
||||
@@ -351,6 +357,112 @@ class StripeService:
|
||||
logger.error(f"Error retrieving session {session_id}: {e}")
|
||||
return None
|
||||
|
||||
def get_or_create_referral_coupon(self, discount_percent: int) -> Optional[str]:
|
||||
"""Get or create a Stripe coupon for a referral discount percentage."""
|
||||
if not self.is_configured():
|
||||
return None
|
||||
coupon_id = f"referral-{discount_percent}pct"
|
||||
try:
|
||||
stripe.Coupon.retrieve(coupon_id)
|
||||
return coupon_id
|
||||
except stripe.error.InvalidRequestError:
|
||||
try:
|
||||
stripe.Coupon.create(
|
||||
id=coupon_id,
|
||||
percent_off=discount_percent,
|
||||
duration="once",
|
||||
name=f"Referral {discount_percent}% off",
|
||||
)
|
||||
logger.info(f"Created Stripe coupon: {coupon_id}")
|
||||
return coupon_id
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to create coupon {coupon_id}: {e}")
|
||||
return None
|
||||
|
||||
def create_connect_account(self, email: str) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""Create a Stripe Connect Express account. Returns (account_id, onboarding_url)."""
|
||||
if not self.is_configured():
|
||||
return None, None
|
||||
try:
|
||||
account = stripe.Account.create(
|
||||
type="express",
|
||||
email=email,
|
||||
capabilities={"transfers": {"requested": True}},
|
||||
metadata={"source": "nomad_karaoke_referrals"},
|
||||
)
|
||||
account_link = stripe.AccountLink.create(
|
||||
account=account.id,
|
||||
refresh_url=f"{self.frontend_url}/app/referrals?connect=refresh",
|
||||
return_url=f"{self.frontend_url}/app/referrals?connect=complete",
|
||||
type="account_onboarding",
|
||||
)
|
||||
logger.info(f"Created Connect account {account.id} for {email}")
|
||||
return account.id, account_link.url
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to create Connect account for {email}: {e}")
|
||||
return None, None
|
||||
|
||||
def get_connect_account_status(self, account_id: str) -> Optional[dict]:
|
||||
"""Retrieve Stripe Connect account status. Returns dict with account details."""
|
||||
if not self.is_configured():
|
||||
return None
|
||||
try:
|
||||
account = stripe.Account.retrieve(account_id)
|
||||
return {
|
||||
"account_id": account.id,
|
||||
"charges_enabled": account.charges_enabled,
|
||||
"payouts_enabled": account.payouts_enabled,
|
||||
"details_submitted": account.details_submitted,
|
||||
"email": account.email,
|
||||
}
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to retrieve Connect account {account_id}: {e}")
|
||||
return None
|
||||
|
||||
def create_connect_login_link(self, account_id: str) -> Optional[str]:
|
||||
"""Create a login link to the Stripe Express dashboard. Returns URL."""
|
||||
if not self.is_configured():
|
||||
return None
|
||||
try:
|
||||
link = stripe.Account.create_login_link(account_id)
|
||||
return link.url
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to create login link for {account_id}: {e}")
|
||||
return None
|
||||
|
||||
def create_connect_update_link(self, account_id: str) -> Optional[str]:
|
||||
"""Create an account link for updating Connect account info. Returns URL."""
|
||||
if not self.is_configured():
|
||||
return None
|
||||
try:
|
||||
account_link = stripe.AccountLink.create(
|
||||
account=account_id,
|
||||
refresh_url=f"{self.frontend_url}/app/referrals?connect=refresh",
|
||||
return_url=f"{self.frontend_url}/app/referrals?connect=complete",
|
||||
type="account_onboarding",
|
||||
)
|
||||
return account_link.url
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to create update link for {account_id}: {e}")
|
||||
return None
|
||||
|
||||
def create_transfer(self, amount_cents: int, destination_account_id: str, description: str = "Nomad Karaoke referral payout") -> Optional[str]:
|
||||
"""Create a transfer to a Connect account. Returns transfer ID."""
|
||||
if not self.is_configured():
|
||||
return None
|
||||
try:
|
||||
transfer = stripe.Transfer.create(
|
||||
amount=amount_cents,
|
||||
currency="usd",
|
||||
destination=destination_account_id,
|
||||
description=description,
|
||||
)
|
||||
logger.info(f"Created transfer {transfer.id}: ${amount_cents / 100:.2f} to {destination_account_id}")
|
||||
return transfer.id
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to create transfer to {destination_account_id}: {e}")
|
||||
return None
|
||||
|
||||
def create_customer(self, email: str, name: Optional[str] = None) -> Optional[str]:
|
||||
"""
|
||||
Create or get a Stripe customer for a user.
|
||||
|
||||
@@ -14,6 +14,7 @@ import re
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -154,29 +155,48 @@ class TemplateService:
|
||||
logger.error(f"Failed to fetch template {blob_path}: {e}")
|
||||
return None
|
||||
|
||||
def get_job_completion_template(self) -> str:
|
||||
def get_job_completion_template(self, locale: str = "en") -> str:
|
||||
"""Get the job completion email template."""
|
||||
# Try locale-specific GCS template first, then default GCS, then localized default
|
||||
if locale != "en":
|
||||
template = self._fetch_template_from_gcs(f"{locale}/job-completion.txt")
|
||||
if template is not None:
|
||||
return template
|
||||
template = self._fetch_template_from_gcs("job-completion.txt")
|
||||
if template is None:
|
||||
logger.info("Using default job completion template")
|
||||
if template is not None:
|
||||
return template
|
||||
logger.info("Using default job completion template")
|
||||
if locale == "en":
|
||||
return DEFAULT_JOB_COMPLETION_TEMPLATE
|
||||
return template
|
||||
return self._build_localized_job_completion_template(locale)
|
||||
|
||||
def get_action_needed_lyrics_template(self) -> str:
|
||||
def get_action_needed_lyrics_template(self, locale: str = "en") -> str:
|
||||
"""Get the lyrics review reminder template."""
|
||||
if locale != "en":
|
||||
template = self._fetch_template_from_gcs(f"{locale}/action-needed-lyrics.txt")
|
||||
if template is not None:
|
||||
return template
|
||||
template = self._fetch_template_from_gcs("action-needed-lyrics.txt")
|
||||
if template is None:
|
||||
logger.info("Using default lyrics reminder template")
|
||||
if template is not None:
|
||||
return template
|
||||
logger.info("Using default lyrics reminder template")
|
||||
if locale == "en":
|
||||
return DEFAULT_ACTION_NEEDED_LYRICS_TEMPLATE
|
||||
return template
|
||||
return self._build_localized_action_lyrics_template(locale)
|
||||
|
||||
def get_action_needed_instrumental_template(self) -> str:
|
||||
def get_action_needed_instrumental_template(self, locale: str = "en") -> str:
|
||||
"""Get the instrumental selection reminder template."""
|
||||
if locale != "en":
|
||||
template = self._fetch_template_from_gcs(f"{locale}/action-needed-instrumental.txt")
|
||||
if template is not None:
|
||||
return template
|
||||
template = self._fetch_template_from_gcs("action-needed-instrumental.txt")
|
||||
if template is None:
|
||||
logger.info("Using default instrumental reminder template")
|
||||
if template is not None:
|
||||
return template
|
||||
logger.info("Using default instrumental reminder template")
|
||||
if locale == "en":
|
||||
return DEFAULT_ACTION_NEEDED_INSTRUMENTAL_TEMPLATE
|
||||
return template
|
||||
return self._build_localized_action_instrumental_template(locale)
|
||||
|
||||
def render_template(self, template: str, variables: Dict[str, Any]) -> str:
|
||||
"""
|
||||
@@ -215,6 +235,74 @@ class TemplateService:
|
||||
|
||||
return result.strip()
|
||||
|
||||
def _build_localized_job_completion_template(self, locale: str) -> str:
|
||||
"""Build a localized job completion template from translation keys."""
|
||||
ns = "emails.templates.jobCompletion"
|
||||
return f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.thanks")}
|
||||
|
||||
{t(locale, f"{ns}.youtubeLink")}
|
||||
{{youtube_url}}
|
||||
|
||||
{t(locale, f"{ns}.dropboxIntro")}
|
||||
{t(locale, f"{ns}.fileList")}
|
||||
|
||||
{{dropbox_url}}
|
||||
|
||||
{t(locale, f"{ns}.fixOffer")}
|
||||
|
||||
{t(locale, f"{ns}.feedbackRequest")}
|
||||
{{feedback_url}}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
|
||||
def _build_localized_action_lyrics_template(self, locale: str) -> str:
|
||||
"""Build a localized action-needed lyrics template."""
|
||||
ns = "emails.templates.actionLyrics"
|
||||
return f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.ready")}
|
||||
|
||||
{t(locale, f"{ns}.instructions")}
|
||||
|
||||
{t(locale, f"{ns}.reviewPrompt")}
|
||||
{{review_url}}
|
||||
|
||||
{t(locale, f"{ns}.duration")}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
|
||||
def _build_localized_action_instrumental_template(self, locale: str) -> str:
|
||||
"""Build a localized action-needed instrumental template."""
|
||||
ns = "emails.templates.actionInstrumental"
|
||||
return f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.almostDone")}
|
||||
|
||||
{t(locale, f"{ns}.instructions")}
|
||||
|
||||
{t(locale, f"{ns}.selectPrompt")}
|
||||
{{instrumental_url}}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
|
||||
def _build_localized_youtube_complete_template(self, locale: str) -> str:
|
||||
"""Build a localized YouTube upload complete template."""
|
||||
ns = "emails.templates.youtubeComplete"
|
||||
return f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.greatNews")}
|
||||
{{youtube_url}}
|
||||
|
||||
{t(locale, f"{ns}.delayNote")}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
|
||||
def render_job_completion(
|
||||
self,
|
||||
name: Optional[str] = None,
|
||||
@@ -226,6 +314,7 @@ class TemplateService:
|
||||
feedback_url: Optional[str] = None,
|
||||
is_private: bool = False,
|
||||
youtube_queued: bool = False,
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""
|
||||
Render the job completion email template.
|
||||
@@ -244,7 +333,7 @@ class TemplateService:
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self.get_job_completion_template()
|
||||
template = self.get_job_completion_template(locale)
|
||||
|
||||
# For private tracks, remove the YouTube section entirely
|
||||
if is_private:
|
||||
@@ -255,11 +344,18 @@ class TemplateService:
|
||||
)
|
||||
elif youtube_queued and not youtube_url:
|
||||
# Replace YouTube URL with pending message
|
||||
queued_msg = t(locale, "emails.templates.jobCompletion.youtubeQueued")
|
||||
youtube_link_text = t(locale, "emails.templates.jobCompletion.youtubeLink")
|
||||
template = template.replace(
|
||||
"Here's the link for the karaoke video published to YouTube:\n{youtube_url}",
|
||||
"Your YouTube upload is queued and will be processed automatically. "
|
||||
"You'll receive a follow-up email with the link shortly."
|
||||
f"{youtube_link_text}\n{{youtube_url}}",
|
||||
queued_msg
|
||||
)
|
||||
# Also handle the English default template pattern
|
||||
if "{youtube_url}" in template:
|
||||
template = template.replace(
|
||||
"Here's the link for the karaoke video published to YouTube:\n{youtube_url}",
|
||||
queued_msg
|
||||
)
|
||||
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
@@ -278,6 +374,7 @@ class TemplateService:
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
review_url: str = "",
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""
|
||||
Render the combined review reminder template.
|
||||
@@ -294,7 +391,7 @@ class TemplateService:
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self.get_action_needed_lyrics_template()
|
||||
template = self.get_action_needed_lyrics_template(locale)
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"artist": artist or "Unknown Artist",
|
||||
@@ -309,6 +406,7 @@ class TemplateService:
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
instrumental_url: str = "",
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""
|
||||
Render the instrumental selection reminder template.
|
||||
@@ -326,7 +424,7 @@ class TemplateService:
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self.get_action_needed_instrumental_template()
|
||||
template = self.get_action_needed_instrumental_template(locale)
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"artist": artist or "Unknown Artist",
|
||||
@@ -341,6 +439,7 @@ class TemplateService:
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""
|
||||
Render the YouTube upload complete follow-up email template.
|
||||
@@ -356,9 +455,16 @@ class TemplateService:
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
|
||||
if locale != "en":
|
||||
template = self._fetch_template_from_gcs(f"{locale}/youtube-upload-complete.txt")
|
||||
if template is not None:
|
||||
pass # Use locale-specific GCS template
|
||||
else:
|
||||
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
|
||||
else:
|
||||
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
|
||||
if template is None:
|
||||
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE
|
||||
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE if locale == "en" else self._build_localized_youtube_complete_template(locale)
|
||||
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
|
||||
@@ -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."""
|
||||
@@ -59,29 +59,71 @@ class UserService:
|
||||
# User CRUD Operations
|
||||
# =========================================================================
|
||||
|
||||
def get_user_doc_ref(self, email: str):
|
||||
"""Get the Firestore document reference for a user by email.
|
||||
|
||||
Handles both email-keyed docs (doc ID = email) and hash-keyed docs
|
||||
(doc ID = hash, email stored as field). Returns None if not found.
|
||||
"""
|
||||
try:
|
||||
# First try direct lookup by email as doc ID
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc = doc_ref.get()
|
||||
if doc.exists:
|
||||
return doc_ref
|
||||
|
||||
# Fallback: query by email field (for hash-keyed docs)
|
||||
query = self.db.collection(USERS_COLLECTION).where(
|
||||
filter=FieldFilter('email', '==', email.lower())
|
||||
).limit(1)
|
||||
results = list(query.stream())
|
||||
if results:
|
||||
return results[0].reference
|
||||
|
||||
return None
|
||||
except Exception:
|
||||
logger.exception(f"Error finding user doc ref for {email}")
|
||||
return None
|
||||
|
||||
def get_user(self, email: str) -> Optional[User]:
|
||||
"""Get a user by email."""
|
||||
try:
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return None
|
||||
if doc.exists:
|
||||
return User(**doc.to_dict())
|
||||
|
||||
return User(**doc.to_dict())
|
||||
# Fallback: query by email field (for hash-keyed docs)
|
||||
query = self.db.collection(USERS_COLLECTION).where(
|
||||
filter=FieldFilter('email', '==', email.lower())
|
||||
).limit(1)
|
||||
results = list(query.stream())
|
||||
if results:
|
||||
return User(**results[0].to_dict())
|
||||
|
||||
return None
|
||||
except Exception:
|
||||
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.
|
||||
@@ -95,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:
|
||||
@@ -127,7 +164,10 @@ class UserService:
|
||||
"""Update user fields."""
|
||||
try:
|
||||
updates['updated_at'] = datetime.utcnow()
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc_ref = self.get_user_doc_ref(email)
|
||||
if not doc_ref:
|
||||
logger.warning(f"Cannot update user {email}: doc not found")
|
||||
return None
|
||||
doc_ref.update(updates)
|
||||
return self.get_user(email)
|
||||
except Exception:
|
||||
@@ -176,7 +216,9 @@ 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,
|
||||
referral_code: Optional[str] = None,
|
||||
) -> MagicLinkToken:
|
||||
"""
|
||||
Create a magic link token for email authentication.
|
||||
@@ -189,11 +231,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)
|
||||
@@ -205,6 +253,8 @@ class UserService:
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
referral_code=referral_code,
|
||||
)
|
||||
|
||||
# Save to Firestore
|
||||
@@ -322,6 +372,406 @@ 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"
|
||||
|
||||
# Skip AI evaluation for test emails (e.g. E2E test accounts)
|
||||
# to avoid wasting LLM credits and sending unnecessary denial emails
|
||||
from backend.utils.test_data import is_test_email
|
||||
if not is_test_email(email):
|
||||
# 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"
|
||||
else:
|
||||
logger.info(f"Skipping credit evaluation for test email {email}")
|
||||
|
||||
# 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
|
||||
# =========================================================================
|
||||
@@ -331,7 +781,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.
|
||||
@@ -341,6 +792,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]
|
||||
@@ -352,6 +804,7 @@ class UserService:
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Serialize and write to Firestore
|
||||
@@ -820,12 +1273,10 @@ class UserService:
|
||||
def increment_jobs_completed(self, email: str) -> bool:
|
||||
"""Increment the completed jobs counter for a user using atomic increment."""
|
||||
try:
|
||||
# Check user exists first
|
||||
if not self.get_user(email):
|
||||
doc_ref = self.get_user_doc_ref(email)
|
||||
if not doc_ref:
|
||||
return False
|
||||
|
||||
# Use atomic increment to prevent race conditions
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc_ref.update({
|
||||
'total_jobs_completed': Increment(1),
|
||||
'updated_at': datetime.utcnow()
|
||||
|
||||
@@ -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:
|
||||
@@ -395,14 +411,40 @@ class WorkerService:
|
||||
"""Trigger screen generation worker."""
|
||||
return await self.trigger_worker("screens", job_id)
|
||||
|
||||
def _warmup_encoding_worker(self, job_id: str) -> None:
|
||||
"""Fire-and-forget warmup of the encoding worker VM.
|
||||
|
||||
Called before dispatching video/render workers so the GCE encoding
|
||||
VM starts booting while the worker downloads files and prepares.
|
||||
Failures are logged but never block worker dispatch.
|
||||
"""
|
||||
try:
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from google.cloud import compute_v1, firestore
|
||||
db = firestore.Client(project=self.settings.google_cloud_project)
|
||||
compute_client = compute_v1.InstancesClient()
|
||||
manager = EncodingWorkerManager(
|
||||
db=db,
|
||||
compute_client=compute_client,
|
||||
project_id=self.settings.google_cloud_project,
|
||||
)
|
||||
result = manager.ensure_primary_running()
|
||||
if result["started"]:
|
||||
logger.info(f"[job:{job_id}] Encoding worker warmup: started VM {result['vm_name']}")
|
||||
else:
|
||||
logger.info(f"[job:{job_id}] Encoding worker warmup: VM {result['vm_name']} already running")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Encoding worker warmup failed (non-fatal): {e}")
|
||||
|
||||
async def trigger_video_worker(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger video generation worker.
|
||||
|
||||
|
||||
When USE_CLOUD_RUN_JOBS_FOR_VIDEO=true and ENABLE_CLOUD_TASKS=true,
|
||||
uses Cloud Run Jobs for execution (supports >30 min encoding).
|
||||
Otherwise, uses Cloud Tasks or direct HTTP.
|
||||
"""
|
||||
self._warmup_encoding_worker(job_id)
|
||||
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_video:
|
||||
return await self._trigger_cloud_run_job(job_id)
|
||||
return await self.trigger_worker("video", job_id)
|
||||
@@ -431,6 +473,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 +486,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 +499,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
|
||||
@@ -493,6 +537,7 @@ class WorkerService:
|
||||
|
||||
async def trigger_render_video_worker(self, job_id: str) -> bool:
|
||||
"""Trigger render video worker (post-review)."""
|
||||
self._warmup_encoding_worker(job_id)
|
||||
return await self.trigger_worker("render-video", job_id)
|
||||
|
||||
async def schedule_idle_reminder(
|
||||
|
||||
@@ -68,6 +68,36 @@ class YouTubeDownloadService:
|
||||
"""Check if remote flacfetch is configured."""
|
||||
return self._flacfetch_client is not None
|
||||
|
||||
async def check_availability(self, url: str) -> Optional[dict]:
|
||||
"""
|
||||
Check if a YouTube video is available for download.
|
||||
|
||||
Uses the flacfetch /check-youtube endpoint to detect geo-restrictions,
|
||||
private/removed videos, etc. before creating a job.
|
||||
|
||||
Returns:
|
||||
Check result dict if check succeeds, None if check can't be
|
||||
performed (no remote configured, network error, etc.).
|
||||
Callers should treat None as "unknown, proceed anyway".
|
||||
"""
|
||||
if not self._flacfetch_client:
|
||||
return None
|
||||
|
||||
video_id = self._extract_video_id(url)
|
||||
if not video_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
result = await self._flacfetch_client.check_youtube(url)
|
||||
logger.info(
|
||||
f"YouTube availability check for {video_id}: "
|
||||
f"available={result.get('available')}"
|
||||
)
|
||||
return result
|
||||
except FlacfetchServiceError as e:
|
||||
logger.warning(f"YouTube availability check failed for {video_id}, proceeding anyway: {e}")
|
||||
return None
|
||||
|
||||
async def download(
|
||||
self,
|
||||
url: str,
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Nomad Karaoke - Make Your Own Karaoke Videos</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
*, html { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
@page {
|
||||
size: 8.5in 11in;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 8.5in;
|
||||
height: 11in;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
font-family: 'Outfit', sans-serif;
|
||||
background: #0c0a1a;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* Dark atmospheric background */
|
||||
.bg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
radial-gradient(ellipse 80% 50% at 50% 0%, rgba(120, 40, 200, 0.35) 0%, transparent 70%),
|
||||
radial-gradient(ellipse 60% 40% at 20% 80%, rgba(255, 50, 120, 0.2) 0%, transparent 60%),
|
||||
radial-gradient(ellipse 50% 30% at 85% 70%, rgba(255, 180, 40, 0.15) 0%, transparent 60%),
|
||||
linear-gradient(180deg, #0c0a1a 0%, #1a1035 40%, #0c0a1a 100%);
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.content {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 0.6in 0.65in 0.5in;
|
||||
}
|
||||
|
||||
/* Logo at top */
|
||||
.logo-container {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.logo-svg {
|
||||
width: 260px;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
/* Headline */
|
||||
.headline {
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
text-align: center;
|
||||
line-height: 0.92;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.headline-main {
|
||||
font-size: 96px;
|
||||
letter-spacing: 3px;
|
||||
background: linear-gradient(180deg, #ffd86b 0%, #ff7acc 50%, #c45aff 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.headline-sub {
|
||||
font-size: 62px;
|
||||
letter-spacing: 2px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* Subtitle */
|
||||
.subtitle {
|
||||
font-size: 20px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
text-align: center;
|
||||
max-width: 5.5in;
|
||||
line-height: 1.4;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
/* Steps section */
|
||||
.steps {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
width: 100%;
|
||||
max-width: 6in;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.step {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.step-number {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
flex-shrink: 0;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(135deg, #c45aff, #ff7acc);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
font-size: 30px;
|
||||
color: #fff;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.step-content {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.step-title {
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
color: #fff;
|
||||
letter-spacing: -0.3px;
|
||||
}
|
||||
|
||||
.step-desc {
|
||||
font-size: 16px;
|
||||
font-weight: 400;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* Divider */
|
||||
.divider {
|
||||
width: 80%;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, transparent, rgba(255, 122, 204, 0.4), rgba(255, 216, 107, 0.4), transparent);
|
||||
margin: 4px 0 24px;
|
||||
}
|
||||
|
||||
/* CTA section */
|
||||
.cta-section {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 40px;
|
||||
width: 100%;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.qr-container {
|
||||
width: 180px;
|
||||
height: 180px;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
border: 3px solid rgba(255, 255, 255, 0.15);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 4px 20px rgba(0,0,0,0.06);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.qr-container img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.qr-placeholder {
|
||||
font-size: 14px;
|
||||
color: #999;
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.cta-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.cta-label {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 2px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.cta-url {
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
font-size: 38px;
|
||||
letter-spacing: 2px;
|
||||
color: #ffd86b;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cta-url .referral-code {
|
||||
background: linear-gradient(135deg, #ff7acc 0%, #c45aff 40%, #ff5a8a 70%, #ffdf6b 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
letter-spacing: 4px;
|
||||
}
|
||||
|
||||
.cta-note {
|
||||
font-size: 15px;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
margin-top: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Bottom section */
|
||||
.bottom {
|
||||
margin-top: auto;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.bottom-features {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.bottom-feature {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.bottom-feature-icon {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.bottom-tagline {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
|
||||
@media print {
|
||||
body {
|
||||
-webkit-print-color-adjust: exact;
|
||||
print-color-adjust: exact;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="bg"></div>
|
||||
|
||||
<div class="content">
|
||||
<!-- Logo -->
|
||||
<div class="logo-container">
|
||||
<svg class="logo-svg" viewBox="45 60 255 135" xmlns="http://www.w3.org/2000/svg">
|
||||
<g fill="#ff7acc" transform="translate(48.368003845214844,62.62239074707031)"><g transform="translate(0,0)"><g transform="scale(1.4000000000000004)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill-opacity="0"><path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)"></path></g><g transform="translate(0,38.959999084472656)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill="#ff7acc" fill-opacity="0" transform="scale(1.02719)"><path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)"></path></g></g></g></g>
|
||||
<g fill-rule="" fill="#ffdf6b" transform="translate(5,111.788818359375)"><rect x="0" height="1" y="5.9832000732421875" width="14.278396606445312"></rect><rect height="1" y="5.9832000732421875" width="14.278396606445312" x="218.985595703125"></rect><g transform="translate(17.278396606445312,0)"><g transform="scale(1.2800000000000002)"><path d="M10.21-8.38L12.02-8.38L9.68 0L7.70 0L6.13-5.96L4.49 0L2.52 0.01L0.26-8.38L2.06-8.38L3.54-1.87L5.24-8.38L7.12-8.38L8.72-1.91L10.21-8.38ZM18.38-8.38L20.06-8.38L20.06 0L18.38 0L18.38-3.56L14.80-3.56L14.80 0L13.12 0L13.12-8.38L14.80-8.38L14.80-4.93L18.38-4.93L18.38-8.38ZM26.58-7.02L23.40-7.02L23.40-4.92L26.22-4.92L26.22-3.59L23.40-3.59L23.40-1.37L26.58-1.37L26.58 0L21.72 0L21.72-8.39L26.58-8.39L26.58-7.02ZM34.37 0L32.42 0L30.58-3.26L29.78-3.26L29.78 0L28.10 0L28.10-8.38L31.25-8.38Q32.22-8.38 32.90-8.03Q33.59-7.69 33.93-7.11Q34.27-6.53 34.27-5.81L34.27-5.81Q34.27-4.98 33.79-4.31Q33.31-3.65 32.36-3.40L32.36-3.40L34.37 0ZM29.78-6.98L29.78-4.52L31.19-4.52Q31.87-4.52 32.21-4.85Q32.54-5.18 32.54-5.77L32.54-5.77Q32.54-6.35 32.21-6.67Q31.87-6.98 31.19-6.98L31.19-6.98L29.78-6.98ZM40.66-7.02L37.48-7.02L37.48-4.92L40.30-4.92L40.30-3.59L37.48-3.59L37.48-1.37L40.66-1.37L40.66 0L35.80 0L35.80-8.39L40.66-8.39L40.66-7.02ZM47.92-8.38L49.70-8.38L46.63 0L44.59 0L41.52-8.38L43.32-8.38L45.62-1.72L47.92-8.38ZM55.57-7.02L52.39-7.02L52.39-4.92L55.21-4.92L55.21-3.59L52.39-3.59L52.39-1.37L55.57-1.37L55.57 0L50.71 0L50.71-8.39L55.57-8.39L55.57-7.02ZM63.36 0L61.42 0L59.57-3.26L58.78-3.26L58.78 0L57.10 0L57.10-8.38L60.24-8.38Q61.21-8.38 61.90-8.03Q62.58-7.69 62.92-7.11Q63.26-6.53 63.26-5.81L63.26-5.81Q63.26-4.98 62.78-4.31Q62.30-3.65 61.36-3.40L61.36-3.40L63.36 0ZM58.78-6.98L58.78-4.52L60.18-4.52Q60.86-4.52 61.20-4.85Q61.54-5.18 61.54-5.77L61.54-5.77Q61.54-6.35 61.20-6.67Q60.86-6.98 60.18-6.98L60.18-6.98L58.78-6.98ZM72.43-8.38L74.30-8.38L71.47-2.92L71.47 0L69.79 0L69.79-2.92L66.95-8.38L68.84-8.38L70.64-4.55L72.43-8.38ZM79.16 0.08Q77.99 0.08 77.00-0.47Q76.02-1.02 75.44-2.00Q74.87-2.98 74.87-4.21L74.87-4.21Q74.87-5.44 75.44-6.41Q76.02-7.39 77.00-7.94Q77.99-8.50 79.16-8.50L79.16-8.50Q80.35-8.50 81.33-7.94Q82.31-7.39 82.88-6.41Q83.45-5.44 83.45-4.21L83.45-4.21Q83.45-2.98 82.88-2.00Q82.31-1.02 81.32-0.47Q80.34 0.08 79.16 0.08L79.16 0.08ZM79.16-1.42Q79.92-1.42 80.50-1.76Q81.07-2.10 81.40-2.74Q81.72-3.37 81.72-4.21L81.72-4.21Q81.72-5.05 81.40-5.68Q81.07-6.31 80.50-6.65Q79.92-6.98 79.16-6.98L79.16-6.98Q78.41-6.98 77.83-6.65Q77.24-6.31 76.92-5.68Q76.60-5.05 76.60-4.21L76.60-4.21Q76.60-3.37 76.92-2.74Q77.24-2.10 77.83-1.76Q78.41-1.42 79.16-1.42L79.16-1.42ZM84.67-8.38L86.35-8.38L86.35-3.19Q86.35-2.34 86.80-1.89Q87.24-1.44 88.04-1.44L88.04-1.44Q88.86-1.44 89.30-1.89Q89.75-2.34 89.75-3.19L89.75-3.19L89.75-8.38L91.44-8.38L91.44-3.20Q91.44-2.14 90.98-1.40Q90.52-0.66 89.74-0.29Q88.97 0.08 88.02 0.08L88.02 0.08Q87.08 0.08 86.32-0.29Q85.56-0.66 85.12-1.40Q84.67-2.14 84.67-3.20L84.67-3.20L84.67-8.38ZM101.60 0L101.05-1.60L97.72-1.60L97.16 0L95.40 0L98.41-8.39L100.37-8.39L103.38 0L101.60 0ZM98.17-2.94L100.60-2.94L99.38-6.44L98.17-2.94ZM110.77 0L108.83 0L106.98-3.26L106.19-3.26L106.19 0L104.51 0L104.51-8.38L107.65-8.38Q108.62-8.38 109.31-8.03Q109.99-7.69 110.33-7.11Q110.68-6.53 110.68-5.81L110.68-5.81Q110.68-4.98 110.20-4.31Q109.72-3.65 108.77-3.40L108.77-3.40L110.77 0ZM106.19-6.98L106.19-4.52L107.59-4.52Q108.28-4.52 108.61-4.85Q108.95-5.18 108.95-5.77L108.95-5.77Q108.95-6.35 108.61-6.67Q108.28-6.98 107.59-6.98L107.59-6.98L106.19-6.98ZM117.06-7.02L113.88-7.02L113.88-4.92L116.70-4.92L116.70-3.59L113.88-3.59L113.88-1.37L117.06-1.37L117.06 0L112.20 0L112.20-8.39L117.06-8.39L117.06-7.02ZM118.72-1.76L120.42-1.76L119.02 1.61L117.94 1.61L118.72-1.76ZM127.38 0.08Q126.50 0.08 125.80-0.22Q125.10-0.52 124.69-1.08Q124.28-1.64 124.27-2.41L124.27-2.41L126.07-2.41Q126.11-1.90 126.44-1.60Q126.77-1.30 127.34-1.30L127.34-1.30Q127.93-1.30 128.27-1.58Q128.60-1.86 128.60-2.32L128.60-2.32Q128.60-2.69 128.38-2.93Q128.15-3.17 127.81-3.31Q127.46-3.44 126.86-3.61L126.86-3.61Q126.05-3.85 125.54-4.09Q125.03-4.32 124.66-4.79Q124.30-5.27 124.30-6.06L124.30-6.06Q124.30-6.80 124.67-7.36Q125.04-7.91 125.71-8.20Q126.38-8.50 127.25-8.50L127.25-8.50Q128.54-8.50 129.35-7.87Q130.16-7.24 130.25-6.11L130.25-6.11L128.40-6.11Q128.38-6.54 128.03-6.82Q127.69-7.10 127.13-7.10L127.13-7.10Q126.64-7.10 126.34-6.85Q126.05-6.60 126.05-6.12L126.05-6.12Q126.05-5.78 126.27-5.56Q126.49-5.34 126.82-5.20Q127.15-5.06 127.75-4.88L127.75-4.88Q128.57-4.64 129.08-4.40Q129.60-4.16 129.97-3.68Q130.34-3.20 130.34-2.42L130.34-2.42Q130.34-1.75 130.00-1.18Q129.65-0.60 128.98-0.26Q128.30 0.08 127.38 0.08L127.38 0.08ZM131.80-8.38L133.48-8.38L133.48 0L131.80 0L131.80-8.38ZM142.30-8.39L142.30 0L140.62 0L136.81-5.75L136.81 0L135.13 0L135.13-8.39L136.81-8.39L140.62-2.63L140.62-8.39L142.30-8.39ZM151.72-5.86L149.78-5.86Q149.50-6.38 148.99-6.66Q148.49-6.94 147.82-6.94L147.82-6.94Q147.07-6.94 146.50-6.60Q145.92-6.26 145.60-5.64Q145.27-5.02 145.27-4.20L145.27-4.20Q145.27-3.36 145.60Line truncated
|
||||
</svg>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Headline -->
|
||||
<div class="headline">
|
||||
<div class="headline-main">MAKE YOUR OWN</div>
|
||||
<div class="headline-sub">KARAOKE VIDEOS</div>
|
||||
</div>
|
||||
|
||||
<!-- Subtitle -->
|
||||
<div class="subtitle">
|
||||
Turn any song into a professional karaoke video with synced lyrics, vocal removal, and automatic YouTube publishing.
|
||||
</div>
|
||||
|
||||
<!-- How it works -->
|
||||
<div class="steps">
|
||||
<div class="step">
|
||||
<div class="step-number">1</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Pick any song</div>
|
||||
<div class="step-desc">Search by artist & title or paste a YouTube link</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">2</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Our system does the work</div>
|
||||
<div class="step-desc">Vocals removed, lyrics synced, video rendered automatically</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">3</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Review & correct the lyrics and instrumental</div>
|
||||
<div class="step-desc">Fine-tune everything before publishing</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">4</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Download or publish to YouTube</div>
|
||||
<div class="step-desc">Get your finished karaoke video in minutes</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<!-- CTA with QR code -->
|
||||
<div class="cta-section">
|
||||
<div class="qr-container">
|
||||
<!-- Replace src with actual QR code image path -->
|
||||
<img src="{{QR_DATA_URL}}" alt="QR Code - nomadkaraoke.com/r/{{REFERRAL_CODE_LOWER}}">
|
||||
</div>
|
||||
<div class="cta-text">
|
||||
<div class="cta-label">First track free + {{DISCOUNT_PERCENT}}% off with this link</div>
|
||||
<div class="cta-url">NOMADKARAOKE.COM/R/<span class="referral-code">{{REFERRAL_CODE}}</span></div>
|
||||
<div class="cta-note">Scan the QR code or visit the link above</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bottom -->
|
||||
<div class="bottom">
|
||||
<div class="bottom-features">
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">🎤</span>
|
||||
<span>Any Song</span>
|
||||
</div>
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">⚡</span>
|
||||
<span>Automatic</span>
|
||||
</div>
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">🎬</span>
|
||||
<span>Pro Quality</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bottom-tagline">Wherever you are, sing!</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,359 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Nomad Karaoke - Make Your Own Karaoke Videos</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
*, html { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
@page {
|
||||
size: 8.5in 11in;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 8.5in;
|
||||
height: 11in;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
font-family: 'Outfit', sans-serif;
|
||||
background: #faf8f5;
|
||||
color: #1a1a1a;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Simple gradient background */
|
||||
.bg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(180deg, #faf8f5 0%, #f3eff8 100%);
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.content {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 0.6in 0.65in 0.5in;
|
||||
}
|
||||
|
||||
/* Logo at top */
|
||||
.logo-container {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.logo-svg {
|
||||
width: 260px;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
/* Headline */
|
||||
.headline {
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
text-align: center;
|
||||
line-height: 0.92;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.headline-main {
|
||||
font-size: 96px;
|
||||
letter-spacing: 3px;
|
||||
background: linear-gradient(135deg, #c45aff 0%, #ff7acc 50%, #ff5a8a 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.headline-sub {
|
||||
font-size: 62px;
|
||||
letter-spacing: 2px;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
|
||||
/* Subtitle */
|
||||
.subtitle {
|
||||
font-size: 20px;
|
||||
font-weight: 500;
|
||||
color: #555;
|
||||
text-align: center;
|
||||
max-width: 5.5in;
|
||||
line-height: 1.4;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
/* Steps section */
|
||||
.steps {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
width: 100%;
|
||||
max-width: 6in;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.step {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.step-number {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
flex-shrink: 0;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(135deg, #c45aff, #ff7acc);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
font-size: 30px;
|
||||
color: #fff;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.step-content {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.step-title {
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
color: #1a1a1a;
|
||||
letter-spacing: -0.3px;
|
||||
}
|
||||
|
||||
.step-desc {
|
||||
font-size: 16px;
|
||||
font-weight: 400;
|
||||
color: #666;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* Divider */
|
||||
.divider {
|
||||
width: 80%;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, transparent, rgba(196, 90, 255, 0.3), rgba(255, 122, 204, 0.3), transparent);
|
||||
margin: 4px 0 24px;
|
||||
}
|
||||
|
||||
/* CTA section */
|
||||
.cta-section {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 40px;
|
||||
width: 100%;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.qr-container {
|
||||
width: 180px;
|
||||
height: 180px;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
border: 3px solid #e8e4e0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 4px 20px rgba(0,0,0,0.06);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.qr-container img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.qr-placeholder {
|
||||
font-size: 14px;
|
||||
color: #999;
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.cta-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.cta-label {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #888;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 2px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.cta-url {
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
font-size: 38px;
|
||||
letter-spacing: 2px;
|
||||
color: #1a1a1a;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cta-url .referral-code {
|
||||
background: linear-gradient(135deg, #ff7acc 0%, #c45aff 40%, #ff5a8a 70%, #ffdf6b 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
letter-spacing: 4px;
|
||||
}
|
||||
|
||||
.cta-note {
|
||||
font-size: 15px;
|
||||
color: #888;
|
||||
margin-top: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Bottom section */
|
||||
.bottom {
|
||||
margin-top: auto;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.bottom-features {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.bottom-feature {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.bottom-feature-icon {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.bottom-tagline {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #aaa;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
|
||||
@media print {
|
||||
body {
|
||||
-webkit-print-color-adjust: exact;
|
||||
print-color-adjust: exact;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="bg"></div>
|
||||
|
||||
<div class="content">
|
||||
<!-- Logo -->
|
||||
<div class="logo-container">
|
||||
<svg class="logo-svg" viewBox="45 60 255 135" xmlns="http://www.w3.org/2000/svg">
|
||||
<g fill="#ff7acc" transform="translate(48.368003845214844,62.62239074707031)"><g transform="translate(0,0)"><g transform="scale(1.4000000000000004)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill-opacity="0"><path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)"></path></g><g transform="translate(0,38.959999084472656)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill="#ff7acc" fill-opacity="0" transform="scale(1.02719)"><path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)"></path></g></g></g></g>
|
||||
<g fill-rule="" fill="#ffdf6b" transform="translate(5,111.788818359375)"><rect x="0" height="1" y="5.9832000732421875" width="14.278396606445312"></rect><rect height="1" y="5.9832000732421875" width="14.278396606445312" x="218.985595703125"></rect><g transform="translate(17.278396606445312,0)"><g transform="scale(1.2800000000000002)"><path d="M10.21-8.38L12.02-8.38L9.68 0L7.70 0L6.13-5.96L4.49 0L2.52 0.01L0.26-8.38L2.06-8.38L3.54-1.87L5.24-8.38L7.12-8.38L8.72-1.91L10.21-8.38ZM18.38-8.38L20.06-8.38L20.06 0L18.38 0L18.38-3.56L14.80-3.56L14.80 0L13.12 0L13.12-8.38L14.80-8.38L14.80-4.93L18.38-4.93L18.38-8.38ZM26.58-7.02L23.40-7.02L23.40-4.92L26.22-4.92L26.22-3.59L23.40-3.59L23.40-1.37L26.58-1.37L26.58 0L21.72 0L21.72-8.39L26.58-8.39L26.58-7.02ZM34.37 0L32.42 0L30.58-3.26L29.78-3.26L29.78 0L28.10 0L28.10-8.38L31.25-8.38Q32.22-8.38 32.90-8.03Q33.59-7.69 33.93-7.11Q34.27-6.53 34.27-5.81L34.27-5.81Q34.27-4.98 33.79-4.31Q33.31-3.65 32.36-3.40L32.36-3.40L34.37 0ZM29.78-6.98L29.78-4.52L31.19-4.52Q31.87-4.52 32.21-4.85Q32.54-5.18 32.54-5.77L32.54-5.77Q32.54-6.35 32.21-6.67Q31.87-6.98 31.19-6.98L31.19-6.98L29.78-6.98ZM40.66-7.02L37.48-7.02L37.48-4.92L40.30-4.92L40.30-3.59L37.48-3.59L37.48-1.37L40.66-1.37L40.66 0L35.80 0L35.80-8.39L40.66-8.39L40.66-7.02ZM47.92-8.38L49.70-8.38L46.63 0L44.59 0L41.52-8.38L43.32-8.38L45.62-1.72L47.92-8.38ZM55.57-7.02L52.39-7.02L52.39-4.92L55.21-4.92L55.21-3.59L52.39-3.59L52.39-1.37L55.57-1.37L55.57 0L50.71 0L50.71-8.39L55.57-8.39L55.57-7.02ZM63.36 0L61.42 0L59.57-3.26L58.78-3.26L58.78 0L57.10 0L57.10-8.38L60.24-8.38Q61.21-8.38 61.90-8.03Q62.58-7.69 62.92-7.11Q63.26-6.53 63.26-5.81L63.26-5.81Q63.26-4.98 62.78-4.31Q62.30-3.65 61.36-3.40L61.36-3.40L63.36 0ZM58.78-6.98L58.78-4.52L60.18-4.52Q60.86-4.52 61.20-4.85Q61.54-5.18 61.54-5.77L61.54-5.77Q61.54-6.35 61.20-6.67Q60.86-6.98 60.18-6.98L60.18-6.98L58.78-6.98ZM72.43-8.38L74.30-8.38L71.47-2.92L71.47 0L69.79 0L69.79-2.92L66.95-8.38L68.84-8.38L70.64-4.55L72.43-8.38ZM79.16 0.08Q77.99 0.08 77.00-0.47Q76.02-1.02 75.44-2.00Q74.87-2.98 74.87-4.21L74.87-4.21Q74.87-5.44 75.44-6.41Q76.02-7.39 77.00-7.94Q77.99-8.50 79.16-8.50L79.16-8.50Q80.35-8.50 81.33-7.94Q82.31-7.39 82.88-6.41Q83.45-5.44 83.45-4.21L83.45-4.21Q83.45-2.98 82.88-2.00Q82.31-1.02 81.32-0.47Q80.34 0.08 79.16 0.08L79.16 0.08ZM79.16-1.42Q79.92-1.42 80.50-1.76Q81.07-2.10 81.40-2.74Q81.72-3.37 81.72-4.21L81.72-4.21Q81.72-5.05 81.40-5.68Q81.07-6.31 80.50-6.65Q79.92-6.98 79.16-6.98L79.16-6.98Q78.41-6.98 77.83-6.65Q77.24-6.31 76.92-5.68Q76.60-5.05 76.60-4.21L76.60-4.21Q76.60-3.37 76.92-2.74Q77.24-2.10 77.83-1.76Q78.41-1.42 79.16-1.42L79.16-1.42ZM84.67-8.38L86.35-8.38L86.35-3.19Q86.35-2.34 86.80-1.89Q87.24-1.44 88.04-1.44L88.04-1.44Q88.86-1.44 89.30-1.89Q89.75-2.34 89.75-3.19L89.75-3.19L89.75-8.38L91.44-8.38L91.44-3.20Q91.44-2.14 90.98-1.40Q90.52-0.66 89.74-0.29Q88.97 0.08 88.02 0.08L88.02 0.08Q87.08 0.08 86.32-0.29Q85.56-0.66 85.12-1.40Q84.67-2.14 84.67-3.20L84.67-3.20L84.67-8.38ZM101.60 0L101.05-1.60L97.72-1.60L97.16 0L95.40 0L98.41-8.39L100.37-8.39L103.38 0L101.60 0ZM98.17-2.94L100.60-2.94L99.38-6.44L98.17-2.94ZM110.77 0L108.83 0L106.98-3.26L106.19-3.26L106.19 0L104.51 0L104.51-8.38L107.65-8.38Q108.62-8.38 109.31-8.03Q109.99-7.69 110.33-7.11Q110.68-6.53 110.68-5.81L110.68-5.81Q110.68-4.98 110.20-4.31Q109.72-3.65 108.77-3.40L108.77-3.40L110.77 0ZM106.19-6.98L106.19-4.52L107.59-4.52Q108.28-4.52 108.61-4.85Q108.95-5.18 108.95-5.77L108.95-5.77Q108.95-6.35 108.61-6.67Q108.28-6.98 107.59-6.98L107.59-6.98L106.19-6.98ZM117.06-7.02L113.88-7.02L113.88-4.92L116.70-4.92L116.70-3.59L113.88-3.59L113.88-1.37L117.06-1.37L117.06 0L112.20 0L112.20-8.39L117.06-8.39L117.06-7.02ZM118.72-1.76L120.42-1.76L119.02 1.61L117.94 1.61L118.72-1.76ZM127.38 0.08Q126.50 0.08 125.80-0.22Q125.10-0.52 124.69-1.08Q124.28-1.64 124.27-2.41L124.27-2.41L126.07-2.41Q126.11-1.90 126.44-1.60Q126.77-1.30 127.34-1.30L127.34-1.30Q127.93-1.30 128.27-1.58Q128.60-1.86 128.60-2.32L128.60-2.32Q128.60-2.69 128.38-2.93Q128.15-3.17 127.81-3.31Q127.46-3.44 126.86-3.61L126.86-3.61Q126.05-3.85 125.54-4.09Q125.03-4.32 124.66-4.79Q124.30-5.27 124.30-6.06L124.30-6.06Q124.30-6.80 124.67-7.36Q125.04-7.91 125.71-8.20Q126.38-8.50 127.25-8.50L127.25-8.50Q128.54-8.50 129.35-7.87Q130.16-7.24 130.25-6.11L130.25-6.11L128.40-6.11Q128.38-6.54 128.03-6.82Q127.69-7.10 127.13-7.10L127.13-7.10Q126.64-7.10 126.34-6.85Q126.05-6.60 126.05-6.12L126.05-6.12Q126.05-5.78 126.27-5.56Q126.49-5.34 126.82-5.20Q127.15-5.06 127.75-4.88L127.75-4.88Q128.57-4.64 129.08-4.40Q129.60-4.16 129.97-3.68Q130.34-3.20 130.34-2.42L130.34-2.42Q130.34-1.75 130.00-1.18Q129.65-0.60 128.98-0.26Q128.30 0.08 127.38 0.08L127.38 0.08ZM131.80-8.38L133.48-8.38L133.48 0L131.80 0L131.80-8.38ZM142.30-8.39L142.30 0L140.62 0L136.81-5.75L136.81 0L135.13 0L135.13-8.39L136.81-8.39L140.62-2.63L140.62-8.39L142.30-8.39ZM151.72-5.86L149.78-5.86Q149.50-6.38 148.99-6.66Q148.49-6.94 147.82-6.94L147.82-6.94Q147.07-6.94 146.50-6.60Q145.92-6.26 145.60-5.64Q145.27-5.02 145.27-4.20L145.27-4.20Q145.27-3.36 145.60Line truncated
|
||||
</svg>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Headline -->
|
||||
<div class="headline">
|
||||
<div class="headline-main">MAKE YOUR OWN</div>
|
||||
<div class="headline-sub">KARAOKE VIDEOS</div>
|
||||
</div>
|
||||
|
||||
<!-- Subtitle -->
|
||||
<div class="subtitle">
|
||||
Turn any song into a professional karaoke video with synced lyrics, vocal removal, and automatic YouTube publishing.
|
||||
</div>
|
||||
|
||||
<!-- How it works -->
|
||||
<div class="steps">
|
||||
<div class="step">
|
||||
<div class="step-number">1</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Pick any song</div>
|
||||
<div class="step-desc">Search by artist & title or paste a YouTube link</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">2</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Our system does the work</div>
|
||||
<div class="step-desc">Vocals removed, lyrics synced, video rendered automatically</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">3</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Review & correct the lyrics and instrumental</div>
|
||||
<div class="step-desc">Fine-tune everything before publishing</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">4</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Download or publish to YouTube</div>
|
||||
<div class="step-desc">Get your finished karaoke video in minutes</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<!-- CTA with QR code -->
|
||||
<div class="cta-section">
|
||||
<div class="qr-container">
|
||||
<!-- Replace src with actual QR code image path -->
|
||||
<img src="{{QR_DATA_URL}}" alt="QR Code - nomadkaraoke.com/r/{{REFERRAL_CODE_LOWER}}">
|
||||
</div>
|
||||
<div class="cta-text">
|
||||
<div class="cta-label">First track free + {{DISCOUNT_PERCENT}}% off with this link</div>
|
||||
<div class="cta-url">NOMADKARAOKE.COM/R/<span class="referral-code">{{REFERRAL_CODE}}</span></div>
|
||||
<div class="cta-note">Scan the QR code or visit the link above</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bottom -->
|
||||
<div class="bottom">
|
||||
<div class="bottom-features">
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">🎤</span>
|
||||
<span>Any Song</span>
|
||||
</div>
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">⚡</span>
|
||||
<span>Automatic</span>
|
||||
</div>
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">🎬</span>
|
||||
<span>Pro Quality</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bottom-tagline">Wherever you are, sing!</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# Verify email notification was called with matching args
|
||||
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(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# User still gets credits even though email failed
|
||||
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,857 @@
|
||||
"""
|
||||
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
|
||||
|
||||
@patch('backend.services.user_service.get_settings')
|
||||
@patch('backend.services.user_service.firestore')
|
||||
def test_skips_evaluation_for_test_emails(self, mock_fs, mock_settings):
|
||||
"""grant_welcome_credits_if_eligible skips AI evaluation for @inbox.testmail.app emails."""
|
||||
mock_settings.return_value = MagicMock(google_cloud_project='test')
|
||||
mock_db = MagicMock()
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
user = User(email="e2e.test@inbox.testmail.app", 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("e2e.test@inbox.testmail.app")
|
||||
# AI evaluation should NOT have been called
|
||||
mock_eval.return_value.evaluate.assert_not_called()
|
||||
|
||||
assert granted is True
|
||||
assert status == "granted"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 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"
|
||||
@@ -0,0 +1,150 @@
|
||||
"""
|
||||
Tests for Google OIDC token validation in AuthService.
|
||||
|
||||
Cloud Scheduler and Cloud Tasks send OIDC JWTs signed by Google.
|
||||
The auth service must validate these and grant admin access for
|
||||
requests from the configured service account.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from backend.services.auth_service import AuthService, AuthResult, UserType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_service():
|
||||
"""Create an AuthService instance with mocked Firestore."""
|
||||
with patch("backend.services.auth_service.FirestoreService"):
|
||||
service = AuthService()
|
||||
service._scheduler_service_account = "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
|
||||
return service
|
||||
|
||||
|
||||
# A fake JWT-shaped token (3 dot-separated parts)
|
||||
FAKE_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20ifQ.signature"
|
||||
|
||||
|
||||
class TestOidcTokenValidation:
|
||||
"""Tests for _validate_oidc_token."""
|
||||
|
||||
def test_non_jwt_returns_none(self, auth_service):
|
||||
"""Non-JWT tokens (no dots) should return None immediately."""
|
||||
result = auth_service._validate_oidc_token("simple-token-no-dots")
|
||||
assert result is None
|
||||
|
||||
def test_two_dots_not_three_parts_returns_none(self, auth_service):
|
||||
"""Tokens with wrong number of dots should return None."""
|
||||
result = auth_service._validate_oidc_token("only.one.dot-but-not-jwt")
|
||||
# This has 2 dots = 3 parts, so it will attempt OIDC validation
|
||||
# but fail signature verification. That's fine — it returns None.
|
||||
# A token with 1 dot should be skipped entirely.
|
||||
result_one_dot = auth_service._validate_oidc_token("one.dot")
|
||||
assert result_one_dot is None
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_valid_oidc_from_allowed_sa(self, mock_verify, auth_service):
|
||||
"""Valid OIDC token from the configured service account grants admin."""
|
||||
mock_verify.return_value = {
|
||||
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
|
||||
"email_verified": True,
|
||||
"iss": "https://accounts.google.com",
|
||||
"aud": "https://api.nomadkaraoke.com/api/internal/process-stale-reviews",
|
||||
}
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is not None
|
||||
assert result.is_valid is True
|
||||
assert result.is_admin is True
|
||||
assert result.user_type == UserType.ADMIN
|
||||
assert result.remaining_uses == -1
|
||||
assert result.user_email == "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_oidc_from_wrong_sa_returns_none(self, mock_verify, auth_service):
|
||||
"""OIDC token from a different service account is rejected."""
|
||||
mock_verify.return_value = {
|
||||
"email": "attacker@evil-project.iam.gserviceaccount.com",
|
||||
"email_verified": True,
|
||||
"iss": "https://accounts.google.com",
|
||||
}
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is None
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_expired_oidc_token_returns_none(self, mock_verify, auth_service):
|
||||
"""Expired OIDC token raises ValueError and returns None."""
|
||||
mock_verify.side_effect = ValueError("Token expired")
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is None
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_invalid_signature_returns_none(self, mock_verify, auth_service):
|
||||
"""Token with invalid signature raises ValueError and returns None."""
|
||||
mock_verify.side_effect = ValueError("Could not verify token signature")
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is None
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_network_error_returns_none(self, mock_verify, auth_service):
|
||||
"""Network error fetching Google certs returns None gracefully."""
|
||||
mock_verify.side_effect = Exception("Connection timeout")
|
||||
|
||||
result = auth_service._validate_oidc_token(FAKE_JWT)
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestValidateTokenFullOidc:
|
||||
"""Tests that OIDC validation is properly integrated into validate_token_full."""
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_oidc_token_grants_admin_via_validate_token_full(self, mock_verify, auth_service):
|
||||
"""OIDC token flows through validate_token_full and grants admin."""
|
||||
mock_verify.return_value = {
|
||||
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
|
||||
"email_verified": True,
|
||||
}
|
||||
|
||||
# Mock Firestore to not interfere
|
||||
auth_service.firestore.get_token = MagicMock(return_value=None)
|
||||
|
||||
result = auth_service.validate_token_full(FAKE_JWT)
|
||||
|
||||
assert result.is_valid is True
|
||||
assert result.is_admin is True
|
||||
assert result.user_type == UserType.ADMIN
|
||||
|
||||
def test_admin_token_still_works(self, auth_service):
|
||||
"""Admin tokens from env var still take priority over OIDC."""
|
||||
auth_service.admin_tokens = ["test-admin-token"]
|
||||
|
||||
result = auth_service.validate_token_full("test-admin-token")
|
||||
|
||||
assert result.is_valid is True
|
||||
assert result.is_admin is True
|
||||
assert result.message == "Admin access granted"
|
||||
|
||||
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
|
||||
def test_failed_oidc_falls_through_to_firestore(self, mock_verify, auth_service):
|
||||
"""If OIDC validation fails, token is still checked against Firestore."""
|
||||
mock_verify.side_effect = ValueError("Invalid token")
|
||||
|
||||
# Firestore has a valid token
|
||||
auth_service.firestore.get_token = MagicMock(return_value={
|
||||
"type": "unlimited",
|
||||
"active": True,
|
||||
"max_uses": -1,
|
||||
"user_email": "user@example.com",
|
||||
})
|
||||
|
||||
result = auth_service.validate_token_full(FAKE_JWT)
|
||||
|
||||
assert result.is_valid is True
|
||||
assert result.user_type == UserType.UNLIMITED
|
||||
@@ -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
|
||||
@@ -319,3 +319,59 @@ class TestRenderVideoWorkerUsesCorrectedData:
|
||||
# Metadata and original_segments preserved
|
||||
assert original_data['metadata']['preserved'] is True
|
||||
assert original_data['original_segments'][0]['id'] == 1
|
||||
|
||||
|
||||
class TestCompleteReviewSkipsEmptyCorrections:
|
||||
"""Test that complete_review doesn't write corrections_updated.json when no corrections.
|
||||
|
||||
Bug scenario: Completing review via admin API without corrections payload writes
|
||||
an empty {} to corrections_updated.json. Downstream render workers then get
|
||||
KeyError: 'corrections' when processing it.
|
||||
"""
|
||||
|
||||
def test_no_corrections_key_skips_upload(self):
|
||||
"""When updated_data has only instrumental_selection, no corrections file is written."""
|
||||
# Simulate what the endpoint does with the corrections_to_save logic
|
||||
updated_data = {"instrumental_selection": "clean"}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# This is the guard we added
|
||||
should_write = corrections_to_save and "corrections" in corrections_to_save
|
||||
assert not should_write, "Should not write corrections_updated.json for empty payload"
|
||||
|
||||
def test_with_corrections_key_allows_upload(self):
|
||||
"""When updated_data has corrections, the file should be written."""
|
||||
updated_data = {
|
||||
"corrections": [{"id": 1, "type": "edit"}],
|
||||
"corrected_segments": [{"id": 1, "text": "fixed"}],
|
||||
"instrumental_selection": "with_backing",
|
||||
}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
should_write = corrections_to_save and "corrections" in corrections_to_save
|
||||
assert should_write, "Should write corrections_updated.json when corrections present"
|
||||
|
||||
def test_empty_dict_payload_skips_upload(self):
|
||||
"""When updated_data is effectively empty after removing instrumental_selection."""
|
||||
updated_data = {"instrumental_selection": "clean", "some_other_key": "value"}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# Has content but no "corrections" key
|
||||
should_write = corrections_to_save and "corrections" in corrections_to_save
|
||||
assert not should_write, "Should not write without corrections key"
|
||||
|
||||
def test_render_worker_handles_empty_corrections_gracefully(self):
|
||||
"""Document that render workers skip empty corrections_updated.json.
|
||||
|
||||
Both GCE and Cloud Run workers now check for 'corrections' key
|
||||
before passing to CorrectionOperations.update_correction_result_with_data().
|
||||
"""
|
||||
# Simulates what the workers do on download
|
||||
empty_updated_data = {}
|
||||
has_valid_corrections = empty_updated_data and "corrections" in empty_updated_data
|
||||
assert not has_valid_corrections, "Empty dict should not be treated as valid corrections"
|
||||
|
||||
# Dict with irrelevant keys
|
||||
bad_updated_data = {"some_key": "value"}
|
||||
has_valid_corrections = bad_updated_data and "corrections" in bad_updated_data
|
||||
assert not has_valid_corrections, "Dict without corrections key should not be valid"
|
||||
@@ -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'],
|
||||
)
|
||||
Loaded 100 of 571 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user