mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-27 09:28:26 +09:00
Compare commits
79
Commits
No files matched your search
@@ -0,0 +1,407 @@
|
||||
# Plan: Add Retry Logic for Flacfetch Download Failures
|
||||
|
||||
**Created:** 2026-02-10
|
||||
**Branch:** feat/sess-20260210-1158-investigate-job-749141f8
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Job 749141f8 failed with error: "Audio download failed: Remote download by ID failed: Download by ID request failed:"
|
||||
|
||||
Investigation revealed **multiple related issues** when flacfetch network calls fail:
|
||||
|
||||
1. **No retry logic** - A single network hiccup causes immediate job failure
|
||||
2. **Missing source info** - When download fails, source_id/source_name aren't saved to job
|
||||
3. **Broken retry button** - Can't retry because no source info was persisted
|
||||
4. **Silent UI failures** - Frontend doesn't show retry error messages to user
|
||||
|
||||
### Root Cause
|
||||
|
||||
Audio search flow saves selection info to `state_data`, but doesn't save download parameters (source_id, source_name, etc.) to the job document until AFTER download succeeds. If the flacfetch call fails (network error), the job fails with no way to retry.
|
||||
|
||||
### Solution
|
||||
|
||||
This plan fixes all four issues:
|
||||
- Add retry logic to flacfetch client (network resilience)
|
||||
- Persist download info before attempting download (enables retry)
|
||||
- Update retry endpoint to handle audio search jobs
|
||||
- Show error messages in frontend when retry fails
|
||||
|
||||
## Requirements
|
||||
|
||||
### Functional Requirements - Flacfetch Retry Logic
|
||||
- [x] Retry `download_by_id()` on `httpx.RequestError` (network failures)
|
||||
- [x] Use exponential backoff spread over ~5 minutes
|
||||
- [x] Configurable max retries via environment variable
|
||||
- [x] Log each retry attempt with context
|
||||
- [x] Do NOT retry on HTTP 4xx errors (client errors - immediate failure)
|
||||
- [x] Do retry on HTTP 5xx errors (server errors - transient)
|
||||
|
||||
### Functional Requirements - Persist Download Info
|
||||
- [x] Save source_id, source_name, target_file, download_url to job document
|
||||
- [x] Save BEFORE attempting download (not after)
|
||||
- [x] Store in top-level fields for easy retry access
|
||||
- [x] Preserve existing state_data fields (selected_audio_index, etc.)
|
||||
|
||||
### Functional Requirements - Retry Endpoint
|
||||
- [x] Add case for audio search jobs in `/jobs/{id}/retry` endpoint
|
||||
- [x] Check for saved download params (source_id, source_name)
|
||||
- [x] Re-download using saved params
|
||||
- [x] Clear error state before retrying
|
||||
- [x] Trigger appropriate workers after successful download
|
||||
|
||||
### Functional Requirements - Frontend Error Handling
|
||||
- [x] Show toast notification when retry fails
|
||||
- [x] Display actual error message from API
|
||||
- [x] Don't just console.error - make it visible to user
|
||||
|
||||
### Non-Functional Requirements
|
||||
- [x] Minimal code changes (use existing patterns)
|
||||
- [x] Clear error messages that include retry context
|
||||
- [x] Backwards compatible (no breaking changes)
|
||||
- [x] Should not significantly increase total timeout duration
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Architecture Decisions
|
||||
|
||||
**Option 1: Tenacity library (Recommended)**
|
||||
- ✅ Industry standard, well-tested
|
||||
- ✅ Declarative retry configuration
|
||||
- ✅ Built-in exponential backoff
|
||||
- ✅ Already used in project (check `poetry.lock`)
|
||||
- ❌ New dependency if not already present
|
||||
|
||||
**Option 2: Manual retry loop**
|
||||
- ✅ No new dependencies
|
||||
- ✅ Full control over logic
|
||||
- ❌ More code to maintain
|
||||
- ❌ Easy to get wrong (edge cases)
|
||||
|
||||
**Decision:** Use **tenacity** if already in dependencies, otherwise implement manual retry loop.
|
||||
|
||||
### Retry Strategy
|
||||
|
||||
```python
|
||||
# Retry on network errors only (RequestError)
|
||||
# Do NOT retry on:
|
||||
# - HTTP 4xx (client errors like 400, 401, 404)
|
||||
# - Already completed downloads
|
||||
# Do retry on:
|
||||
# - httpx.RequestError (connection timeout, refused, DNS failure)
|
||||
# - HTTP 5xx (server errors - service temporarily down)
|
||||
|
||||
Max retries: 8 (total 9 attempts)
|
||||
Backoff: Exponential with cap, multiplier=2, min=10s, max=60s
|
||||
- Attempt 1: immediate
|
||||
- Attempt 2: wait 10s
|
||||
- Attempt 3: wait 20s
|
||||
- Attempt 4: wait 40s
|
||||
- Attempt 5: wait 60s (capped)
|
||||
- Attempt 6: wait 60s (capped)
|
||||
- Attempt 7: wait 60s (capped)
|
||||
- Attempt 8: wait 60s (capped)
|
||||
- Attempt 9: wait 60s (capped)
|
||||
Total max time: ~370s (6+ minutes) of backoff + request timeouts
|
||||
|
||||
This gives the flacfetch service time to recover from restarts,
|
||||
network issues, or temporary VM problems.
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
Add to `backend/config.py`:
|
||||
```python
|
||||
# Flacfetch client retry settings
|
||||
flacfetch_retry_max_attempts: int = int(os.getenv("FLACFETCH_RETRY_MAX_ATTEMPTS", "9")) # Total attempts (1 initial + 8 retries)
|
||||
flacfetch_retry_min_wait: float = float(os.getenv("FLACFETCH_RETRY_MIN_WAIT", "10.0")) # seconds
|
||||
flacfetch_retry_max_wait: float = float(os.getenv("FLACFETCH_RETRY_MAX_WAIT", "60.0")) # seconds
|
||||
```
|
||||
|
||||
### Error Message Improvements
|
||||
|
||||
Change from:
|
||||
```
|
||||
Download by ID request failed:
|
||||
```
|
||||
|
||||
To:
|
||||
```
|
||||
Download by ID request failed after 4 attempts: [ConnectTimeout] Connection to http://10.0.0.5:8080 timed out
|
||||
```
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Check Dependencies
|
||||
1. [ ] Check if `tenacity` is in `pyproject.toml` dependencies
|
||||
2. [ ] If not present, add `tenacity = "^8.2.0"` to dependencies
|
||||
3. [ ] Run `poetry lock` if dependencies changed
|
||||
|
||||
### Phase 2: Add Configuration
|
||||
4. [ ] Add retry configuration to `backend/config.py`
|
||||
- `flacfetch_retry_max_attempts = 9`
|
||||
- `flacfetch_retry_min_wait = 10.0`
|
||||
- `flacfetch_retry_max_wait = 60.0`
|
||||
|
||||
### Phase 3: Implement Flacfetch Retry Logic
|
||||
5. [ ] Import tenacity in `backend/services/flacfetch_client.py`
|
||||
6. [ ] Create retry decorator with:
|
||||
- Retry on `httpx.RequestError`
|
||||
- Retry on `httpx.HTTPStatusError` with 5xx status
|
||||
- Stop on `httpx.HTTPStatusError` with 4xx status
|
||||
- Exponential backoff with cap at 60s
|
||||
- Before-sleep logging callback
|
||||
7. [ ] Apply decorator to `download_by_id()` method
|
||||
8. [ ] Improve error messages to include:
|
||||
- Number of attempts made
|
||||
- Original exception type and message
|
||||
|
||||
### Phase 4: Persist Download Info Before Download
|
||||
9. [ ] Update `audio_search.py:_download_and_start_processing()`
|
||||
10. [ ] After getting source info from selected result (line 307-311)
|
||||
11. [ ] **Save to job document BEFORE download attempt:**
|
||||
```python
|
||||
job_manager.update_job(job_id, {
|
||||
'audio_source_type': 'audio_search',
|
||||
'source_name': source_name,
|
||||
'source_id': source_id,
|
||||
'target_file': target_file,
|
||||
'download_url': download_url,
|
||||
})
|
||||
```
|
||||
12. [ ] Then proceed with download (existing code)
|
||||
13. [ ] Add to Job model if needed (check if fields exist)
|
||||
|
||||
### Phase 5: Update Retry Endpoint for Audio Search
|
||||
14. [ ] Update `backend/api/routes/jobs.py:retry_job()`
|
||||
15. [ ] Add new case before "no input audio" error (line ~1088)
|
||||
16. [ ] Check if job has saved download params:
|
||||
```python
|
||||
elif job.audio_source_type == 'audio_search' and job.source_id:
|
||||
# Has audio search download info - retry download
|
||||
```
|
||||
17. [ ] Re-call audio search download logic with saved params
|
||||
18. [ ] Or refactor download into reusable function
|
||||
|
||||
### Phase 6: Frontend Error Handling
|
||||
19. [ ] Update `frontend/components/job/JobActions.tsx`
|
||||
20. [ ] Add toast notification library (check if exists)
|
||||
21. [ ] In `handleRetry()` catch block, show toast:
|
||||
```typescript
|
||||
catch (error) {
|
||||
const message = error.response?.data?.detail || "Failed to retry job"
|
||||
toast.error(message)
|
||||
console.error("Failed to retry job:", error)
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 7: Testing - Flacfetch Retry
|
||||
22. [ ] Add unit tests to `backend/tests/test_flacfetch_client.py`
|
||||
23. [ ] Test retry on RequestError (mock fails N times then succeeds)
|
||||
24. [ ] Test no retry on 4xx errors
|
||||
25. [ ] Test retry on 5xx errors
|
||||
26. [ ] Test max retries exhausted
|
||||
27. [ ] Verify logging output includes attempt numbers
|
||||
|
||||
### Phase 8: Testing - End-to-End
|
||||
28. [ ] Test audio search job with flacfetch down
|
||||
29. [ ] Verify source info is saved even when download fails
|
||||
30. [ ] Verify retry button works after source info saved
|
||||
31. [ ] Test retry succeeds when flacfetch comes back up
|
||||
32. [ ] Verify error toast appears when retry fails
|
||||
|
||||
### Phase 9: Documentation
|
||||
33. [ ] Update `backend/services/flacfetch_client.py` docstring
|
||||
34. [ ] Add to `docs/LESSONS-LEARNED.md`:
|
||||
- "Always add retries for external service calls"
|
||||
- "Save operation parameters before attempting operations"
|
||||
- "Persist enough state to enable retry from any failure point"
|
||||
35. [ ] Update `docs/ARCHITECTURE.md` if needed
|
||||
36. [ ] Document the new job fields in API.md
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/config.py` | Modify | Add retry configuration variables |
|
||||
| `backend/services/flacfetch_client.py` | Modify | Add retry logic to `download_by_id()` |
|
||||
| `backend/api/routes/audio_search.py` | Modify | Save download info before attempting download |
|
||||
| `backend/api/routes/jobs.py` | Modify | Add audio search case to retry endpoint |
|
||||
| `backend/models/job.py` | Modify (maybe) | Add fields: source_name, source_id, target_file, download_url |
|
||||
| `frontend/components/job/JobActions.tsx` | Modify | Show error toast when retry fails |
|
||||
| `backend/tests/test_flacfetch_client.py` | Modify | Add retry tests |
|
||||
| `backend/tests/test_audio_search.py` | Modify | Test download info persistence |
|
||||
| `backend/tests/test_jobs.py` | Modify | Test retry with audio search jobs |
|
||||
| `pyproject.toml` | Modify (maybe) | Add tenacity if not present |
|
||||
| `docs/LESSONS-LEARNED.md` | Modify | Document patterns |
|
||||
| `docs/API.md` | Modify | Document new job fields |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (`backend/tests/test_flacfetch_client.py`)
|
||||
|
||||
1. **Test retry on RequestError**
|
||||
```python
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_retries_on_network_error():
|
||||
"""Should retry 3 times on connection errors."""
|
||||
client = FlacfetchClient(base_url="http://test", api_key="key")
|
||||
|
||||
with patch("httpx.AsyncClient.post") as mock_post:
|
||||
# Fail 2 times, then succeed
|
||||
mock_post.side_effect = [
|
||||
httpx.RequestError("Connection timeout"),
|
||||
httpx.RequestError("Connection refused"),
|
||||
Mock(json=lambda: {"download_id": "test123"}, status_code=200),
|
||||
]
|
||||
|
||||
result = await client.download_by_id("YouTube", "abc123")
|
||||
|
||||
assert result == "test123"
|
||||
assert mock_post.call_count == 3
|
||||
```
|
||||
|
||||
2. **Test no retry on 4xx errors**
|
||||
```python
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_no_retry_on_client_error():
|
||||
"""Should NOT retry on 400/401/404 errors."""
|
||||
client = FlacfetchClient(base_url="http://test", api_key="key")
|
||||
|
||||
with patch("httpx.AsyncClient.post") as mock_post:
|
||||
response = Mock(status_code=404, text="Not found")
|
||||
response.raise_for_status.side_effect = httpx.HTTPStatusError(
|
||||
"Not found", request=Mock(), response=response
|
||||
)
|
||||
mock_post.return_value = response
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="404"):
|
||||
await client.download_by_id("YouTube", "abc123")
|
||||
|
||||
assert mock_post.call_count == 1 # No retries
|
||||
```
|
||||
|
||||
3. **Test retry on 5xx errors**
|
||||
```python
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_retries_on_server_error():
|
||||
"""Should retry on 500/503 errors."""
|
||||
# Similar to test 1 but with HTTP 503 errors
|
||||
```
|
||||
|
||||
4. **Test max retries exhausted**
|
||||
```python
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_fails_after_max_retries():
|
||||
"""Should fail with clear message after max retries."""
|
||||
# All attempts fail, verify error message includes attempt count
|
||||
```
|
||||
|
||||
### Integration Tests
|
||||
|
||||
5. **Test with actual flacfetch service** (if available in test environment)
|
||||
- Verify retry doesn't break normal operation
|
||||
- Test with deliberate network issues
|
||||
|
||||
### Manual Testing
|
||||
|
||||
6. **Simulate network failure**
|
||||
```bash
|
||||
# Temporarily stop flacfetch VM
|
||||
gcloud compute instances stop flacfetch-service --zone=us-central1-a
|
||||
|
||||
# Submit a test job
|
||||
# Observe logs showing retry attempts
|
||||
|
||||
# Restart VM during retries
|
||||
gcloud compute instances start flacfetch-service --zone=us-central1-a
|
||||
|
||||
# Job should succeed
|
||||
```
|
||||
|
||||
7. **Test with intentional delays**
|
||||
- Add sleep in flacfetch API handler
|
||||
- Verify retries don't cause issues
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [x] ~~Is tenacity already in dependencies?~~ (Will check during implementation)
|
||||
- [x] ~~What's the appropriate total timeout budget?~~ - 9 attempts over ~6 minutes
|
||||
- [x] ~~Should we fix the Retry button UX in this PR?~~ - YES, it's the same root cause
|
||||
- [x] ~~Why did job 749141f8 fail before saving audio source info?~~ - Download info saved AFTER download, not before
|
||||
- [ ] Should we also add retries to `wait_for_download()`?
|
||||
- Probably NO - that already has its own polling/timeout logic
|
||||
- [ ] Should we add circuit breaker pattern?
|
||||
- Probably NO for now - keep it simple
|
||||
- Could add in future if we see cascading failures
|
||||
- [ ] Should retry logic be applied to other flacfetch methods?
|
||||
- `start_download()` - probably YES (same pattern)
|
||||
- `search()` - maybe YES (search can also have network issues)
|
||||
- `get_download_status()` - probably NO (polling already handles this)
|
||||
- **Decision**: Apply to `start_download()` too, skip `search()` for now
|
||||
- [ ] Which toast library should frontend use?
|
||||
- Check if already exists (react-hot-toast, sonner, etc.)
|
||||
- If not, add lightweight library
|
||||
- [ ] Should we save download params to state_data or top-level fields?
|
||||
- Top-level fields more visible and easier to query
|
||||
- **Decision**: Top-level fields (source_id, source_name, etc.)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
If this causes issues:
|
||||
|
||||
1. **Quick rollback**: Set env var `FLACFETCH_RETRY_MAX_ATTEMPTS=1` in Cloud Run
|
||||
- Disables retries without code change
|
||||
- Can deploy in ~2 minutes
|
||||
|
||||
2. **Full rollback**: Revert the PR
|
||||
- Git revert the merge commit
|
||||
- Deploy previous version
|
||||
|
||||
3. **Monitoring**: Watch for:
|
||||
- Increased request duration to flacfetch
|
||||
- Jobs timing out at higher layer (Cloud Tasks, Cloud Run)
|
||||
- Duplicate download attempts causing issues
|
||||
|
||||
## Success Criteria
|
||||
|
||||
- [ ] Jobs with transient flacfetch failures succeed instead of failing
|
||||
- [ ] Error messages are more informative (show attempts and root cause)
|
||||
- [ ] No increase in false positives (jobs that should fail, now hang)
|
||||
- [ ] All tests pass
|
||||
- [ ] No impact on successful jobs (retry overhead is minimal)
|
||||
|
||||
## Related Issues
|
||||
|
||||
### Job 749141f8 - The Incident
|
||||
|
||||
**What happened:**
|
||||
- User searched for audio via audio search
|
||||
- Selected "Elizabeth Moen - Songbird"
|
||||
- Backend tried to download via flacfetch
|
||||
- Flacfetch call failed with network error (connection timeout/refused)
|
||||
- Job immediately failed
|
||||
- No source info saved → Retry button broken
|
||||
- User sees "Retry" button but clicking does nothing (silent 400 error)
|
||||
|
||||
**How this fix helps:**
|
||||
1. ✅ Flacfetch retry logic → Download would have succeeded after retry
|
||||
2. ✅ Persist download info → Even if all retries fail, user can retry later
|
||||
3. ✅ Retry endpoint fix → Retry button will actually work
|
||||
4. ✅ Frontend toast → User sees helpful error if retry still fails
|
||||
|
||||
**Note:** Job 749141f8 cannot be fixed retroactively (no source info saved). But future jobs with same issue will be fixable via retry button.
|
||||
|
||||
### Future Work (Not in This PR)
|
||||
|
||||
Similar pattern should be applied to other external service calls:
|
||||
- AudioShake API (lyrics transcription)
|
||||
- Modal API (audio separation)
|
||||
- YouTube direct API calls (not via flacfetch)
|
||||
- Email sending (SendGrid)
|
||||
|
||||
## References
|
||||
|
||||
- [Tenacity documentation](https://tenacity.readthedocs.io/)
|
||||
- [LESSONS-LEARNED.md](docs/LESSONS-LEARNED.md) - External service response format mismatches
|
||||
- [flacfetch README](../../flacfetch/README.md) - Understanding the service
|
||||
@@ -0,0 +1,279 @@
|
||||
# Plan: Private (Non-Published) Tracks
|
||||
|
||||
**Created:** 2026-02-24
|
||||
**Branch:** feat/sess-20260224-1149-private-tracks
|
||||
**Status:** Implemented
|
||||
|
||||
## Overview
|
||||
|
||||
Add a `is_private` flag to jobs that changes distribution behavior:
|
||||
- **Dropbox**: Uses `Tracks-NonPublished` folder (not `Tracks-Organized`) with brand code `NOMADNP` (not `NOMAD`)
|
||||
- **YouTube**: Skipped entirely
|
||||
- **Google Drive**: Skipped entirely
|
||||
- **Email**: Completion email includes Dropbox link but no YouTube section
|
||||
- **Discord**: Still notified (for internal tracking)
|
||||
|
||||
Available to all users at job creation and toggleable by admin on existing jobs.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] All users can mark a job as "Private (Non-Published)" when creating it
|
||||
- [ ] Admin can toggle `is_private` on any existing job via admin dashboard
|
||||
- [ ] Private jobs upload to Dropbox at `Tracks-NonPublished` with `NOMADNP-XXXX` brand codes
|
||||
- [ ] Private jobs skip YouTube and Google Drive uploads entirely
|
||||
- [ ] Completion emails omit YouTube section when no YouTube URL (private jobs + any other edge case)
|
||||
- [ ] When admin toggles a completed job to private, existing outputs are auto-deleted
|
||||
- [ ] Discord notifications still fire for private jobs
|
||||
- [ ] Existing (non-private) jobs are completely unaffected (backward compatible)
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Core Design: Single Boolean Flag with Runtime Overrides
|
||||
|
||||
Store `is_private: bool = False` on the job model. At distribution time, a helper function returns effective distribution parameters based on this flag. This means:
|
||||
|
||||
- **Toggling is_private automatically changes all distribution behavior** - no need to manually update dropbox_path, brand_prefix, enable_youtube_upload, gdrive_folder_id
|
||||
- **Job fields still store the "normal" defaults** - the override happens at the config-to-orchestrator boundary
|
||||
- **Admin can flip one field** and everything adapts
|
||||
|
||||
### Key Helper Function
|
||||
|
||||
```python
|
||||
# In job_defaults_service.py
|
||||
def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings:
|
||||
"""Return distribution settings, applying private overrides if is_private=True."""
|
||||
if getattr(job, 'is_private', False):
|
||||
settings = get_settings()
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=settings.default_private_dropbox_path,
|
||||
brand_prefix=settings.default_private_brand_prefix,
|
||||
enable_youtube_upload=False,
|
||||
gdrive_folder_id=None,
|
||||
# Keep other settings from job (discord, youtube_description, etc.)
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=None,
|
||||
)
|
||||
# Non-private: return job's own settings
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=getattr(job, 'dropbox_path', None),
|
||||
brand_prefix=getattr(job, 'brand_prefix', None),
|
||||
enable_youtube_upload=getattr(job, 'enable_youtube_upload', False),
|
||||
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=getattr(job, 'youtube_description_template', None),
|
||||
)
|
||||
```
|
||||
|
||||
This helper is used in both distribution paths (orchestrator and native fallback).
|
||||
|
||||
### Distribution Paths That Need Changes
|
||||
|
||||
Two code paths handle distribution (see LESSONS-LEARNED: "Fix Both Sides of Dual Code Paths"):
|
||||
|
||||
1. **Orchestrator path** (`video_worker_orchestrator.py`): Primary path. `create_orchestrator_config_from_job()` uses the helper to build config.
|
||||
2. **Native distribution path** (`video_worker.py` → `_handle_native_distribution()`): Fallback path. Also uses the helper instead of reading job fields directly.
|
||||
|
||||
### Email Template Change
|
||||
|
||||
Add conditional YouTube section removal in `render_template()`, matching the existing pattern for `feedback_url`:
|
||||
|
||||
```python
|
||||
# Remove YouTube section if no URL provided
|
||||
if not variables.get("youtube_url"):
|
||||
result = re.sub(
|
||||
r"\n*Here's the link for the karaoke video published to YouTube:\n\{youtube_url\}\n*",
|
||||
'\n',
|
||||
result,
|
||||
flags=re.DOTALL
|
||||
)
|
||||
variables["youtube_url"] = ""
|
||||
```
|
||||
|
||||
And change `render_job_completion()` to pass `None` instead of `"[YouTube URL not available]"` when youtube_url is empty.
|
||||
|
||||
### Admin Toggle Auto-Delete
|
||||
|
||||
When admin PATCH updates `is_private` from False to True on a job that has existing outputs, reuse the existing delete-outputs logic to remove YouTube + GDrive + Dropbox outputs. Admin can then "Reprocess" to re-distribute to the private Dropbox path.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Backend Model & Config (foundation)
|
||||
|
||||
1. [ ] **Add `is_private` to Job model** (`backend/models/job.py`)
|
||||
- Add `is_private: bool = False` field after `made_for_you` field
|
||||
- Add to `JobCreate` model as well
|
||||
|
||||
2. [ ] **Add private distribution config** (`backend/config.py`)
|
||||
- Add `default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")`
|
||||
- Add `default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")`
|
||||
|
||||
3. [ ] **Add helper function** (`backend/services/job_defaults_service.py`)
|
||||
- Add `get_effective_distribution_for_job(job)` function that returns distribution settings with private overrides applied
|
||||
|
||||
### Phase 2: Backend API (job creation + admin)
|
||||
|
||||
4. [ ] **Add `is_private` to request models** (`backend/models/requests.py`)
|
||||
- Add `is_private: Optional[bool] = None` to `URLSubmissionRequest`
|
||||
- Add `is_private: Optional[bool] = None` to `AudioSearchRequest`
|
||||
|
||||
5. [ ] **Update URL creation endpoint** (`backend/api/routes/jobs.py`)
|
||||
- Accept and pass through `is_private` field to `JobCreate`
|
||||
|
||||
6. [ ] **Update file upload endpoint** (`backend/api/routes/file_upload.py`)
|
||||
- Accept `is_private` Form parameter
|
||||
- Pass through to `JobCreate`
|
||||
|
||||
7. [ ] **Update audio search endpoint** (`backend/api/routes/audio_search.py`)
|
||||
- Accept `is_private` in `AudioSearchRequest`
|
||||
- Pass through to `JobCreate`
|
||||
|
||||
8. [ ] **Update admin endpoints** (`backend/api/routes/admin.py`)
|
||||
- Add `is_private: Optional[bool] = None` to `JobUpdateRequest`
|
||||
- Add `"is_private"` to `EDITABLE_JOB_FIELDS`
|
||||
- In the PATCH handler: detect when `is_private` changes from False→True on a completed job, auto-delete existing outputs (call existing delete-outputs service logic)
|
||||
|
||||
### Phase 3: Distribution Pipeline
|
||||
|
||||
9. [ ] **Update orchestrator config creation** (`backend/workers/video_worker_orchestrator.py`)
|
||||
- In `create_orchestrator_config_from_job()`: Use `get_effective_distribution_for_job()` helper to determine dropbox_path, brand_prefix, enable_youtube_upload, gdrive_folder_id instead of reading directly from job
|
||||
|
||||
10. [ ] **Update native distribution fallback** (`backend/workers/video_worker.py`)
|
||||
- In `_handle_native_distribution()`: Use `get_effective_distribution_for_job()` helper instead of reading directly from job fields
|
||||
|
||||
### Phase 4: Email Template
|
||||
|
||||
11. [ ] **Add YouTube section conditional removal** (`backend/services/template_service.py`)
|
||||
- In `render_template()`: Add regex to remove YouTube paragraph when `youtube_url` is empty (matching existing `feedback_url` pattern)
|
||||
- In `render_job_completion()`: Pass `None` for youtube_url when empty (instead of `"[YouTube URL not available]"`)
|
||||
|
||||
### Phase 5: Frontend
|
||||
|
||||
12. [ ] **Add private checkbox to job creation form** (`frontend/components/job/JobSubmission.tsx`)
|
||||
- Add "Private (Non-Published)" checkbox below the existing "Skip lyrics review" checkbox
|
||||
- Show for all users (not just admin)
|
||||
- Include brief description text: "Private tracks go to Dropbox only, not YouTube or Google Drive"
|
||||
|
||||
13. [ ] **Update API interfaces** (`frontend/lib/api.ts`)
|
||||
- Add `is_private?: boolean` to all job creation option interfaces
|
||||
- Add `is_private` to `JobUpdateRequest` interface
|
||||
- Pass through in `uploadJob()`, `createJobFromUrl()`, `searchAudio()` methods
|
||||
|
||||
14. [ ] **Add private toggle to admin job detail** (`frontend/app/admin/jobs/page.tsx`)
|
||||
- Add `is_private` as an inline-editable field in the job overview section (use Switch component)
|
||||
- Show current state with visual indicator (e.g., lock icon for private jobs)
|
||||
- When toggling to private on a completed job, show confirmation dialog about auto-deleting outputs
|
||||
|
||||
### Phase 6: Environment Configuration
|
||||
|
||||
15. [ ] **Update CI/deployment config** (`.github/workflows/ci.yml` or Cloud Run env)
|
||||
- Add `DEFAULT_PRIVATE_DROPBOX_PATH` environment variable (e.g., `/Karaoke/Tracks-NonPublished`)
|
||||
- Add `DEFAULT_PRIVATE_BRAND_PREFIX` environment variable (e.g., `NOMADNP`)
|
||||
- These should be configured in Cloud Run service and CI test environment
|
||||
|
||||
### Phase 7: Testing
|
||||
|
||||
16. [ ] **Unit tests for private distribution logic** (`backend/tests/test_private_tracks.py`)
|
||||
- Test `get_effective_distribution_for_job()` with private and non-private jobs
|
||||
- Test `create_orchestrator_config_from_job()` applies private overrides correctly
|
||||
- Test `_run_distribution()` skips YouTube and GDrive when private config applied
|
||||
- Test `_upload_to_dropbox()` uses private path and brand prefix
|
||||
- Test brand code generation with NOMADNP prefix in Tracks-NonPublished
|
||||
- Test `_handle_native_distribution()` respects private overrides
|
||||
- Test non-private jobs are completely unaffected (regression tests)
|
||||
|
||||
17. [ ] **Unit tests for email changes** (add to `backend/tests/test_email_service.py` or `test_template_service.py`)
|
||||
- Test YouTube section removed from email when youtube_url is None
|
||||
- Test YouTube section present when youtube_url is provided
|
||||
- Test Dropbox section still present for private jobs
|
||||
- Test full email rendering for private job scenario
|
||||
|
||||
18. [ ] **Unit tests for admin toggle** (add to `backend/tests/test_admin.py` or new file)
|
||||
- Test admin can update is_private field
|
||||
- Test toggling is_private to True on completed job triggers output deletion
|
||||
- Test toggling is_private to True on non-completed job does NOT delete outputs
|
||||
- Test toggling is_private to False does nothing special
|
||||
|
||||
19. [ ] **Integration test** (`backend/tests/emulator/` or `test_distribution_services.py`)
|
||||
- Test full distribution pipeline with is_private=True: verify Dropbox path, brand prefix, YouTube skip, GDrive skip
|
||||
|
||||
20. [ ] **Frontend E2E regression test** (`frontend/e2e/regression/`)
|
||||
- Test private checkbox appears in job creation form
|
||||
- Test private toggle in admin dashboard
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/models/job.py` | Modify | Add `is_private: bool = False` to Job and JobCreate |
|
||||
| `backend/config.py` | Modify | Add `default_private_dropbox_path` and `default_private_brand_prefix` |
|
||||
| `backend/services/job_defaults_service.py` | Modify | Add `get_effective_distribution_for_job()` helper |
|
||||
| `backend/models/requests.py` | Modify | Add `is_private` to URL and AudioSearch request models |
|
||||
| `backend/api/routes/jobs.py` | Modify | Accept and pass `is_private` |
|
||||
| `backend/api/routes/file_upload.py` | Modify | Accept and pass `is_private` |
|
||||
| `backend/api/routes/audio_search.py` | Modify | Accept and pass `is_private` |
|
||||
| `backend/api/routes/admin.py` | Modify | Add `is_private` to editable fields + auto-delete logic |
|
||||
| `backend/workers/video_worker_orchestrator.py` | Modify | Use helper in `create_orchestrator_config_from_job()` |
|
||||
| `backend/workers/video_worker.py` | Modify | Use helper in `_handle_native_distribution()` |
|
||||
| `backend/services/template_service.py` | Modify | Conditional YouTube section removal |
|
||||
| `frontend/components/job/JobSubmission.tsx` | Modify | Add private checkbox |
|
||||
| `frontend/lib/api.ts` | Modify | Add `is_private` to interfaces and API calls |
|
||||
| `frontend/app/admin/jobs/page.tsx` | Modify | Add private toggle to admin detail |
|
||||
| `backend/tests/test_private_tracks.py` | Create | Comprehensive unit tests for private track logic |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (~25-30 tests in `test_private_tracks.py`)
|
||||
- `get_effective_distribution_for_job()` with private=True and False
|
||||
- `create_orchestrator_config_from_job()` private overrides (YouTube=False, GDrive=None, private Dropbox path, NOMADNP brand)
|
||||
- Distribution stage skips: YouTube not called, GDrive not called, Dropbox IS called with correct path
|
||||
- Brand code generation uses NOMADNP prefix and Tracks-NonPublished path
|
||||
- Native distribution fallback applies same overrides
|
||||
- **Regression tests**: Non-private jobs have unchanged behavior (same paths, same brand code, YouTube+GDrive+Dropbox all fire)
|
||||
|
||||
### Email Template Tests (~5 tests)
|
||||
- YouTube section stripped when youtube_url is None
|
||||
- YouTube section preserved when youtube_url has value
|
||||
- Dropbox section always present
|
||||
- Full private job email rendering (Dropbox + no YouTube)
|
||||
- Full non-private job email rendering (both present) - regression
|
||||
|
||||
### Admin Toggle Tests (~5 tests)
|
||||
- is_private editable via PATCH
|
||||
- Toggle to private on completed job deletes outputs
|
||||
- Toggle to private on pending/in-progress job does NOT delete
|
||||
- Toggle to non-private does nothing special
|
||||
|
||||
### Frontend Tests
|
||||
- E2E: Private checkbox visible and functional in job creation
|
||||
- E2E: Admin toggle visible and includes confirmation dialog
|
||||
|
||||
### Manual Verification
|
||||
- Create a private job end-to-end, verify Dropbox folder in Tracks-NonPublished with NOMADNP code
|
||||
- Verify completion email has Dropbox link but no YouTube section
|
||||
- Toggle existing completed job to private, verify outputs deleted
|
||||
|
||||
## Regression Risk Analysis
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|-----------|
|
||||
| Non-private jobs affected | `is_private` defaults to `False`; helper returns unchanged values for non-private. Explicit regression tests. |
|
||||
| Dual code paths (orchestrator vs native) | Both paths use same helper function. Tests cover both paths. (Lesson: "Fix Both Sides of Dual Code Paths") |
|
||||
| Email template regex breaks other content | Regex targets specific YouTube paragraph text. Tests verify non-YouTube content untouched. |
|
||||
| Brand code namespace collision | NOMADNP codes are in a completely separate Dropbox folder (Tracks-NonPublished), no overlap with NOMAD codes in Tracks-Organized |
|
||||
| Admin auto-delete on wrong job | Only triggers when `is_private` changes from False→True AND job has terminal status (complete). Confirmation dialog in frontend. |
|
||||
| Made-for-you orders | MFY webhook doesn't set is_private (defaults False). Admin can toggle after. No change to MFY flow. |
|
||||
| Existing Firestore documents | Missing `is_private` field defaults to `False` via model default. No migration needed. |
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [x] Who sees private toggle? → **Everyone** (all users at creation, admin on existing)
|
||||
- [x] Auto-delete on toggle? → **Yes**, auto-delete all outputs when toggling to private on completed job
|
||||
- [x] Email format? → **Remove YouTube section** when no YouTube URL (improves all edge cases)
|
||||
- [x] Discord? → **Still notify** (useful for internal tracking)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
1. **Feature flag**: The `is_private` field defaults to `False`, so setting `DEFAULT_PRIVATE_DROPBOX_PATH` to empty/None effectively disables private distribution
|
||||
2. **No schema migration needed**: Missing `is_private` field on existing Firestore documents defaults to `False`
|
||||
3. **Email change is backward-compatible**: The YouTube section removal only happens when youtube_url is None, which is already an edge case showing "[YouTube URL not available]"
|
||||
4. **Frontend**: Private checkbox is additive UI, removing it just means users can't create new private jobs
|
||||
@@ -0,0 +1,239 @@
|
||||
# Plan: Song Lookup & Autocomplete + Community Version Detection
|
||||
|
||||
**Created:** 2026-03-02
|
||||
**Branch:** feat/sess-20260302-2324-song-lookup-autocomplete
|
||||
**Status:** Implementation Complete
|
||||
|
||||
## Overview
|
||||
|
||||
Add two features to the karaoke-gen job creation flow:
|
||||
|
||||
1. **Artist/title autocomplete** using karaoke-decide's MusicBrainz + Spotify catalog data, so users get properly-styled artist/title text (e.g. "Fleetwood Mac" instead of "fleetwood mac")
|
||||
2. **Community karaoke version detection** that warns users when a high-quality community karaoke version already exists on YouTube (via karaokenerds data), saving them credits and time
|
||||
|
||||
Both features are **optional and non-blocking** — users can still type whatever they want and proceed even if a community version exists.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Artist field autocomplete across all 3 job creation tabs (Search, Upload, URL)
|
||||
- [ ] Title field autocomplete (optionally filtered by selected artist) across all 3 tabs
|
||||
- [ ] Autocomplete uses canonical MusicBrainz/Spotify text styling
|
||||
- [ ] Autocomplete is optional — users can ignore suggestions and type freely
|
||||
- [ ] Community version check triggers when both artist and title are filled
|
||||
- [ ] If community karaoke version exists, show a dismissible banner with YouTube link(s)
|
||||
- [ ] Community check does not block job submission — just informs the user
|
||||
- [ ] Graceful degradation if karaoke-decide API or karaokenerds.com is down
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
### How to access karaoke-decide catalog data
|
||||
|
||||
**Decision: Proxy through karaoke-gen backend**
|
||||
|
||||
Both services share the same GCP project (`nomadkaraoke`), but the frontend at `gen.nomadkaraoke.com` can't directly call `decide.nomadkaraoke.com/api/` due to CORS (different origins). Options considered:
|
||||
|
||||
| Option | Pros | Cons |
|
||||
|--------|------|------|
|
||||
| **Proxy via karaoke-gen backend** | No CORS issues, no changes to karaoke-decide, frontend already calls api.nomadkaraoke.com | Added latency (extra hop), karaoke-decide dependency |
|
||||
| Direct frontend calls + CORS | Simpler, no proxy code | Requires karaoke-decide CORS changes, cross-project coupling |
|
||||
| Query BigQuery directly from karaoke-gen | No dependency on karaoke-decide service | Duplicates query logic, BigQuery setup needed, higher latency |
|
||||
|
||||
The proxy approach is cleanest: karaoke-gen frontend → karaoke-gen backend → karaoke-decide API. Response caching in the proxy minimizes latency impact.
|
||||
|
||||
### How to detect community karaoke versions
|
||||
|
||||
**Decision: Scrape karaokenerds.com from karaoke-gen backend** (same approach as kjbox)
|
||||
|
||||
The `karaokenerds_raw` BigQuery table has the catalog but NOT community status. Community status is determined by an `<img class="check">` badge in karaokenerds.com's HTML, only available via web scraping. The kjbox codebase has proven, well-tested scraping logic we can port directly.
|
||||
|
||||
Search URL: `https://karaokenerds.com/Search?query={artist}+{title}&webFilter=OnlyWeb`
|
||||
|
||||
Returns: songs with tracks, each track having `brand_name`, `brand_code`, `youtube_url`, `is_community`.
|
||||
|
||||
### Autocomplete UI component
|
||||
|
||||
**Decision: Use existing shadcn Command (cmdk) + Popover components**
|
||||
|
||||
The frontend already has `command.tsx` and `popover.tsx` from shadcn/ui. The standard combobox pattern (Popover + Command) provides:
|
||||
- Keyboard navigation (arrow keys, enter to select)
|
||||
- Debounced search-as-you-type
|
||||
- Clean dropdown with loading states
|
||||
- Works inline within forms (not modal)
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Data flow
|
||||
|
||||
```
|
||||
User types in artist field
|
||||
→ debounced (300ms) API call to GET /api/catalog/artists?q=fle
|
||||
→ karaoke-gen backend proxies to decide.nomadkaraoke.com/api/catalog/artists?q=fle
|
||||
→ returns [{ name: "Fleetwood Mac", mbid: "...", popularity: 85 }, ...]
|
||||
→ user selects "Fleetwood Mac" → field populated with canonical name
|
||||
|
||||
User types in title field
|
||||
→ debounced (300ms) API call to GET /api/catalog/tracks?q=dreams&artist=Fleetwood+Mac
|
||||
→ returns [{ track_name: "Dreams", artist_name: "Fleetwood Mac", popularity: 82 }, ...]
|
||||
→ user selects "Dreams" → field populated with canonical title
|
||||
|
||||
Both fields filled → community check fires
|
||||
→ POST /api/catalog/community-check { artist: "Fleetwood Mac", title: "Dreams" }
|
||||
→ backend scrapes karaokenerds.com for "Fleetwood Mac Dreams" with webFilter=OnlyWeb
|
||||
→ if community tracks found with YouTube URLs, return them
|
||||
→ frontend shows banner: "A community karaoke version already exists! [Watch on YouTube →]"
|
||||
```
|
||||
|
||||
### Caching strategy
|
||||
|
||||
| Endpoint | Cache TTL | Scope |
|
||||
|----------|-----------|-------|
|
||||
| Artist search proxy | 5 min | In-memory (backend) |
|
||||
| Track search proxy | 5 min | In-memory (backend) |
|
||||
| Community check | 1 hour | In-memory (backend) |
|
||||
|
||||
### karaoke-decide API endpoints used
|
||||
|
||||
These are all **public, no auth required**:
|
||||
|
||||
- `GET /api/catalog/artists?q={query}&limit=10` — MBID-first artist search
|
||||
- Returns: `[{ mbid, name, disambiguation, artist_type, tags, spotify_id, popularity, genres }]`
|
||||
- `GET /api/catalog/tracks?q={query}&limit=10` — Track search (Spotify data)
|
||||
- Returns: `[{ track_id, track_name, artist_name, artist_id, popularity, duration_ms, explicit }]`
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Backend — Catalog proxy + community check endpoints
|
||||
|
||||
1. [ ] **Add catalog proxy service** — `backend/services/catalog_proxy_service.py`
|
||||
- HTTP client (httpx async) calling karaoke-decide API
|
||||
- In-memory TTL cache for responses (5 min)
|
||||
- Configurable karaoke-decide base URL
|
||||
- Graceful error handling (return empty results on failure)
|
||||
|
||||
2. [ ] **Port karaokenerds scraping logic** — `backend/services/karaokenerds_service.py`
|
||||
- Port `search()`, `parse_results()`, `_parse_tracks()`, `_parse_single_track()`, `_clean_youtube_url()` from `kjbox/kj-controller/karaoke_nerds.py`
|
||||
- Add async support (httpx instead of requests)
|
||||
- In-memory TTL cache (1 hour)
|
||||
- Return only community tracks with YouTube URLs
|
||||
|
||||
3. [ ] **Add catalog routes** — `backend/api/routes/catalog.py`
|
||||
- `GET /api/catalog/artists?q=&limit=10` — proxy to karaoke-decide
|
||||
- `GET /api/catalog/tracks?q=&artist=&limit=10` — proxy to karaoke-decide
|
||||
- `POST /api/catalog/community-check` — scrape karaokenerds.com
|
||||
- All endpoints require auth (same as job creation)
|
||||
- Pydantic request/response models
|
||||
|
||||
4. [ ] **Register routes in main.py** — add `catalog.router` to app
|
||||
|
||||
5. [ ] **Add config** — `backend/config.py`
|
||||
- `karaoke_decide_api_url` setting (default: `https://decide.nomadkaraoke.com`)
|
||||
|
||||
6. [ ] **Add `beautifulsoup4` + `httpx` dependencies** to `pyproject.toml` (if not already present)
|
||||
|
||||
### Phase 2: Frontend — Autocomplete component
|
||||
|
||||
7. [ ] **Create `AutocompleteInput` component** — `frontend/components/ui/autocomplete-input.tsx`
|
||||
- Wraps an Input field with a Popover + Command dropdown
|
||||
- Props: `value`, `onChange`, `onSelect`, `fetchSuggestions(query) => Promise<Suggestion[]>`, `placeholder`, `disabled`, `renderItem`
|
||||
- Debounced search (300ms) triggered on input change
|
||||
- Shows loading spinner while fetching
|
||||
- Shows "No results" when search returns empty
|
||||
- Keyboard navigation (up/down arrows, enter to select, escape to close)
|
||||
- Clicking outside closes dropdown
|
||||
- When user selects a suggestion, calls `onSelect(suggestion)` and populates input
|
||||
- When user types without selecting, uses their raw text (autocomplete is optional)
|
||||
|
||||
8. [ ] **Add catalog API functions** — `frontend/lib/api.ts`
|
||||
- `searchArtists(query: string, limit?: number)` → `GET /api/catalog/artists`
|
||||
- `searchTracks(query: string, artist?: string, limit?: number)` → `GET /api/catalog/tracks`
|
||||
- `checkCommunityVersions(artist: string, title: string)` → `POST /api/catalog/community-check`
|
||||
|
||||
### Phase 3: Frontend — Integrate autocomplete into job creation
|
||||
|
||||
9. [ ] **Replace artist Input fields with AutocompleteInput** in `JobSubmission.tsx`
|
||||
- All 3 tabs: `searchArtist`, `uploadArtist`, `youtubeArtist`
|
||||
- Fetch suggestions from `api.searchArtists(query)`
|
||||
- On select: populate artist field with canonical name
|
||||
- Show artist name + optional disambiguation in dropdown items
|
||||
|
||||
10. [ ] **Replace title Input fields with AutocompleteInput** in `JobSubmission.tsx`
|
||||
- All 3 tabs: `searchTitle`, `uploadTitle`, `youtubeTitle`
|
||||
- Fetch suggestions from `api.searchTracks(query, selectedArtist)`
|
||||
- On select: populate title field with canonical name
|
||||
- Show track name + artist name + duration in dropdown items
|
||||
|
||||
### Phase 4: Frontend — Community version detection
|
||||
|
||||
11. [ ] **Create `CommunityVersionBanner` component** — `frontend/components/job/CommunityVersionBanner.tsx`
|
||||
- Shows when community karaoke version(s) found
|
||||
- Displays: "A karaoke version of this song already exists!"
|
||||
- Lists community tracks with brand name and YouTube link
|
||||
- "Watch on YouTube" button for top community version
|
||||
- Dismissible (X button or "Continue anyway" link)
|
||||
- Styled with green border (matching kjbox community track styling)
|
||||
|
||||
12. [ ] **Add community check logic to `JobSubmission.tsx`** (Search tab only)
|
||||
- Debounced check (500ms) when both artist AND title fields have values
|
||||
- Only triggers when values change (not on every keystroke)
|
||||
- Shows `CommunityVersionBanner` between the form fields and the submit button
|
||||
- Does NOT block form submission
|
||||
- Clears when artist or title changes
|
||||
|
||||
### Phase 5: Testing
|
||||
|
||||
13. [ ] **Backend unit tests** — `backend/tests/unit/test_catalog_routes.py`
|
||||
- Test proxy endpoints with mocked karaoke-decide responses
|
||||
- Test community check with mocked karaokenerds HTML
|
||||
- Test error handling (karaoke-decide down, karaokenerds down)
|
||||
- Test caching behavior
|
||||
|
||||
14. [ ] **Backend unit tests** — `backend/tests/unit/test_karaokenerds_service.py`
|
||||
- Port relevant tests from `kjbox/kj-controller/tests/unit/test_karaoke_nerds.py`
|
||||
- Test HTML parsing, community detection, YouTube URL cleanup
|
||||
|
||||
15. [ ] **Frontend component tests** — `frontend/components/ui/__tests__/autocomplete-input.test.tsx`
|
||||
- Test suggestion fetching and display
|
||||
- Test keyboard navigation
|
||||
- Test selection behavior
|
||||
- Test free-text input (no selection)
|
||||
|
||||
16. [ ] **E2E tests** — `frontend/e2e/job-creation-autocomplete.spec.ts`
|
||||
- Test autocomplete appears on typing
|
||||
- Test selecting from autocomplete populates field
|
||||
- Test community banner appears for known songs
|
||||
- Test form submission works with and without autocomplete selection
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/services/catalog_proxy_service.py` | Create | HTTP client for karaoke-decide API with caching |
|
||||
| `backend/services/karaokenerds_service.py` | Create | Karaokenerds.com scraper (ported from kjbox) |
|
||||
| `backend/api/routes/catalog.py` | Create | Proxy endpoints for artist/track search + community check |
|
||||
| `backend/main.py` | Modify | Register catalog router |
|
||||
| `backend/config.py` | Modify | Add karaoke_decide_api_url setting |
|
||||
| `pyproject.toml` | Modify | Add beautifulsoup4 dependency (if missing) |
|
||||
| `frontend/components/ui/autocomplete-input.tsx` | Create | Reusable autocomplete input component |
|
||||
| `frontend/components/job/CommunityVersionBanner.tsx` | Create | Community version warning banner |
|
||||
| `frontend/components/job/JobSubmission.tsx` | Modify | Replace Input with AutocompleteInput, add community check |
|
||||
| `frontend/lib/api.ts` | Modify | Add catalog API functions |
|
||||
| `backend/tests/unit/test_catalog_routes.py` | Create | Backend route tests |
|
||||
| `backend/tests/unit/test_karaokenerds_service.py` | Create | Scraper unit tests |
|
||||
| `frontend/components/ui/__tests__/autocomplete-input.test.tsx` | Create | Component tests |
|
||||
| `frontend/e2e/job-creation-autocomplete.spec.ts` | Create | E2E tests |
|
||||
|
||||
## Decisions (Resolved)
|
||||
|
||||
- **Track search scope**: All Spotify tracks (256M) — better coverage for new/obscure songs
|
||||
- **Community check scope**: Search tab only (Upload/URL users already have their audio)
|
||||
- **Rate limiting**: 20 requests/min per user on catalog proxy endpoints (prevents abuse of karaokenerds scraping). All endpoints require auth.
|
||||
- **"Display As" fields**: No autocomplete — they're for deliberate overrides like soundtrack names
|
||||
- **CORS**: Proxy approach (no changes needed to karaoke-decide)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Feature is entirely additive — no existing functionality is modified
|
||||
- Autocomplete fields fall back to plain text Input if API calls fail
|
||||
- Community check is non-blocking — if it fails, form works normally
|
||||
- All new endpoints are behind the existing auth middleware
|
||||
- Can disable by reverting the frontend changes (backend proxy is harmless if unused)
|
||||
+58
-18
@@ -9,7 +9,6 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
@@ -245,12 +244,23 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Refresh E2E session token
|
||||
id: refresh_token
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Happy Path Production Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ secrets.E2E_TEST_TOKEN }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
run: |
|
||||
@@ -677,14 +687,16 @@ jobs:
|
||||
ci-gate:
|
||||
name: "CI Gate"
|
||||
runs-on: ubuntu-latest
|
||||
# Note: frontend-e2e-full is optional (requires 'e2e' label) so not included here
|
||||
# frontend-e2e-smoke IS required - fast smoke tests catch critical regressions
|
||||
# frontend-lint IS required - catches React hooks violations that cause runtime crashes
|
||||
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 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]
|
||||
if: github.ref != 'refs/heads/main' && always()
|
||||
steps:
|
||||
- name: Check results
|
||||
run: |
|
||||
# Check all always-required jobs
|
||||
results=(
|
||||
"${{ needs.frontend-lint.result }}"
|
||||
"${{ needs.frontend-unit-tests.result }}"
|
||||
@@ -702,6 +714,20 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# 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') }}"
|
||||
if [[ "$has_label" == "true" ]]; then
|
||||
if [[ "$e2e_result" != "success" ]]; then
|
||||
echo "❌ E2E Happy Path is required (label present) but result is: $e2e_result"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ E2E Happy Path passed (required by label)"
|
||||
else
|
||||
echo "ℹ️ E2E Happy Path skipped (no label)"
|
||||
fi
|
||||
|
||||
echo "✅ CI passed"
|
||||
|
||||
# ============================================
|
||||
@@ -842,7 +868,7 @@ jobs:
|
||||
|
||||
### Assets
|
||||
- Python package published to PyPI
|
||||
- Frontend deployed to GitHub Pages at gen.nomadkaraoke.com
|
||||
- Frontend deployed to Cloudflare Pages at gen.nomadkaraoke.com
|
||||
|
||||
For detailed changes, see the commit history.
|
||||
draft: false
|
||||
@@ -852,7 +878,7 @@ jobs:
|
||||
dist/*.tar.gz
|
||||
|
||||
deploy-frontend:
|
||||
name: "Deploy - Frontend (GitHub Pages)"
|
||||
name: "Deploy - Frontend (Cloudflare Pages)"
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
steps:
|
||||
@@ -877,23 +903,37 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Build frontend (Next.js static export)
|
||||
# ===== Consumer Build (gen.nomadkaraoke.com) =====
|
||||
- name: Build frontend (consumer)
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
run: npm run build
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v4
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
- name: Deploy consumer to Cloudflare Pages
|
||||
uses: cloudflare/wrangler-action@v3
|
||||
with:
|
||||
path: "frontend/out"
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
command: pages deploy frontend/out --project-name=karaoke-gen --branch=main
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
# ===== Tenant Portal Build (vocalstar.nomadkaraoke.com, singa.nomadkaraoke.com, etc.) =====
|
||||
# Separate build with NEXT_PUBLIC_TENANT_PORTAL=true which tree-shakes
|
||||
# consumer marketing content and renders TenantLandingPage at root.
|
||||
# The Cloudflare Pages Function (frontend/functions/) injects tenant config at the edge.
|
||||
- name: Build frontend (tenant portal)
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
NEXT_PUBLIC_TENANT_PORTAL: "true"
|
||||
run: npm run build
|
||||
|
||||
- name: Deploy tenant portal to Cloudflare Pages
|
||||
uses: cloudflare/wrangler-action@v3
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
command: pages deploy frontend/out --project-name=karaoke-gen-tenant --branch=main
|
||||
|
||||
# NOTE: buy-site was consolidated into the main frontend (PR #122, Dec 2024)
|
||||
# Landing page and payment flow are now at gen.nomadkaraoke.com (root)
|
||||
@@ -1242,8 +1282,8 @@ jobs:
|
||||
--min-instances 4 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest"
|
||||
--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-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: Verify deployment and version
|
||||
run: |
|
||||
|
||||
@@ -67,12 +67,24 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: inputs.use_test_token == true
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run E2E Happy Path Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ inputs.use_test_token && secrets.E2E_TEST_TOKEN || '' }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || '' }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
| **Testing & code quality** | `docs/TESTING.md` |
|
||||
| API reference | `docs/API.md` |
|
||||
| Past learnings | `docs/LESSONS-LEARNED.md` |
|
||||
| **Operational runbooks** | `docs/TROUBLESHOOTING.md` |
|
||||
| **Product communication** | `docs/PRODUCT-COMMUNICATION-GUIDE.md` |
|
||||
| Brand style guide | `docs/BRAND-STYLE-GUIDE.md` |
|
||||
|
||||
@@ -128,15 +129,17 @@ EOF
|
||||
|
||||
### GCE Encoding Worker
|
||||
```bash
|
||||
# SSH to restart service (clears in-memory job queue)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
|
||||
# Check health
|
||||
# Check health (includes wheel_version)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="curl -s http://localhost:8080/health"
|
||||
|
||||
# Restart service (pick up new wheel after a deploy)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
```
|
||||
|
||||
For job stuck at `encoding` status, see [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md).
|
||||
|
||||
### What Doesn't Work
|
||||
- `gcloud auth print-identity-token` - Wrong token type for internal endpoints
|
||||
- Cloud Tasks without proper service account - Gets 401 from Cloud Run
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
# Makefile for karaoke-gen project
|
||||
# Run `make help` to see available commands
|
||||
|
||||
.PHONY: help install install-backend install-frontend build-frontend test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop
|
||||
.PHONY: help install install-backend install-frontend build-frontend dev-install test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop
|
||||
|
||||
# Per-stage timeout in seconds (default: 10 minutes)
|
||||
# Prevents hangs from stale dev servers, broken emulators, etc.
|
||||
# Override with: make test TEST_TIMEOUT=300
|
||||
TEST_TIMEOUT ?= 600
|
||||
|
||||
# Default target
|
||||
help:
|
||||
@@ -12,7 +17,8 @@ help:
|
||||
@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)"
|
||||
@echo " make build-frontend - Build frontend and copy to Python package (for local testing)"
|
||||
@echo " make build-frontend - Build frontend and copy to Python package"
|
||||
@echo " make dev-install - Build frontend + pip install -e . (for local CLI testing)"
|
||||
@echo " make lint - Run linter checks"
|
||||
@echo " make emulators-start - Start GCP emulators for local development"
|
||||
@echo " make emulators-stop - Stop GCP emulators"
|
||||
@@ -34,23 +40,34 @@ install-frontend:
|
||||
|
||||
install: install-backend install-frontend
|
||||
|
||||
# Build frontend and copy to Python package (for local CLI testing)
|
||||
# Build frontend and copy to Python package
|
||||
build-frontend: install-frontend
|
||||
@echo "=== Building frontend ==="
|
||||
cd frontend && npm run build
|
||||
@echo "=== Copying build to Python package ==="
|
||||
rm -rf karaoke_gen/nextjs_frontend/out
|
||||
mkdir -p karaoke_gen/nextjs_frontend/out
|
||||
cp -r frontend/out/* karaoke_gen/nextjs_frontend/out/
|
||||
@echo "✅ Frontend built and ready for local testing"
|
||||
@echo "✅ Frontend built and copied to karaoke_gen/nextjs_frontend/out/"
|
||||
|
||||
# Build frontend + install package in editable mode for local CLI testing
|
||||
# After running this, `karaoke-gen` CLI will use the freshly built frontend.
|
||||
dev-install: build-frontend
|
||||
@echo "=== Installing package in editable mode ==="
|
||||
pip install -e .
|
||||
@echo ""
|
||||
@echo "✅ Ready! You can now run karaoke-gen with the updated frontend."
|
||||
@echo " Example: karaoke-gen input.flac \"Artist\" \"Title\""
|
||||
|
||||
# Run unit tests for karaoke_gen package
|
||||
test-unit: install-backend
|
||||
@echo "=== Running karaoke_gen unit tests ==="
|
||||
poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=term-missing --cov-fail-under=69
|
||||
timeout $(TEST_TIMEOUT) poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=term-missing --cov-fail-under=69
|
||||
|
||||
# Run backend unit tests (excludes emulator tests)
|
||||
test-backend-unit: install-backend
|
||||
@echo "=== Running backend unit tests ==="
|
||||
poetry run pytest backend/tests/ --ignore=backend/tests/emulator -v
|
||||
timeout $(TEST_TIMEOUT) poetry run pytest backend/tests/ --ignore=backend/tests/emulator -v
|
||||
|
||||
# Run E2E integration tests with emulators
|
||||
test-e2e: install-backend
|
||||
@@ -62,7 +79,7 @@ test-e2e: install-backend
|
||||
export GCS_BUCKET_NAME=test-bucket && \
|
||||
export ADMIN_TOKENS=test-admin-token && \
|
||||
export ENVIRONMENT=test && \
|
||||
poetry run pytest backend/tests/emulator/ -v; \
|
||||
timeout $(TEST_TIMEOUT) poetry run pytest backend/tests/emulator/ -v; \
|
||||
TEST_RESULT=$$?; \
|
||||
./scripts/stop-emulators.sh; \
|
||||
exit $$TEST_RESULT
|
||||
@@ -75,7 +92,7 @@ test-backend: test-unit test-backend-unit test-e2e
|
||||
# Run frontend tests (unit + E2E)
|
||||
test-frontend: install-frontend
|
||||
@echo "=== Running frontend tests ==="
|
||||
cd frontend && npm run test:all
|
||||
cd frontend && timeout $(TEST_TIMEOUT) npm run test:all
|
||||
|
||||
# Run ALL tests (backend + frontend) - use this before committing!
|
||||
test: test-backend test-frontend
|
||||
|
||||
@@ -113,6 +113,11 @@ async def require_auth(
|
||||
detail=f"Authentication failed: {auth_result.message}"
|
||||
)
|
||||
|
||||
# If token has a tenant_id, override the hostname-based tenant detection.
|
||||
# This allows tenant-scoped tokens to enforce tenant context regardless of domain.
|
||||
if auth_result.tenant_id:
|
||||
request.state.tenant_id = auth_result.tenant_id
|
||||
|
||||
# Log successful auth with request_id for correlation with request audit
|
||||
logger.info(
|
||||
"auth_success",
|
||||
@@ -122,6 +127,7 @@ async def require_auth(
|
||||
"user_type": auth_result.user_type.value if auth_result.user_type else None,
|
||||
"is_admin": auth_result.is_admin,
|
||||
"remaining_uses": auth_result.remaining_uses,
|
||||
"tenant_id": auth_result.tenant_id,
|
||||
"audit_type": "auth_event",
|
||||
}
|
||||
)
|
||||
|
||||
+135
-9
@@ -96,6 +96,7 @@ class JobUpdateRequest(BaseModel):
|
||||
enable_youtube_upload: Optional[bool] = None
|
||||
non_interactive: Optional[bool] = None
|
||||
prep_only: Optional[bool] = None
|
||||
is_private: Optional[bool] = None
|
||||
|
||||
|
||||
class JobUpdateResponse(BaseModel):
|
||||
@@ -123,6 +124,7 @@ EDITABLE_JOB_FIELDS = {
|
||||
"enable_youtube_upload",
|
||||
"non_interactive",
|
||||
"prep_only",
|
||||
"is_private",
|
||||
}
|
||||
|
||||
|
||||
@@ -912,6 +914,7 @@ async def update_job(
|
||||
- customer_email, customer_notes: Made-for-you order info
|
||||
- brand_prefix: Brand code prefix
|
||||
- non_interactive, prep_only: Workflow options
|
||||
- is_private: Private (non-published) track mode
|
||||
- discord_webhook_url: Notification URL
|
||||
- youtube_description, youtube_description_template: YouTube settings
|
||||
|
||||
@@ -950,26 +953,63 @@ async def update_job(
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Perform the update
|
||||
success = job_manager.update_job(job_id, updates)
|
||||
# Check if we're toggling is_private from False to True on a completed job
|
||||
# If so, auto-delete existing outputs (YouTube, Dropbox, GDrive)
|
||||
toggling_to_private = (
|
||||
"is_private" in updates
|
||||
and updates["is_private"] is True
|
||||
and not getattr(job, 'is_private', False)
|
||||
)
|
||||
|
||||
if not success:
|
||||
# Perform the update (update_job returns None; exceptions indicate failure)
|
||||
try:
|
||||
job_manager.update_job(job_id, updates)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to update job. Please try again."
|
||||
) from e
|
||||
|
||||
# Auto-delete outputs when toggling to private on a job with existing outputs
|
||||
auto_deleted = False
|
||||
if toggling_to_private and job.status in TERMINAL_STATES and not job.outputs_deleted_at:
|
||||
state_data = job.state_data or {}
|
||||
has_outputs = (
|
||||
state_data.get('youtube_url')
|
||||
or state_data.get('dropbox_link')
|
||||
or state_data.get('gdrive_files')
|
||||
)
|
||||
if has_outputs:
|
||||
try:
|
||||
logger.info(
|
||||
f"Auto-deleting outputs for job {job_id} (toggled to private by {admin_email})"
|
||||
)
|
||||
# Call the delete-outputs endpoint directly (same module)
|
||||
await delete_job_outputs(job_id, auth_data)
|
||||
auto_deleted = True
|
||||
except HTTPException:
|
||||
# delete_job_outputs raises HTTPException on validation failures,
|
||||
# but we've already validated terminal state + not-already-deleted
|
||||
logger.warning(f"Auto-delete outputs skipped for job {job_id} (validation)")
|
||||
except Exception as e:
|
||||
logger.warning(f"Auto-delete outputs failed for job {job_id}: {e}")
|
||||
|
||||
# Log the admin action
|
||||
logger.info(
|
||||
f"Admin {admin_email} updated job {job_id}. "
|
||||
f"Updated fields: {list(updates.keys())}"
|
||||
f"{' (outputs auto-deleted)' if auto_deleted else ''}"
|
||||
)
|
||||
|
||||
message = f"Successfully updated {len(updates)} field(s)"
|
||||
if auto_deleted:
|
||||
message += ". Existing outputs were auto-deleted (job set to private)."
|
||||
|
||||
return JobUpdateResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
updated_fields=list(updates.keys()),
|
||||
message=f"Successfully updated {len(updates)} field(s)",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
@@ -1327,6 +1367,69 @@ async def trigger_worker(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Prepare Review Audio Endpoint
|
||||
# =============================================================================
|
||||
|
||||
class PrepareReviewAudioResponse(BaseModel):
|
||||
"""Response from prepare-review-audio endpoint."""
|
||||
status: str
|
||||
job_id: str
|
||||
transcoded_files: List[str]
|
||||
message: str
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/prepare-review-audio", response_model=PrepareReviewAudioResponse)
|
||||
async def prepare_review_audio(
|
||||
job_id: str,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Transcode review audio to OGG Opus for a job (admin only).
|
||||
|
||||
Use this to backfill transcoded audio for existing jobs that were
|
||||
created before eager transcoding was deployed. Transcodes the main
|
||||
input audio and all stem files to OGG Opus 128kbps.
|
||||
|
||||
Idempotent: skips files that are already transcoded.
|
||||
"""
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
try:
|
||||
import asyncio
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
transcoding = AudioTranscodingService()
|
||||
transcoded = await asyncio.to_thread(transcoding.prepare_review_audio_for_job, job)
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin_email} prepared review audio for job {job_id}: "
|
||||
f"{len(transcoded)} files transcoded"
|
||||
)
|
||||
|
||||
return PrepareReviewAudioResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
transcoded_files=transcoded,
|
||||
message=f"Transcoded {len(transcoded)} files to OGG Opus",
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Admin {admin_email} failed to prepare review audio for job {job_id}: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Failed to prepare review audio: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Clear Worker State Endpoint
|
||||
# =============================================================================
|
||||
@@ -1448,8 +1551,9 @@ async def delete_job_outputs(
|
||||
|
||||
This endpoint deletes:
|
||||
1. YouTube video (if uploaded)
|
||||
2. Dropbox folder (if uploaded) - frees brand code for reuse
|
||||
2. Dropbox folder (if uploaded)
|
||||
3. Google Drive files (if uploaded)
|
||||
4. Recycles brand code for reuse (if Dropbox + GDrive cleanup succeeded)
|
||||
|
||||
The job record is preserved with outputs_deleted_at timestamp set.
|
||||
State data related to distribution is cleared.
|
||||
@@ -1585,6 +1689,23 @@ async def delete_job_outputs(
|
||||
logger.error(f"Error deleting GCS finals folder for job {job_id}: {e}", exc_info=True)
|
||||
results["gcs_finals"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Recycle brand code if Dropbox and GDrive cleanup both succeeded
|
||||
dropbox_success = results["dropbox"]["status"] in ("success", "skipped")
|
||||
gdrive_success = results["gdrive"]["status"] in ("success", "skipped")
|
||||
if brand_code and dropbox_success and gdrive_success:
|
||||
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)
|
||||
results["brand_code"] = {"status": "recycled", "code": brand_code}
|
||||
logger.info(f"Recycled brand code {brand_code} during delete-outputs for job {job_id}")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
results["brand_code"] = {"status": "failed", "error": str(e)}
|
||||
elif brand_code:
|
||||
logger.warning(f"Brand code {brand_code} NOT recycled: cleanup incomplete (dropbox={results['dropbox']['status']}, gdrive={results['gdrive']['status']})")
|
||||
results["brand_code"] = {"status": "skipped", "reason": "Dropbox/GDrive cleanup incomplete"}
|
||||
|
||||
# Update job record
|
||||
deletion_timestamp = datetime.now(timezone.utc)
|
||||
user_service = get_user_service()
|
||||
@@ -1632,12 +1753,14 @@ async def delete_job_outputs(
|
||||
overall_status = "success"
|
||||
message = "Outputs deleted successfully"
|
||||
|
||||
brand_code_status = results.get('brand_code', {}).get('status', 'n/a')
|
||||
logger.info(
|
||||
f"Admin {admin_email} deleted outputs for job {job_id}. "
|
||||
f"YouTube: {results['youtube']['status']}, "
|
||||
f"Dropbox: {results['dropbox']['status']}, "
|
||||
f"GDrive: {results['gdrive']['status']}, "
|
||||
f"GCS Finals: {results['gcs_finals']['status']}. "
|
||||
f"GCS Finals: {results['gcs_finals']['status']}, "
|
||||
f"Brand Code: {brand_code_status}. "
|
||||
f"Cleared state_data keys: {cleared_keys}"
|
||||
)
|
||||
|
||||
@@ -1691,6 +1814,7 @@ async def get_job_completion_message(
|
||||
title=job.title,
|
||||
youtube_url=youtube_url,
|
||||
dropbox_url=dropbox_url,
|
||||
is_private=getattr(job, 'is_private', False),
|
||||
)
|
||||
|
||||
# Build subject: "NOMAD-1178: Artist - Title (Your karaoke video is ready!)"
|
||||
@@ -1755,6 +1879,7 @@ async def send_job_completion_email(
|
||||
title=job.title,
|
||||
youtube_url=youtube_url,
|
||||
dropbox_url=dropbox_url,
|
||||
is_private=getattr(job, 'is_private', False),
|
||||
)
|
||||
|
||||
# Send the email
|
||||
@@ -2038,6 +2163,7 @@ RESTART_ALLOWED_STATES = {
|
||||
"complete",
|
||||
"failed",
|
||||
"awaiting_review",
|
||||
"in_review", # User opened review UI but hasn't completed
|
||||
"awaiting_audio_selection",
|
||||
"awaiting_instrumental_selection",
|
||||
"instrumental_selected",
|
||||
@@ -2158,18 +2284,18 @@ async def restart_job(
|
||||
# Set coordination flags to trigger screens worker
|
||||
update_payload["state_data.audio_complete"] = True
|
||||
update_payload["state_data.lyrics_complete"] = True
|
||||
update_payload["status"] = "transcribing" # Allows screens worker to run
|
||||
update_payload["status"] = "downloading" # Allows transition to generating_screens
|
||||
update_payload["message"] = "Restarting with preserved audio stems"
|
||||
update_payload["error_message"] = DELETE_FIELD
|
||||
update_payload["error_details"] = DELETE_FIELD
|
||||
update_payload["timeline"] = ArrayUnion([{
|
||||
"status": "transcribing",
|
||||
"status": "downloading",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Admin {admin_email} restarted job (preserving audio stems)"
|
||||
}])
|
||||
|
||||
job_ref.update(update_payload)
|
||||
new_status = "transcribing"
|
||||
new_status = "downloading"
|
||||
|
||||
# Trigger screens worker
|
||||
try:
|
||||
|
||||
@@ -17,6 +17,8 @@ import mimetypes
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request, Depends
|
||||
@@ -35,6 +37,7 @@ from backend.services.audio_search_service import (
|
||||
NoResultsError,
|
||||
DownloadError,
|
||||
)
|
||||
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
@@ -46,6 +49,8 @@ from backend.version import VERSION
|
||||
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, RateLimitExceededError
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -134,6 +139,9 @@ class AudioSearchRequest(BaseModel):
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
@validator('artist', 'title', 'lyrics_artist', 'lyrics_title', 'display_artist', 'display_title')
|
||||
def normalize_text_fields(cls, v):
|
||||
"""Normalize text fields to standardize Unicode characters."""
|
||||
@@ -192,9 +200,32 @@ class AudioSearchResponse(BaseModel):
|
||||
style_upload_urls: Optional[List[StyleUploadUrl]] = None
|
||||
|
||||
|
||||
class StandaloneSearchRequest(BaseModel):
|
||||
"""Request for standalone audio search (no job created)."""
|
||||
artist: str = Field(..., description="Artist name to search for")
|
||||
title: str = Field(..., description="Song title to search for")
|
||||
|
||||
@validator('artist', 'title')
|
||||
def normalize_text_fields(cls, v):
|
||||
if v is not None and isinstance(v, str):
|
||||
return normalize_text(v)
|
||||
return v
|
||||
|
||||
|
||||
class StandaloneSearchResponse(BaseModel):
|
||||
"""Response from standalone audio search."""
|
||||
search_session_id: str
|
||||
results: List[AudioSearchResultResponse]
|
||||
results_count: int
|
||||
|
||||
|
||||
class AudioSelectRequest(BaseModel):
|
||||
"""Request to select an audio source."""
|
||||
selection_index: int = Field(..., description="Index of the selected audio source from search results")
|
||||
# Optional overrides — sent from the guided flow's Customize step (Step 3)
|
||||
is_private: Optional[bool] = Field(None, description="Override privacy flag (guided flow Step 3)")
|
||||
display_artist: Optional[str] = Field(None, description="Override display artist name")
|
||||
display_title: Optional[str] = Field(None, description="Override display title")
|
||||
|
||||
|
||||
class AudioSelectResponse(BaseModel):
|
||||
@@ -254,27 +285,20 @@ def _extract_gcs_path(filepath: str) -> str:
|
||||
return filepath
|
||||
|
||||
|
||||
async def _download_and_start_processing(
|
||||
def _validate_and_prepare_selection(
|
||||
job_id: str,
|
||||
selection_index: int,
|
||||
audio_search_service,
|
||||
background_tasks: BackgroundTasks,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Download selected audio and start job processing.
|
||||
|
||||
This is called either:
|
||||
- Immediately after search if auto_download=True
|
||||
- When user calls the select endpoint
|
||||
|
||||
For remote flacfetch downloads (torrent sources), the file is downloaded
|
||||
on the flacfetch VM and uploaded directly to GCS. For local downloads
|
||||
(YouTube), the file is downloaded locally and then uploaded to GCS.
|
||||
Validate selection and transition job to DOWNLOADING_AUDIO state.
|
||||
|
||||
Returns selection info dict with the selected result details.
|
||||
Raises HTTPException on validation errors.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
|
||||
# Get search results from state_data
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
if not search_results:
|
||||
@@ -288,9 +312,6 @@ async def _download_and_start_processing(
|
||||
|
||||
selected = search_results[selection_index]
|
||||
|
||||
# Get remote_search_id from state_data (stored during initial search)
|
||||
remote_search_id = job.state_data.get('remote_search_id')
|
||||
|
||||
# Transition to downloading state
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
@@ -302,8 +323,59 @@ async def _download_and_start_processing(
|
||||
'selected_audio_provider': selected['provider'],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# Save download params to job BEFORE attempting download
|
||||
# This enables retry even if download fails
|
||||
source_name = selected.get('provider')
|
||||
source_id = selected.get('source_id')
|
||||
target_file = selected.get('target_file')
|
||||
download_url = selected.get('url')
|
||||
|
||||
job_manager.update_job(job_id, {
|
||||
'audio_source_type': 'audio_search',
|
||||
'source_name': source_name,
|
||||
'source_id': source_id,
|
||||
'target_file': target_file,
|
||||
'download_url': download_url,
|
||||
})
|
||||
logger.info(
|
||||
f"Job {job_id}: Saved download params before attempt: "
|
||||
f"source_name={source_name}, source_id={source_id}"
|
||||
)
|
||||
|
||||
return {
|
||||
'selected_index': selection_index,
|
||||
'selected_title': selected['title'],
|
||||
'selected_artist': selected['artist'],
|
||||
'selected_provider': selected['provider'],
|
||||
}
|
||||
|
||||
|
||||
async def _download_audio_and_trigger_workers(
|
||||
job_id: str,
|
||||
selection_index: int,
|
||||
audio_search_service,
|
||||
) -> None:
|
||||
"""
|
||||
Download audio and trigger processing workers.
|
||||
|
||||
This runs as a background task after the select endpoint returns.
|
||||
Also called synchronously from the auto_download path during search.
|
||||
|
||||
For remote flacfetch downloads (torrent sources), the file is downloaded
|
||||
on the flacfetch VM and uploaded directly to GCS. For local downloads
|
||||
(YouTube), the file is downloaded locally and then uploaded to GCS.
|
||||
"""
|
||||
try:
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.error(f"Job {job_id} not found during background download")
|
||||
return
|
||||
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
selected = search_results[selection_index]
|
||||
remote_search_id = job.state_data.get('remote_search_id')
|
||||
|
||||
# Get source info from selected result
|
||||
source_name = selected.get('provider')
|
||||
source_id = selected.get('source_id')
|
||||
@@ -337,8 +409,9 @@ async def _download_and_start_processing(
|
||||
raise DownloadError(f"YouTube download failed: {e}")
|
||||
|
||||
elif source_name in ['RED', 'OPS']:
|
||||
# Torrent sources - must use remote flacfetch
|
||||
if not audio_search_service.is_remote_enabled():
|
||||
# Torrent sources - must use remote flacfetch (async, no event loop blocking)
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
raise DownloadError(
|
||||
f"Cannot download from {source_name} without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
@@ -348,31 +421,48 @@ async def _download_and_start_processing(
|
||||
|
||||
if source_id:
|
||||
logger.info(f"Torrent download via download_by_id: {source_name} ID={source_id}")
|
||||
result = audio_search_service.download_by_id(
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="",
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
else:
|
||||
if not remote_search_id:
|
||||
raise DownloadError(
|
||||
f"No source_id or remote_search_id available for {source_name} download"
|
||||
)
|
||||
logger.info(f"Torrent download via search-based download")
|
||||
result = audio_search_service.download(
|
||||
download_id = await flacfetch_client.download(
|
||||
search_id=remote_search_id,
|
||||
result_index=selection_index,
|
||||
output_dir="",
|
||||
gcs_path=gcs_destination,
|
||||
remote_search_id=remote_search_id,
|
||||
)
|
||||
|
||||
# Extract GCS path from result
|
||||
audio_gcs_path = _extract_gcs_path(result.filepath)
|
||||
filename = os.path.basename(result.filepath)
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
logger.info(f"Torrent download complete: {audio_gcs_path}")
|
||||
|
||||
elif source_name == 'Spotify':
|
||||
# Spotify downloads - use audio_search_service
|
||||
if not audio_search_service.is_remote_enabled():
|
||||
# Spotify downloads - use async FlacfetchClient directly (no event loop blocking)
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
raise DownloadError(
|
||||
f"Cannot download from Spotify without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
@@ -381,25 +471,40 @@ async def _download_and_start_processing(
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
logger.info(f"Spotify download: source_id={source_id}")
|
||||
|
||||
result = audio_search_service.download_by_id(
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="",
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(result.filepath)
|
||||
filename = os.path.basename(result.filepath)
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
logger.info(f"Spotify download complete: {audio_gcs_path}")
|
||||
|
||||
else:
|
||||
# Unknown source - try generic download
|
||||
# Unknown source - try generic download (run sync code in thread to avoid blocking)
|
||||
logger.warning(f"Unknown source type: {source_name}, attempting generic download")
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
|
||||
|
||||
try:
|
||||
result = audio_search_service.download(
|
||||
result = await asyncio.to_thread(
|
||||
audio_search_service.download,
|
||||
result_index=selection_index,
|
||||
output_dir=temp_dir,
|
||||
remote_search_id=remote_search_id,
|
||||
@@ -425,7 +530,7 @@ async def _download_and_start_processing(
|
||||
shutil.rmtree(temp_dir)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to clean up temp files: {e}")
|
||||
|
||||
|
||||
# Update job with GCS path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
@@ -442,29 +547,19 @@ async def _download_and_start_processing(
|
||||
message="Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
# Trigger workers in background
|
||||
async def trigger_workers():
|
||||
worker_service = get_worker_service()
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
# Trigger workers directly
|
||||
worker_service = get_worker_service()
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
background_tasks.add_task(trigger_workers)
|
||||
|
||||
return {
|
||||
'selected_index': selection_index,
|
||||
'selected_title': selected['title'],
|
||||
'selected_artist': selected['artist'],
|
||||
'selected_provider': selected['provider'],
|
||||
}
|
||||
|
||||
except DownloadError as e:
|
||||
except (DownloadError, FlacfetchServiceError) as e:
|
||||
logger.error(f"Download failed for job {job_id}: {e}")
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Download failed: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"Download failed for job {job_id}: {e}", exc_info=True)
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Download failed: {e}")
|
||||
|
||||
|
||||
@router.post("/audio-search/search", response_model=AudioSearchResponse)
|
||||
@@ -590,6 +685,7 @@ async def search_audio(
|
||||
auto_download=body.auto_download,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
@@ -698,7 +794,7 @@ async def search_audio(
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
try:
|
||||
search_results = audio_search_service.search(body.artist, body.title)
|
||||
search_results = await audio_search_service.search_async(body.artist, body.title)
|
||||
except NoResultsError as e:
|
||||
job_manager.fail_job(job_id, f"No audio sources found for: {body.artist} - {body.title}")
|
||||
raise HTTPException(
|
||||
@@ -729,16 +825,22 @@ async def search_audio(
|
||||
# If auto_download, select best and start processing
|
||||
if body.auto_download:
|
||||
best_index = audio_search_service.select_best(search_results)
|
||||
|
||||
|
||||
logger.info(f"Auto-download enabled, selecting result {best_index}")
|
||||
|
||||
selection_info = await _download_and_start_processing(
|
||||
|
||||
selection_info = _validate_and_prepare_selection(
|
||||
job_id=job_id,
|
||||
selection_index=best_index,
|
||||
audio_search_service=audio_search_service,
|
||||
background_tasks=background_tasks,
|
||||
)
|
||||
|
||||
|
||||
# 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,
|
||||
)
|
||||
|
||||
return AudioSearchResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
@@ -826,10 +928,145 @@ async def search_audio(
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
if isinstance(e, (InsufficientCreditsError, RateLimitExceededError)):
|
||||
raise
|
||||
logger.error(f"Error in audio search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/audio-search/search-standalone", response_model=StandaloneSearchResponse)
|
||||
async def search_audio_standalone(
|
||||
request: Request,
|
||||
body: StandaloneSearchRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Search for audio by artist and title WITHOUT creating a job.
|
||||
|
||||
Returns a search session ID and results. Call POST /api/jobs/create-from-search
|
||||
with the session ID and selected result index to create the actual job.
|
||||
|
||||
Credits are checked here (early feedback) but NOT deducted — deduction
|
||||
happens when the job is created via create-from-search.
|
||||
"""
|
||||
# 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"
|
||||
)
|
||||
|
||||
try:
|
||||
user_email = auth_result.user_email
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
# Credit check — give early feedback but do NOT deduct here
|
||||
if not auth_result.is_admin:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
if not user_service.has_credits(user_email):
|
||||
credits_available = user_service.check_credits(user_email)
|
||||
raise InsufficientCreditsError(
|
||||
message="You're out of credits. Buy more to continue creating karaoke videos.",
|
||||
credits_available=credits_available,
|
||||
credits_required=1,
|
||||
)
|
||||
|
||||
# Perform the search (runs in thread to avoid blocking the event loop)
|
||||
audio_search_service = get_audio_search_service()
|
||||
try:
|
||||
search_results = await audio_search_service.search_async(body.artist, body.title)
|
||||
except NoResultsError:
|
||||
# No results is a normal outcome — return empty list, not an error
|
||||
search_results = []
|
||||
except AudioSearchError as e:
|
||||
raise HTTPException(status_code=500, detail=f"Search failed: {e}")
|
||||
|
||||
# Build result response objects
|
||||
result_responses: List[AudioSearchResultResponse] = []
|
||||
results_dicts: List[Dict[str, Any]] = []
|
||||
for r in search_results:
|
||||
raw_dict: Dict[str, Any] = {}
|
||||
if r.raw_result:
|
||||
if isinstance(r.raw_result, dict):
|
||||
raw_dict = r.raw_result
|
||||
else:
|
||||
try:
|
||||
raw_dict = r.raw_result.to_dict()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
result_responses.append(
|
||||
AudioSearchResultResponse(
|
||||
index=r.index,
|
||||
title=r.title,
|
||||
artist=r.artist,
|
||||
provider=r.provider,
|
||||
url=r.url,
|
||||
duration=r.duration,
|
||||
quality=r.quality,
|
||||
source_id=r.source_id,
|
||||
seeders=raw_dict.get('seeders') or r.seeders,
|
||||
target_file=raw_dict.get('target_file') or r.target_file,
|
||||
year=raw_dict.get('year'),
|
||||
label=raw_dict.get('label'),
|
||||
edition_info=raw_dict.get('edition_info'),
|
||||
release_type=raw_dict.get('release_type'),
|
||||
channel=raw_dict.get('channel'),
|
||||
view_count=raw_dict.get('view_count'),
|
||||
size_bytes=raw_dict.get('size_bytes'),
|
||||
target_file_size=raw_dict.get('target_file_size'),
|
||||
track_pattern=raw_dict.get('track_pattern'),
|
||||
match_score=raw_dict.get('match_score'),
|
||||
formatted_size=raw_dict.get('formatted_size'),
|
||||
formatted_duration=raw_dict.get('formatted_duration'),
|
||||
formatted_views=raw_dict.get('formatted_views'),
|
||||
is_lossless=raw_dict.get('is_lossless'),
|
||||
quality_str=raw_dict.get('quality_str'),
|
||||
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
|
||||
)
|
||||
)
|
||||
results_dicts.append(r.to_dict())
|
||||
|
||||
# Store session in Firestore (TTL: 30 minutes)
|
||||
session_id = str(uuid.uuid4())
|
||||
now = datetime.utcnow()
|
||||
session_data = {
|
||||
'session_id': session_id,
|
||||
'user_email': user_email,
|
||||
'tenant_id': tenant_config.id if tenant_config else None,
|
||||
'artist': body.artist,
|
||||
'title': body.title,
|
||||
'results': results_dicts,
|
||||
'remote_search_id': audio_search_service.last_remote_search_id,
|
||||
'created_at': now.isoformat(),
|
||||
'ttl_expiry': now + timedelta(minutes=30),
|
||||
}
|
||||
firestore_service = FirestoreService()
|
||||
firestore_service.create_search_session(session_data)
|
||||
|
||||
logger.info(
|
||||
f"Standalone search complete for {body.artist} - {body.title}: "
|
||||
f"{len(search_results)} results, session={session_id}"
|
||||
)
|
||||
|
||||
return StandaloneSearchResponse(
|
||||
search_session_id=session_id,
|
||||
results=result_responses,
|
||||
results_count=len(result_responses),
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error in standalone audio search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/audio-search/{job_id}/results")
|
||||
async def get_audio_search_results(
|
||||
job_id: str,
|
||||
@@ -872,45 +1109,65 @@ async def select_audio_source(
|
||||
):
|
||||
"""
|
||||
Select an audio source and start job processing.
|
||||
|
||||
This endpoint:
|
||||
1. Validates the job is awaiting selection
|
||||
2. Downloads the selected audio
|
||||
3. Uploads to GCS
|
||||
4. Triggers audio and lyrics workers
|
||||
|
||||
This endpoint returns immediately after validating the selection and
|
||||
transitioning the job to DOWNLOADING_AUDIO state. The actual download
|
||||
runs as a background task so the UI can close the selection dialog
|
||||
without waiting for the download to complete.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
|
||||
# Verify job is awaiting selection
|
||||
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job is not awaiting audio selection (status: {job.status})"
|
||||
)
|
||||
|
||||
|
||||
# Get search service instance
|
||||
# Note: With download_by_id, we no longer need to re-search to populate the cache.
|
||||
# The source_id stored in job.state_data['audio_search_results'] is sufficient.
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
# Apply optional overrides from guided flow Step 3 (Customize)
|
||||
# These fields are set AFTER the job is created (Step 2), so they must be
|
||||
# patched here before the pipeline starts.
|
||||
overrides = {}
|
||||
if body.is_private is not None:
|
||||
overrides["is_private"] = body.is_private
|
||||
if body.display_artist is not None:
|
||||
overrides["display_artist"] = body.display_artist
|
||||
if body.display_title is not None:
|
||||
overrides["display_title"] = body.display_title
|
||||
if overrides:
|
||||
job_manager.update_job(job_id, overrides)
|
||||
logger.info(f"[job:{job_id}] Applied selection overrides: {list(overrides.keys())}")
|
||||
|
||||
# Validate search results exist in job state_data
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="No search results cached for this job")
|
||||
|
||||
selection_info = await _download_and_start_processing(
|
||||
|
||||
# Validate selection and transition to DOWNLOADING_AUDIO (returns immediately)
|
||||
selection_info = _validate_and_prepare_selection(
|
||||
job_id=job_id,
|
||||
selection_index=body.selection_index,
|
||||
audio_search_service=audio_search_service,
|
||||
background_tasks=background_tasks,
|
||||
)
|
||||
|
||||
|
||||
# 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,
|
||||
)
|
||||
|
||||
return AudioSelectResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Audio selected and download started",
|
||||
message="Audio selected, download starting",
|
||||
selected_index=selection_info['selected_index'],
|
||||
selected_title=selection_info['selected_title'],
|
||||
selected_artist=selection_info['selected_artist'],
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""
|
||||
Catalog API routes for song/artist lookup and community version detection.
|
||||
|
||||
Provides autocomplete data from karaoke-decide's MusicBrainz + Spotify catalog,
|
||||
and checks karaokenerds.com for existing community karaoke versions.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/catalog", tags=["catalog"])
|
||||
|
||||
# Simple per-user rate limiting: 20 requests/minute
|
||||
# { user_email: [timestamp, timestamp, ...] }
|
||||
_rate_limit_windows: dict[str, list[float]] = {}
|
||||
RATE_LIMIT_MAX_REQUESTS = 20
|
||||
RATE_LIMIT_WINDOW_SECONDS = 60
|
||||
|
||||
|
||||
def _check_rate_limit(user_email: str) -> None:
|
||||
"""Check per-user rate limit. Raises 429 if exceeded."""
|
||||
now = time.monotonic()
|
||||
window_start = now - RATE_LIMIT_WINDOW_SECONDS
|
||||
|
||||
# Get or create window for this user
|
||||
if user_email not in _rate_limit_windows:
|
||||
_rate_limit_windows[user_email] = []
|
||||
|
||||
# Remove expired entries
|
||||
timestamps = _rate_limit_windows[user_email]
|
||||
_rate_limit_windows[user_email] = [t for t in timestamps if t > 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.",
|
||||
)
|
||||
|
||||
_rate_limit_windows[user_email].append(now)
|
||||
|
||||
|
||||
# --- Response Models ---
|
||||
|
||||
|
||||
class ArtistResult(BaseModel):
|
||||
"""Artist search result from MusicBrainz/Spotify catalog."""
|
||||
name: str
|
||||
mbid: Optional[str] = None
|
||||
disambiguation: Optional[str] = None
|
||||
artist_type: Optional[str] = None
|
||||
spotify_id: Optional[str] = None
|
||||
popularity: Optional[int] = None
|
||||
genres: Optional[list[str]] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
|
||||
class TrackResult(BaseModel):
|
||||
"""Track search result from Spotify catalog."""
|
||||
track_name: str
|
||||
artist_name: str
|
||||
track_id: Optional[str] = None
|
||||
artist_id: Optional[str] = None
|
||||
popularity: Optional[int] = None
|
||||
duration_ms: Optional[int] = None
|
||||
explicit: Optional[bool] = None
|
||||
|
||||
|
||||
class CommunityTrack(BaseModel):
|
||||
"""A community-approved karaoke track from karaokenerds."""
|
||||
brand_name: str
|
||||
brand_code: str
|
||||
youtube_url: str
|
||||
is_community: bool = True
|
||||
|
||||
|
||||
class CommunityCheckSong(BaseModel):
|
||||
"""A song with community karaoke tracks."""
|
||||
title: str
|
||||
artist: str
|
||||
community_tracks: list[CommunityTrack]
|
||||
|
||||
|
||||
class CommunityCheckRequest(BaseModel):
|
||||
"""Request body for community version check."""
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
|
||||
|
||||
class CommunityCheckResponse(BaseModel):
|
||||
"""Response for community version check."""
|
||||
has_community: bool
|
||||
songs: list[CommunityCheckSong]
|
||||
best_youtube_url: Optional[str] = None
|
||||
|
||||
|
||||
# --- Routes ---
|
||||
|
||||
|
||||
@router.get("/artists", response_model=list[ArtistResult])
|
||||
async def search_artists(
|
||||
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),
|
||||
):
|
||||
"""
|
||||
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")
|
||||
|
||||
from backend.services.catalog_proxy_service import search_artists
|
||||
results = await search_artists(q, limit)
|
||||
return results
|
||||
|
||||
|
||||
@router.get("/tracks", response_model=list[TrackResult])
|
||||
async def search_tracks(
|
||||
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"),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
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")
|
||||
|
||||
from backend.services.catalog_proxy_service import search_tracks
|
||||
results = await search_tracks(q, artist, limit)
|
||||
return results
|
||||
|
||||
|
||||
@router.post("/community-check", response_model=CommunityCheckResponse)
|
||||
async def check_community_versions(
|
||||
body: CommunityCheckRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
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")
|
||||
|
||||
from backend.services.karaokenerds_service import check_community_versions
|
||||
result = await check_community_versions(body.artist, body.title)
|
||||
return result
|
||||
@@ -39,6 +39,7 @@ from backend.services.metrics import metrics
|
||||
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, RateLimitExceededError
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
@@ -111,6 +112,9 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
|
||||
class CreateJobFromUrlResponse(BaseModel):
|
||||
"""Response from creating a job from URL."""
|
||||
@@ -172,6 +176,9 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
|
||||
class SignedUploadUrl(BaseModel):
|
||||
"""Signed URL for uploading a file."""
|
||||
@@ -361,6 +368,8 @@ async def upload_and_create_job(
|
||||
other_stems_models: Optional[str] = Form(None, description="Comma-separated list of models for other stems (bass, drums, guitar, etc.)"),
|
||||
# Non-interactive mode
|
||||
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"),
|
||||
):
|
||||
"""
|
||||
Upload an audio file and create a karaoke generation job with full style configuration.
|
||||
@@ -461,10 +470,11 @@ async def upload_and_create_job(
|
||||
|
||||
# Validate credentials for requested distribution services (including defaults)
|
||||
# This prevents accepting jobs that will fail later due to missing credentials
|
||||
# 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:
|
||||
if effective_enable_youtube_upload and not is_private:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -474,7 +484,7 @@ async def upload_and_create_job(
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id:
|
||||
if dist.gdrive_folder_id and not is_private:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -574,6 +584,8 @@ async def upload_and_create_job(
|
||||
request_metadata=request_metadata,
|
||||
# Non-interactive mode
|
||||
non_interactive=non_interactive,
|
||||
# Private (non-published) track mode
|
||||
is_private=is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
@@ -800,6 +812,8 @@ async def upload_and_create_job(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
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
|
||||
@@ -876,6 +890,8 @@ class CreateFinaliseOnlyJobRequest(BaseModel):
|
||||
dropbox_path: Optional[str] = Field(None, description="Dropbox folder path for organized output")
|
||||
gdrive_folder_id: Optional[str] = Field(None, description="Google Drive folder ID for public share uploads")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
|
||||
|
||||
@@ -1022,10 +1038,11 @@ async def create_job_with_upload_urls(
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
|
||||
|
||||
# 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:
|
||||
if effective_enable_youtube_upload and not body.is_private:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -1035,7 +1052,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:
|
||||
if dist.gdrive_folder_id and not body.is_private:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -1104,6 +1121,7 @@ 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,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
@@ -1161,6 +1179,8 @@ async def create_job_with_upload_urls(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
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
|
||||
@@ -1464,10 +1484,11 @@ async def create_job_from_url(
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
|
||||
|
||||
# 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:
|
||||
if effective_enable_youtube_upload and not body.is_private:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -1477,7 +1498,7 @@ async def create_job_from_url(
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id:
|
||||
if dist.gdrive_folder_id and not body.is_private:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -1544,6 +1565,7 @@ async def create_job_from_url(
|
||||
other_stems_models=body.other_stems_models,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
@@ -1635,6 +1657,8 @@ async def create_job_from_url(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job from URL: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
@@ -1771,10 +1795,11 @@ async def create_finalise_only_job(
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
|
||||
|
||||
# Validate distribution credentials if services are requested
|
||||
# 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:
|
||||
if effective_enable_youtube_upload and not body.is_private:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -1784,7 +1809,7 @@ async def create_finalise_only_job(
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id:
|
||||
if dist.gdrive_folder_id and not body.is_private:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -1842,6 +1867,7 @@ async def create_finalise_only_job(
|
||||
finalise_only=True,
|
||||
keep_brand_code=body.keep_brand_code,
|
||||
request_metadata=request_metadata,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
@@ -1899,6 +1925,8 @@ async def create_finalise_only_job(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating finalise-only job: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
@@ -428,6 +428,79 @@ async def check_idle_reminder(
|
||||
return {"status": "error", "job_id": job_id, "message": str(e)}
|
||||
|
||||
|
||||
@router.post("/youtube-queue/process")
|
||||
async def process_youtube_upload_queue(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Process queued YouTube uploads.
|
||||
|
||||
Called by Cloud Scheduler (hourly) to retry uploads that were deferred
|
||||
due to YouTube API quota exhaustion. Can also be triggered manually
|
||||
from the admin dashboard.
|
||||
|
||||
Processes queued uploads one at a time, stopping if quota is exhausted.
|
||||
"""
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue as process_queue
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info("YOUTUBE_QUEUE_PROCESS starting")
|
||||
add_span_attribute("operation", "youtube_queue_process")
|
||||
|
||||
# Run in background so the HTTP response returns quickly
|
||||
# (Cloud Scheduler has a 30min timeout but we don't want to block)
|
||||
async def _process():
|
||||
try:
|
||||
result = await process_queue()
|
||||
logger.info(f"YOUTUBE_QUEUE_PROCESS complete: {result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"YOUTUBE_QUEUE_PROCESS failed: {e}")
|
||||
|
||||
background_tasks.add_task(_process)
|
||||
|
||||
add_span_event("queue_processing_started")
|
||||
return {
|
||||
"status": "started",
|
||||
"message": "YouTube upload queue processing started in background"
|
||||
}
|
||||
|
||||
|
||||
@router.post("/trigger-gdrive-validation")
|
||||
async def trigger_gdrive_validation_endpoint(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Trigger GDrive validation via the Cloud Function.
|
||||
|
||||
Called by a Cloud Tasks delayed task after a job completes and uploads
|
||||
to the public GDrive share. The 5-minute delay ensures E2E test cleanup
|
||||
finishes before the validator checks for sequence gaps.
|
||||
"""
|
||||
from backend.services.gdrive_validator_client import trigger_gdrive_validation
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info("GDRIVE_VALIDATION_TRIGGER starting (delayed post-job)")
|
||||
add_span_attribute("operation", "gdrive_validation_trigger")
|
||||
|
||||
try:
|
||||
result = trigger_gdrive_validation()
|
||||
if result is None:
|
||||
return {"status": "skipped", "message": "GDRIVE_VALIDATOR_URL not configured"}
|
||||
|
||||
status = result.get("status", "unknown")
|
||||
add_span_event("validation_complete", {"result_status": status})
|
||||
return {"status": status, "message": "GDrive validation completed", "result": result}
|
||||
except Exception as e:
|
||||
logger.exception(f"GDrive validation trigger failed: {e}")
|
||||
add_span_event("error", {"error": str(e)})
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def internal_health(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
|
||||
+816
-18
@@ -8,10 +8,16 @@ Handles job lifecycle endpoints including:
|
||||
- Job deletion and cancellation
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Dict, Any
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
|
||||
|
||||
from datetime import datetime
|
||||
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
|
||||
from backend.models.requests import (
|
||||
URLSubmissionRequest,
|
||||
@@ -20,6 +26,7 @@ from backend.models.requests import (
|
||||
CancelJobRequest,
|
||||
InstrumentalSelection,
|
||||
CompleteReviewRequest,
|
||||
CreateCustomInstrumentalRequest,
|
||||
)
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.worker_service import get_worker_service
|
||||
@@ -31,6 +38,9 @@ from backend.services.auth_service import AuthResult
|
||||
from backend.services.metrics import metrics
|
||||
from backend.middleware.tenant import get_tenant_from_request
|
||||
from backend.utils.test_data import is_test_email
|
||||
from backend.exceptions import InsufficientCreditsError, RateLimitExceededError
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from pydantic import BaseModel, Field, validator
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -115,7 +125,8 @@ async def create_job(
|
||||
enable_youtube_upload=effective_enable_youtube_upload,
|
||||
youtube_description=request.youtube_description,
|
||||
webhook_url=request.webhook_url,
|
||||
user_email=user_email
|
||||
user_email=user_email,
|
||||
is_private=request.is_private or False,
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
|
||||
@@ -133,6 +144,8 @@ async def create_job(
|
||||
job_id=job.job_id,
|
||||
message="Job created successfully. Processing started."
|
||||
)
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@@ -188,7 +201,33 @@ def _check_job_ownership(job: Job, auth_result: AuthResult) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
@router.get("", response_model=List[Job])
|
||||
_SUMMARY_STATE_DATA_KEYS = {
|
||||
'brand_code', 'youtube_url', 'dropbox_link',
|
||||
'audio_progress', 'lyrics_progress',
|
||||
'audio_complete', 'lyrics_complete',
|
||||
'backing_vocals_analysis',
|
||||
}
|
||||
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete']
|
||||
|
||||
|
||||
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Strip state_data down to dashboard-required keys."""
|
||||
sd = data.get('state_data')
|
||||
if isinstance(sd, dict):
|
||||
data['state_data'] = {k: v for k, v in sd.items() if k in _SUMMARY_STATE_DATA_KEYS}
|
||||
return data
|
||||
|
||||
|
||||
def _prune_file_urls(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Strip file_urls down to dashboard-required keys."""
|
||||
fu = data.get('file_urls')
|
||||
if isinstance(fu, dict):
|
||||
data['file_urls'] = {k: v for k, v in fu.items() if k in _SUMMARY_FILE_URLS_KEYS}
|
||||
return data
|
||||
|
||||
|
||||
@router.get("", response_model=None)
|
||||
async def list_jobs(
|
||||
request: Request,
|
||||
status: Optional[JobStatus] = None,
|
||||
@@ -198,8 +237,10 @@ async def list_jobs(
|
||||
created_before: Optional[str] = None,
|
||||
exclude_test: bool = True,
|
||||
limit: int = 100,
|
||||
fields: Optional[str] = None,
|
||||
hide_completed: bool = False,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> List[Job]:
|
||||
):
|
||||
"""
|
||||
List jobs with optional filters.
|
||||
|
||||
@@ -214,9 +255,13 @@ async def list_jobs(
|
||||
created_before: Filter jobs created before this ISO datetime
|
||||
exclude_test: If True (default), exclude jobs from test users (admin only)
|
||||
limit: Maximum number of jobs to return (default 100)
|
||||
fields: Set to "summary" for reduced payload with only dashboard-required fields
|
||||
hide_completed: If True, exclude successful completions (complete, prep_complete). Failed jobs remain visible.
|
||||
|
||||
Returns:
|
||||
List of jobs matching filters, ordered by created_at descending
|
||||
List of jobs matching filters, ordered by created_at descending.
|
||||
When fields=summary, returns List[dict] (pruned).
|
||||
Otherwise returns List[Job] (full model).
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
@@ -253,6 +298,32 @@ async def list_jobs(
|
||||
# Tenant users only see jobs from their tenant
|
||||
tenant_id = get_tenant_from_request(request)
|
||||
|
||||
# --- Summary mode: field-projected query returning dicts ---
|
||||
if fields == "summary":
|
||||
exclude_statuses = _HIDE_COMPLETED_STATUSES if hide_completed else None
|
||||
jobs_dicts = job_manager.list_jobs_summary(
|
||||
status=status,
|
||||
exclude_statuses=exclude_statuses,
|
||||
environment=environment,
|
||||
client_id=client_id,
|
||||
created_after=created_after_dt,
|
||||
created_before=created_before_dt,
|
||||
user_email=user_email_filter,
|
||||
tenant_id=tenant_id,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
# Exclude test user jobs (Python-side, same as full mode)
|
||||
if exclude_test and auth_result.is_admin:
|
||||
jobs_dicts = [j for j in jobs_dicts if not is_test_email(j.get('user_email') or "")]
|
||||
|
||||
# Safety-net pruning (in case Firestore returned extra nested keys)
|
||||
jobs_dicts = [_prune_file_urls(_prune_state_data(j)) for j in jobs_dicts]
|
||||
|
||||
logger.debug(f"Listed {len(jobs_dicts)} summary jobs for user={auth_result.user_email}")
|
||||
return jobs_dicts
|
||||
|
||||
# --- Full mode: existing behaviour (List[Job]) ---
|
||||
jobs = job_manager.list_jobs(
|
||||
status=status,
|
||||
environment=environment,
|
||||
@@ -293,6 +364,24 @@ async def delete_job(
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to delete this job")
|
||||
|
||||
# Recycle any unreturned brand code before deleting the job record
|
||||
state_data = job.state_data or {}
|
||||
brand_code = state_data.get('brand_code')
|
||||
if brand_code:
|
||||
if not job.outputs_deleted_at:
|
||||
logger.warning(
|
||||
f"Deleting job {job_id} with brand_code {brand_code} whose outputs "
|
||||
f"were not cleaned up first. Brand code will be recycled but "
|
||||
f"distributed files (GDrive/Dropbox/YouTube) may be orphaned."
|
||||
)
|
||||
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"Recycled brand code {brand_code} before deleting job {job_id}")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
|
||||
job_manager.delete_job(job_id, delete_files=delete_files)
|
||||
|
||||
return {"status": "success", "message": f"Job {job_id} deleted"}
|
||||
@@ -536,8 +625,14 @@ async def submit_corrections(
|
||||
)
|
||||
|
||||
try:
|
||||
# Store corrected lyrics in state_data
|
||||
job_manager.update_state_data(job_id, 'corrected_lyrics', submission.corrections)
|
||||
# Strip reference_lyrics from Firestore save to avoid exceeding 1MB document
|
||||
# limit. reference_lyrics can be very large (e.g. Genius fetching non-lyrics
|
||||
# content like screenplays). The full data is preserved in the GCS upload below.
|
||||
corrections_for_firestore = {
|
||||
k: v for k, v in submission.corrections.items()
|
||||
if k != 'reference_lyrics'
|
||||
}
|
||||
job_manager.update_state_data(job_id, 'corrected_lyrics', corrections_for_firestore)
|
||||
if submission.user_notes:
|
||||
job_manager.update_state_data(job_id, 'review_notes', submission.user_notes)
|
||||
|
||||
@@ -570,6 +665,278 @@ async def submit_corrections(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{job_id}/edit-log")
|
||||
async def submit_edit_log(
|
||||
job_id: str,
|
||||
edit_log: Dict[str, Any],
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Store an edit log from a lyrics review session.
|
||||
|
||||
Edit logs capture what edits users made and optional feedback on why,
|
||||
for use as training data to improve transcription models.
|
||||
|
||||
Stored to GCS as jobs/{job_id}/lyrics/edit_log_{session_id}.json.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
|
||||
session_id = edit_log.get("session_id", "unknown")
|
||||
entries = edit_log.get("entries", [])
|
||||
feedback_count = sum(1 for e in entries if e.get("feedback") and e["feedback"].get("reason") != "no_response")
|
||||
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/edit_log_{session_id}.json"
|
||||
storage.upload_json(gcs_path, edit_log)
|
||||
|
||||
job_manager.update_state_data(job_id, 'last_edit_log_path', gcs_path)
|
||||
job_manager.update_state_data(job_id, 'last_edit_log_session', session_id)
|
||||
|
||||
logger.info(
|
||||
f"Job {job_id}: Edit log saved — {len(entries)} entries, "
|
||||
f"{feedback_count} with feedback, session {session_id}"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"entries_count": len(entries),
|
||||
"feedback_count": feedback_count,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error saving edit log for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{job_id}/create-custom-instrumental")
|
||||
async def create_custom_instrumental(
|
||||
job_id: str,
|
||||
request: CreateCustomInstrumentalRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Create a custom instrumental by muting regions of backing vocals.
|
||||
|
||||
Downloads the clean instrumental and backing vocals stems, applies mute
|
||||
regions, combines them, uploads to GCS, and returns a signed URL for playback.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
)
|
||||
|
||||
# Get stem paths from job
|
||||
stems = job.file_urls.get('stems', {})
|
||||
clean_path = stems.get('instrumental_clean')
|
||||
backing_path = stems.get('backing_vocals')
|
||||
|
||||
if not clean_path or not backing_path:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Job missing required stems (instrumental_clean and/or backing_vocals)"
|
||||
)
|
||||
|
||||
try:
|
||||
from backend.services.audio_editing_service import AudioEditingService
|
||||
from karaoke_gen.instrumental_review import MuteRegion
|
||||
|
||||
storage = StorageService()
|
||||
editing_service = AudioEditingService(storage_service=storage)
|
||||
|
||||
# Convert request mute regions to domain model
|
||||
mute_regions = [
|
||||
MuteRegion(start_seconds=r.start_seconds, end_seconds=r.end_seconds)
|
||||
for r in request.mute_regions
|
||||
]
|
||||
|
||||
# Create custom instrumental and upload to GCS (offload blocking IO to thread)
|
||||
output_path = f"jobs/{job_id}/stems/custom_instrumental.flac"
|
||||
result = await asyncio.get_event_loop().run_in_executor(
|
||||
None,
|
||||
lambda: editing_service.create_custom_instrumental(
|
||||
gcs_clean_instrumental_path=clean_path,
|
||||
gcs_backing_vocals_path=backing_path,
|
||||
mute_regions=mute_regions,
|
||||
gcs_output_path=output_path,
|
||||
job_id=job_id,
|
||||
)
|
||||
)
|
||||
|
||||
# Store the custom instrumental path in job file_urls
|
||||
job_manager.update_file_url(job_id, 'stems', 'custom_instrumental', output_path)
|
||||
|
||||
# Generate signed URL for playback
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
transcoding = AudioTranscodingService(storage_service=storage)
|
||||
audio_url = await transcoding.get_review_audio_url_async(output_path, expiration_minutes=120)
|
||||
|
||||
logger.info(f"Job {job_id}: Custom instrumental created with {len(mute_regions)} mute regions")
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Custom instrumental created with {len(mute_regions)} mute regions",
|
||||
"audio_url": audio_url,
|
||||
"muted_duration_seconds": result.total_muted_duration_seconds,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating custom instrumental for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{job_id}/upload-instrumental")
|
||||
async def upload_custom_instrumental(
|
||||
job_id: str,
|
||||
file: UploadFile = File(...),
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Upload a custom instrumental audio file for use during review.
|
||||
|
||||
Accepts any audio format supported by pydub/ffmpeg (mp3, wav, flac, ogg, etc.).
|
||||
The file is stored to GCS and its path recorded in the job's stems metadata.
|
||||
The user can then select 'custom' as their instrumental_selection when completing review.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to modify this job")
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
)
|
||||
|
||||
# Determine extension from filename or content type
|
||||
original_filename = file.filename or "instrumental"
|
||||
suffix = Path(original_filename).suffix.lower()
|
||||
if not suffix:
|
||||
content_type = file.content_type or ""
|
||||
suffix_map = {
|
||||
"audio/mpeg": ".mp3",
|
||||
"audio/mp3": ".mp3",
|
||||
"audio/wav": ".wav",
|
||||
"audio/x-wav": ".wav",
|
||||
"audio/flac": ".flac",
|
||||
"audio/x-flac": ".flac",
|
||||
"audio/ogg": ".ogg",
|
||||
"audio/aac": ".aac",
|
||||
"audio/mp4": ".m4a",
|
||||
}
|
||||
suffix = suffix_map.get(content_type, ".audio")
|
||||
|
||||
storage = StorageService()
|
||||
tmp_path = None
|
||||
flac_path = None
|
||||
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
||||
tmp_path = tmp.name
|
||||
content = await file.read()
|
||||
tmp.write(content)
|
||||
|
||||
# Get duration of uploaded file using pydub
|
||||
from pydub import AudioSegment
|
||||
audio_segment = AudioSegment.from_file(tmp_path)
|
||||
upload_duration = len(audio_segment) / 1000.0
|
||||
|
||||
# Get duration of original job audio to validate match
|
||||
original_duration = await _get_audio_duration_ffprobe_signed(job_id, job, storage)
|
||||
if original_duration is not None:
|
||||
diff = abs(upload_duration - original_duration)
|
||||
if diff > 0.5:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
f"Duration mismatch: uploaded file is {upload_duration:.1f}s "
|
||||
f"but original audio is {original_duration:.1f}s. "
|
||||
f"The instrumental must be exactly {original_duration:.1f}s (±0.5s)."
|
||||
),
|
||||
)
|
||||
|
||||
# Convert to FLAC for consistency with the rest of the pipeline
|
||||
# (GCE encoding worker searches for *.flac patterns)
|
||||
flac_path = tmp_path.rsplit('.', 1)[0] + '.flac' if '.' in tmp_path else tmp_path + '.flac'
|
||||
if suffix != '.flac':
|
||||
audio_segment.export(flac_path, format='flac')
|
||||
else:
|
||||
flac_path = tmp_path # Already FLAC, no conversion needed
|
||||
|
||||
# Upload to GCS (always as .flac)
|
||||
output_path = f"jobs/{job_id}/stems/custom_instrumental.flac"
|
||||
storage.upload_file(flac_path, output_path)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error processing uploaded instrumental: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Failed to process audio file: {str(e)}")
|
||||
finally:
|
||||
if tmp_path and os.path.exists(tmp_path):
|
||||
os.unlink(tmp_path)
|
||||
if flac_path and flac_path != tmp_path and os.path.exists(flac_path):
|
||||
os.unlink(flac_path)
|
||||
|
||||
# Record in job file_urls
|
||||
job_manager.update_file_url(job_id, 'stems', 'custom_instrumental', output_path)
|
||||
|
||||
logger.info(f"Job {job_id}: Custom instrumental uploaded ({upload_duration:.1f}s) to {output_path}")
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"duration_seconds": upload_duration,
|
||||
"message": f"Custom instrumental uploaded ({upload_duration:.1f}s)",
|
||||
}
|
||||
|
||||
|
||||
async def _get_audio_duration_ffprobe_signed(job_id: str, job, storage: StorageService) -> Optional[float]:
|
||||
"""
|
||||
Get the duration of the job's original audio using ffprobe on a signed GCS URL.
|
||||
|
||||
Uses ffprobe which reads only the container header - fast even for large files.
|
||||
Returns None if the duration cannot be determined (non-fatal, upload proceeds).
|
||||
"""
|
||||
gcs_path = job.input_media_gcs_path
|
||||
if not gcs_path:
|
||||
return None
|
||||
|
||||
try:
|
||||
signed_url = storage.generate_signed_url(gcs_path, expiration_minutes=5)
|
||||
|
||||
def _run_ffprobe() -> float:
|
||||
result = subprocess.run(
|
||||
['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', signed_url],
|
||||
capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise ValueError(f"ffprobe error: {result.stderr[:200]}")
|
||||
data = json.loads(result.stdout)
|
||||
return float(data['format']['duration'])
|
||||
|
||||
return await asyncio.get_event_loop().run_in_executor(None, _run_ffprobe)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Could not determine original audio duration: {e}")
|
||||
return None
|
||||
|
||||
|
||||
@router.post("/{job_id}/complete-review")
|
||||
async def complete_review(
|
||||
job_id: str,
|
||||
@@ -1085,6 +1452,144 @@ async def retry_job(
|
||||
"retry_stage": "from_beginning"
|
||||
}
|
||||
|
||||
# If we have audio search download params, retry the download
|
||||
elif (job.audio_source_type == 'audio_search' and
|
||||
job.source_name and job.source_id):
|
||||
logger.info(
|
||||
f"Job {job_id}: Has audio search params, retrying download: "
|
||||
f"source_name={job.source_name}, source_id={job.source_id}"
|
||||
)
|
||||
|
||||
# Import needed services
|
||||
from backend.services.audio_search_service import get_audio_search_service
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError
|
||||
)
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
# Clear error state
|
||||
job_manager.update_job(job_id, {
|
||||
'error_message': None,
|
||||
'error_details': None,
|
||||
})
|
||||
|
||||
# Reset to DOWNLOADING_AUDIO state
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING_AUDIO,
|
||||
progress=12,
|
||||
message=f"Retrying audio download from {job.source_name}"
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
# Retry download using saved params
|
||||
# This is similar to the logic in audio_search.py:_download_and_start_processing
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
try:
|
||||
if job.source_name == 'YouTube':
|
||||
# Use YouTubeDownloadService
|
||||
youtube_service = get_youtube_download_service()
|
||||
video_id = job.source_id
|
||||
|
||||
try:
|
||||
audio_gcs_path = await youtube_service.download_by_id(
|
||||
video_id=video_id,
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
)
|
||||
filename = os.path.basename(audio_gcs_path)
|
||||
except YouTubeDownloadError as e:
|
||||
job_manager.fail_job(job_id, f"Audio download retry failed: YouTube download failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"YouTube download failed: {e}")
|
||||
|
||||
elif job.source_name in ['RED', 'OPS', 'Spotify']:
|
||||
# Use audio search service for torrent/Spotify sources
|
||||
if not audio_search_service.is_remote_enabled():
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
f"Cannot retry: flacfetch service not configured for {job.source_name}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Cannot download from {job.source_name} without remote flacfetch service."
|
||||
)
|
||||
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
|
||||
try:
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=job.source_name,
|
||||
source_id=job.source_id,
|
||||
output_dir="",
|
||||
target_file=job.target_file,
|
||||
download_url=job.download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
audio_gcs_path = result.filepath
|
||||
if audio_gcs_path.startswith('gs://'):
|
||||
audio_gcs_path = audio_gcs_path.replace('gs://karaoke-gen-storage/', '', 1)
|
||||
filename = os.path.basename(result.filepath)
|
||||
|
||||
except DownloadError as e:
|
||||
job_manager.fail_job(job_id, f"Audio download retry failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Download failed: {e}")
|
||||
else:
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
f"Cannot retry: unknown source type {job.source_name}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unknown source type: {job.source_name}"
|
||||
)
|
||||
|
||||
# Update job with GCS path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': filename,
|
||||
})
|
||||
|
||||
# Transition to DOWNLOADING and trigger workers
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=15,
|
||||
message="Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
# Trigger workers in background
|
||||
async def trigger_workers():
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
background_tasks.add_task(trigger_workers)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"job_status": "downloading",
|
||||
"message": f"Job retry started: re-downloading from {job.source_name}",
|
||||
"retry_stage": "audio_download"
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error retrying audio download for job {job_id}: {e}", exc_info=True)
|
||||
job_manager.fail_job(job_id, f"Audio download retry failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Download retry failed: {e}")
|
||||
|
||||
else:
|
||||
# No input audio available - job needs to be resubmitted
|
||||
raise HTTPException(
|
||||
@@ -1220,6 +1725,7 @@ async def cleanup_distribution(
|
||||
# Clean up Dropbox
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
dropbox_cleaned = False
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
@@ -1229,6 +1735,7 @@ async def cleanup_distribution(
|
||||
folder_name = f"{brand_code} - {base_name}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
success = dropbox.delete_folder(full_path)
|
||||
dropbox_cleaned = success
|
||||
results["dropbox"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"path": full_path
|
||||
@@ -1240,25 +1747,92 @@ async def cleanup_distribution(
|
||||
results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Clean up Google Drive
|
||||
# Use tracked file IDs if available; otherwise fall back to searching by brand code.
|
||||
# This handles old jobs where gdrive_files was not persisted (e.g., uploaded before
|
||||
# file ID tracking was implemented, or when GDrive upload silently failed and a
|
||||
# previous test run left files behind).
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
gdrive_folder_id = getattr(job, 'gdrive_folder_id', None)
|
||||
gdrive_cleaned = False
|
||||
|
||||
if gdrive_files or (gdrive_folder_id and brand_code):
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
# gdrive_files is a dict like {"mp4": "file_id", "mp4_720p": "file_id", "cdg": "file_id"}
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
results["gdrive"] = {
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results
|
||||
}
|
||||
file_ids: list = []
|
||||
gdrive_method = None # track how files were located for response
|
||||
|
||||
if gdrive_files and isinstance(gdrive_files, dict):
|
||||
# Fast path: delete using tracked file IDs from state_data
|
||||
file_ids = [v for v in gdrive_files.values() if v]
|
||||
logger.info(
|
||||
f"GDrive cleanup for job {job_id}: "
|
||||
f"using {len(file_ids)} tracked file IDs"
|
||||
)
|
||||
|
||||
if not file_ids and gdrive_folder_id and brand_code:
|
||||
# Fallback: search by brand code prefix in CDG/, MP4/, MP4-720p/ subfolders.
|
||||
# Handles jobs where gdrive_files was not tracked (old jobs, or jobs where
|
||||
# GDrive upload succeeded but file IDs were lost).
|
||||
logger.info(
|
||||
f"GDrive cleanup for job {job_id}: "
|
||||
f"no tracked file IDs, searching by brand_code '{brand_code}'"
|
||||
)
|
||||
file_ids = gdrive.find_files_by_brand_code(gdrive_folder_id, brand_code)
|
||||
gdrive_method = "brand_code_search"
|
||||
|
||||
if file_ids:
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
gdrive_cleaned = all_success
|
||||
results["gdrive"] = {
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results,
|
||||
}
|
||||
if gdrive_method:
|
||||
results["gdrive"]["method"] = gdrive_method
|
||||
else:
|
||||
gdrive_cleaned = True # Nothing to delete
|
||||
results["gdrive"] = {
|
||||
"status": "skipped",
|
||||
"reason": "no files found to delete",
|
||||
}
|
||||
else:
|
||||
results["gdrive"] = {"status": "failed", "reason": "Google Drive credentials not configured"}
|
||||
results["gdrive"] = {
|
||||
"status": "failed",
|
||||
"reason": "Google Drive credentials not configured",
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True)
|
||||
logger.error(
|
||||
f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True
|
||||
)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
if not gdrive_folder_id:
|
||||
results["gdrive"]["reason"] = "no gdrive_folder_id on job and no tracked file IDs"
|
||||
|
||||
# Recycle the brand code so it can be reused — but only after GDrive is confirmed clean.
|
||||
# If we recycle before GDrive cleanup, a new job could claim the same brand code and
|
||||
# collide with leftover files on GDrive (duplicate brand code in public share).
|
||||
if dropbox_cleaned and brand_code and gdrive_cleaned:
|
||||
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)
|
||||
results["dropbox"]["recycled_brand_code"] = True
|
||||
logger.info(f"Recycled brand code {brand_code} after full distribution cleanup")
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
results["dropbox"]["recycled_brand_code"] = False
|
||||
elif dropbox_cleaned and brand_code:
|
||||
logger.warning(
|
||||
f"Brand code {brand_code} NOT recycled: GDrive cleanup did not confirm success "
|
||||
f"(gdrive_cleaned={gdrive_cleaned}). Brand code will remain reserved to prevent "
|
||||
f"collisions with leftover GDrive files."
|
||||
)
|
||||
|
||||
# Delete the job if requested
|
||||
if delete_job:
|
||||
@@ -1273,3 +1847,227 @@ async def cleanup_distribution(
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Guided Flow: Create job from search session
|
||||
# ============================================================================
|
||||
|
||||
class CreateFromSearchRequest(BaseModel):
|
||||
"""Request to create a job from a completed standalone search session."""
|
||||
search_session_id: str = Field(..., description="Session ID returned by /api/audio-search/search-standalone")
|
||||
selection_index: int = Field(..., description="Index of the selected audio source from search results")
|
||||
artist: str = Field(..., description="Search artist name (from Step 1)")
|
||||
title: str = Field(..., description="Search title (from Step 1)")
|
||||
display_artist: Optional[str] = Field(None, description="Display artist override for title screens/filenames")
|
||||
display_title: Optional[str] = Field(None, description="Display title override for title screens/filenames")
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only, no YouTube/GDrive")
|
||||
|
||||
@validator('display_artist', 'display_title')
|
||||
def strip_whitespace(cls, v):
|
||||
if v is not None:
|
||||
return v.strip() or None
|
||||
return v
|
||||
|
||||
|
||||
@router.post("/create-from-search", response_model=JobResponse)
|
||||
async def create_job_from_search(
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: CreateFromSearchRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> JobResponse:
|
||||
"""
|
||||
Create a karaoke job from a previously completed standalone search session.
|
||||
|
||||
This is the second half of the guided job creation flow:
|
||||
1. POST /api/audio-search/search-standalone → search_session_id + results
|
||||
2. User picks a result (Step 2 of wizard)
|
||||
3. User confirms job settings (Step 3 of wizard)
|
||||
4. POST /api/jobs/create-from-search → job_id (this endpoint)
|
||||
|
||||
The job is created with all final field values at creation time (including
|
||||
is_private and display overrides). It skips AWAITING_AUDIO_SELECTION and
|
||||
goes directly to DOWNLOADING_AUDIO, then triggers workers.
|
||||
|
||||
Credit deduction happens here (inside job_manager.create_job).
|
||||
"""
|
||||
# Lazy imports from audio_search to avoid circular imports at module level
|
||||
from backend.api.routes.audio_search import (
|
||||
_validate_and_prepare_selection,
|
||||
_download_audio_and_trigger_workers,
|
||||
extract_request_metadata,
|
||||
)
|
||||
from backend.services.audio_search_service import get_audio_search_service
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
|
||||
try:
|
||||
user_email = auth_result.user_email
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
# Read the session non-destructively for validation.
|
||||
# consume_search_session (atomic read+delete) is called later, just before job creation,
|
||||
# so that a 4xx validation error leaves the session intact for the user to retry.
|
||||
firestore_service = FirestoreService()
|
||||
session = firestore_service.get_search_session(body.search_session_id)
|
||||
if not session:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Search expired — please search again"
|
||||
)
|
||||
|
||||
# Verify the session belongs to the requesting user (or admin)
|
||||
if not auth_result.is_admin and session.get('user_email') != user_email:
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to use this search session")
|
||||
|
||||
# Verify tenant consistency — session must have been created in the same tenant context
|
||||
request_tenant_id = getattr(request.state, 'tenant_id', None)
|
||||
if session.get('tenant_id') != request_tenant_id:
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to use this search session")
|
||||
|
||||
# Check TTL (belt-and-suspenders — Firestore TTL may not delete immediately)
|
||||
ttl_expiry = session.get('ttl_expiry')
|
||||
if ttl_expiry:
|
||||
if isinstance(ttl_expiry, str):
|
||||
try:
|
||||
ttl_expiry = datetime.fromisoformat(ttl_expiry)
|
||||
except ValueError:
|
||||
ttl_expiry = None
|
||||
if ttl_expiry and datetime.utcnow() > ttl_expiry.replace(tzinfo=None):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Search expired — please search again"
|
||||
)
|
||||
|
||||
search_results = session.get('results', [])
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="Search session has no results")
|
||||
|
||||
if body.selection_index < 0 or body.selection_index >= len(search_results):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid selection index {body.selection_index}. Valid range: 0-{len(search_results)-1}"
|
||||
)
|
||||
|
||||
# Apply server defaults (same as existing search endpoint)
|
||||
settings_obj = get_settings()
|
||||
effective_dropbox_path = settings_obj.default_dropbox_path
|
||||
effective_gdrive_folder_id = settings_obj.default_gdrive_folder_id
|
||||
effective_discord_webhook_url = settings_obj.default_discord_webhook_url
|
||||
effective_enable_youtube_upload = settings_obj.default_enable_youtube_upload
|
||||
effective_brand_prefix = settings_obj.default_brand_prefix
|
||||
effective_youtube_description = settings_obj.default_youtube_description
|
||||
|
||||
# Apply default theme
|
||||
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}")
|
||||
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(effective_theme_id, None, None)
|
||||
|
||||
# Determine display values
|
||||
session_artist = session.get('artist', body.artist)
|
||||
session_title = session.get('title', body.title)
|
||||
effective_display_artist = body.display_artist or session_artist
|
||||
effective_display_title = body.display_title or session_title
|
||||
|
||||
tenant_id = session.get('tenant_id')
|
||||
|
||||
request_metadata = extract_request_metadata(request, created_from="guided_flow")
|
||||
|
||||
# All validation passed — atomically consume (read+delete) the session to prevent
|
||||
# a second concurrent request from creating a duplicate job.
|
||||
consumed_session = firestore_service.consume_search_session(body.search_session_id)
|
||||
if not consumed_session:
|
||||
# Another concurrent request already consumed the session
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Search expired — please search again"
|
||||
)
|
||||
|
||||
# Create the job with all final values
|
||||
job_create = JobCreate(
|
||||
artist=effective_display_artist,
|
||||
title=effective_display_title,
|
||||
theme_id=effective_theme_id,
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
brand_prefix=effective_brand_prefix,
|
||||
enable_youtube_upload=effective_enable_youtube_upload,
|
||||
youtube_description=effective_youtube_description,
|
||||
youtube_description_template=effective_youtube_description,
|
||||
discord_webhook_url=effective_discord_webhook_url,
|
||||
dropbox_path=effective_dropbox_path,
|
||||
gdrive_folder_id=effective_gdrive_folder_id,
|
||||
user_email=user_email,
|
||||
audio_search_artist=session_artist,
|
||||
audio_search_title=session_title,
|
||||
request_metadata=request_metadata,
|
||||
is_private=body.is_private,
|
||||
tenant_id=tenant_id,
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
logger.info(f"Created job {job_id} from search session {body.search_session_id}")
|
||||
|
||||
metrics.record_job_created(job_id, source="guided_search")
|
||||
|
||||
# Apply default theme style to job (copy style_params.json to job folder)
|
||||
if effective_theme_id:
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
try:
|
||||
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, effective_theme_id, {}
|
||||
)
|
||||
theme_update = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': theme_style_assets,
|
||||
}
|
||||
if youtube_desc and not effective_youtube_description:
|
||||
theme_update['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, theme_update)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to prepare theme '{effective_theme_id}' for job {job_id}: {e}")
|
||||
|
||||
# Store search results and remote_search_id in job state_data
|
||||
# (required by _download_audio_and_trigger_workers)
|
||||
state_data_update: Dict[str, Any] = {
|
||||
'audio_search_results': search_results,
|
||||
'audio_search_count': len(search_results),
|
||||
}
|
||||
if session.get('remote_search_id'):
|
||||
state_data_update['remote_search_id'] = session['remote_search_id']
|
||||
job_manager.update_job(job_id, {'state_data': state_data_update})
|
||||
|
||||
# Transition to DOWNLOADING_AUDIO (skips AWAITING_AUDIO_SELECTION entirely)
|
||||
_validate_and_prepare_selection(
|
||||
job_id=job_id,
|
||||
selection_index=body.selection_index,
|
||||
)
|
||||
|
||||
# Trigger audio download as a background task
|
||||
audio_search_service = get_audio_search_service()
|
||||
background_tasks.add_task(
|
||||
_download_audio_and_trigger_workers,
|
||||
job_id,
|
||||
body.selection_index,
|
||||
audio_search_service,
|
||||
)
|
||||
|
||||
return JobResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Job created successfully. Audio download starting."
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except (InsufficientCreditsError, RateLimitExceededError):
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job from search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@@ -36,10 +36,23 @@ class RateLimitStatsResponse(BaseModel):
|
||||
beta_ip_per_day_limit: int
|
||||
rate_limiting_enabled: bool
|
||||
|
||||
# Current usage
|
||||
# Current usage (legacy count-based)
|
||||
youtube_uploads_today: int
|
||||
youtube_uploads_remaining: int
|
||||
|
||||
# YouTube quota (unit-based tracking)
|
||||
youtube_quota_units_consumed: int
|
||||
youtube_quota_units_remaining: int
|
||||
youtube_quota_daily_limit: int
|
||||
youtube_quota_effective_limit: int
|
||||
youtube_quota_upload_cost: int
|
||||
youtube_quota_estimated_uploads_remaining: int
|
||||
youtube_quota_seconds_until_reset: int
|
||||
|
||||
# YouTube upload queue
|
||||
youtube_uploads_queued: int
|
||||
youtube_uploads_failed: int
|
||||
|
||||
# Blocklist stats
|
||||
disposable_domains_count: int
|
||||
blocked_emails_count: int
|
||||
@@ -49,6 +62,29 @@ class RateLimitStatsResponse(BaseModel):
|
||||
total_overrides: int
|
||||
|
||||
|
||||
class YouTubeQueueEntry(BaseModel):
|
||||
"""A queued YouTube upload entry."""
|
||||
job_id: str
|
||||
status: str
|
||||
reason: Optional[str] = None
|
||||
user_email: Optional[str] = None
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
brand_code: Optional[str] = None
|
||||
queued_at: Optional[datetime] = None
|
||||
attempts: int = 0
|
||||
max_attempts: int = 5
|
||||
last_error: Optional[str] = None
|
||||
youtube_url: Optional[str] = None
|
||||
notification_sent: bool = False
|
||||
|
||||
|
||||
class YouTubeQueueListResponse(BaseModel):
|
||||
"""List of YouTube upload queue entries."""
|
||||
entries: List[YouTubeQueueEntry]
|
||||
stats: dict
|
||||
|
||||
|
||||
class UserRateLimitStatusResponse(BaseModel):
|
||||
"""Rate limit status for a specific user."""
|
||||
email: str
|
||||
@@ -124,16 +160,27 @@ async def get_rate_limit_stats(
|
||||
"""
|
||||
Get current rate limit statistics.
|
||||
|
||||
Returns configuration values, current usage counts, and blocklist stats.
|
||||
Returns configuration values, current usage counts, quota tracking,
|
||||
queue stats, and blocklist stats.
|
||||
"""
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
email_validation = get_email_validation_service()
|
||||
|
||||
# Get YouTube uploads today
|
||||
# Get YouTube uploads today (legacy count)
|
||||
youtube_today = rate_limit_service.get_youtube_uploads_today()
|
||||
youtube_limit = settings.rate_limit_youtube_uploads_per_day
|
||||
youtube_remaining = max(0, youtube_limit - youtube_today) if youtube_limit > 0 else -1
|
||||
|
||||
# Get YouTube quota stats (unit-based)
|
||||
from backend.services.youtube_quota_service import get_youtube_quota_service
|
||||
quota_service = get_youtube_quota_service()
|
||||
quota_stats = quota_service.get_quota_stats()
|
||||
|
||||
# Get YouTube upload queue stats
|
||||
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
|
||||
queue_service = get_youtube_upload_queue_service()
|
||||
queue_stats = queue_service.get_queue_stats()
|
||||
|
||||
# Get blocklist stats
|
||||
blocklist_stats = email_validation.get_blocklist_stats()
|
||||
|
||||
@@ -147,6 +194,15 @@ async def get_rate_limit_stats(
|
||||
rate_limiting_enabled=settings.enable_rate_limiting,
|
||||
youtube_uploads_today=youtube_today,
|
||||
youtube_uploads_remaining=youtube_remaining,
|
||||
youtube_quota_units_consumed=quota_stats["units_consumed"],
|
||||
youtube_quota_units_remaining=quota_stats["units_remaining"],
|
||||
youtube_quota_daily_limit=quota_stats["units_limit"],
|
||||
youtube_quota_effective_limit=quota_stats["effective_limit"],
|
||||
youtube_quota_upload_cost=quota_stats["upload_cost"],
|
||||
youtube_quota_estimated_uploads_remaining=quota_stats["estimated_uploads_remaining"],
|
||||
youtube_quota_seconds_until_reset=quota_stats["seconds_until_reset"],
|
||||
youtube_uploads_queued=queue_stats["queued"],
|
||||
youtube_uploads_failed=queue_stats["failed"],
|
||||
disposable_domains_count=blocklist_stats["disposable_domains_count"],
|
||||
blocked_emails_count=blocklist_stats["blocked_emails_count"],
|
||||
blocked_ips_count=blocklist_stats["blocked_ips_count"],
|
||||
@@ -426,3 +482,87 @@ async def remove_user_override(
|
||||
success=True,
|
||||
message=f"Override removed for user '{email}'"
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# YouTube Upload Queue Management Endpoints
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/youtube-queue", response_model=YouTubeQueueListResponse)
|
||||
async def get_youtube_queue(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Get YouTube upload queue entries and stats.
|
||||
|
||||
Returns all queue entries (any status) and aggregate statistics.
|
||||
"""
|
||||
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
|
||||
|
||||
queue_service = get_youtube_upload_queue_service()
|
||||
entries = queue_service.get_all_queue_entries(limit=50)
|
||||
stats = queue_service.get_queue_stats()
|
||||
|
||||
return YouTubeQueueListResponse(
|
||||
entries=[YouTubeQueueEntry(**entry) for entry in entries],
|
||||
stats=stats,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/youtube-queue/{job_id}/retry", response_model=SuccessResponse)
|
||||
async def retry_youtube_upload(
|
||||
job_id: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Manually retry a failed YouTube upload.
|
||||
|
||||
Resets the entry back to 'queued' status with 0 attempts.
|
||||
"""
|
||||
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
|
||||
|
||||
queue_service = get_youtube_upload_queue_service()
|
||||
|
||||
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}"
|
||||
)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"YouTube upload for job {job_id} queued for retry"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/youtube-queue/process", response_model=SuccessResponse)
|
||||
async def trigger_youtube_queue_processing(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Manually trigger YouTube upload queue processing.
|
||||
|
||||
Same as the scheduled processor but triggered from the admin dashboard.
|
||||
Runs in the background and returns immediately.
|
||||
"""
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue
|
||||
import asyncio
|
||||
|
||||
async def _process():
|
||||
try:
|
||||
result = await process_youtube_upload_queue()
|
||||
logger.info(f"Manual YouTube queue processing complete: {result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"Manual YouTube queue processing failed: {e}")
|
||||
|
||||
# Fire and forget
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
loop.create_task(_process())
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message="YouTube queue processing started in background"
|
||||
)
|
||||
@@ -22,7 +22,7 @@ from pathlib import Path
|
||||
from typing import Dict, Any, Set, Tuple
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
@@ -138,27 +138,40 @@ async def get_correction_data(
|
||||
}
|
||||
|
||||
# === Add instrumental data for combined review ===
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
transcoding = AudioTranscodingService(storage_service=storage)
|
||||
|
||||
# Get instrumental stem URLs
|
||||
stems = job.file_urls.get('stems', {})
|
||||
clean_url = stems.get('instrumental_clean')
|
||||
backing_url = stems.get('instrumental_with_backing')
|
||||
|
||||
# Build instrumental options with signed URLs
|
||||
# Build instrumental options with transcoded signed URLs (OGG Opus)
|
||||
instrumental_options = []
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
|
||||
signed_urls = {}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
signed_urls = dict(zip(url_tasks.keys(), results))
|
||||
|
||||
if clean_url:
|
||||
instrumental_options.append({
|
||||
"id": "clean",
|
||||
"label": "Clean Instrumental",
|
||||
"description": "No backing vocals - just the music",
|
||||
"audio_url": storage.generate_signed_url(clean_url, expiration_minutes=120),
|
||||
"audio_url": signed_urls['clean'],
|
||||
})
|
||||
if backing_url:
|
||||
instrumental_options.append({
|
||||
"id": "with_backing",
|
||||
"label": "Instrumental with Backing Vocals",
|
||||
"description": "Includes harmonies and background vocals",
|
||||
"audio_url": storage.generate_signed_url(backing_url, expiration_minutes=120),
|
||||
"audio_url": signed_urls['with_backing'],
|
||||
})
|
||||
|
||||
corrections_data['instrumental_options'] = instrumental_options
|
||||
@@ -213,49 +226,32 @@ async def get_audio_no_hash(
|
||||
|
||||
async def _stream_audio(job_id: str):
|
||||
"""
|
||||
Stream the audio file for playback in the review interface.
|
||||
Redirect to a signed GCS URL for audio playback in the review interface.
|
||||
|
||||
Serves transcoded OGG Opus (~3 MB) instead of raw FLAC (~35 MB).
|
||||
Falls back to FLAC if transcoded version is not available.
|
||||
"""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
if not audio_gcs_path:
|
||||
raise HTTPException(status_code=404, detail="Audio file not found")
|
||||
|
||||
# Download to temp file and stream
|
||||
|
||||
try:
|
||||
# Create temp file
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".flac") as tmp:
|
||||
tmp_path = tmp.name
|
||||
|
||||
storage.download_file(audio_gcs_path, tmp_path)
|
||||
|
||||
# Determine content type
|
||||
if audio_gcs_path.endswith('.flac'):
|
||||
media_type = "audio/flac"
|
||||
elif audio_gcs_path.endswith('.wav'):
|
||||
media_type = "audio/wav"
|
||||
elif audio_gcs_path.endswith('.mp3'):
|
||||
media_type = "audio/mpeg"
|
||||
else:
|
||||
media_type = "audio/mpeg"
|
||||
|
||||
logger.info(f"Job {job_id}: Streaming audio for review")
|
||||
|
||||
return FileResponse(
|
||||
tmp_path,
|
||||
media_type=media_type,
|
||||
filename=os.path.basename(audio_gcs_path),
|
||||
background=BackgroundTask(os.unlink, tmp_path),
|
||||
)
|
||||
|
||||
transcoding = AudioTranscodingService()
|
||||
signed_url = await transcoding.get_review_audio_url_async(audio_gcs_path, expiration_minutes=120)
|
||||
logger.info(f"Job {job_id}: Redirecting to signed URL for audio review")
|
||||
return RedirectResponse(url=signed_url, status_code=302)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error streaming audio: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error streaming audio: {str(e)}")
|
||||
logger.error(f"Job {job_id}: Error generating audio signed URL: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error serving audio: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{job_id}/complete")
|
||||
@@ -296,8 +292,9 @@ async def complete_review(
|
||||
)
|
||||
|
||||
valid_selections = ["clean", "with_backing"]
|
||||
# Also allow "custom" for user-provided instrumentals
|
||||
if job.existing_instrumental_gcs_path:
|
||||
# Allow "custom" for mute-region instrumentals or user-uploaded instrumentals
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
if job.existing_instrumental_gcs_path or stems.get("custom_instrumental"):
|
||||
valid_selections.append("custom")
|
||||
|
||||
if instrumental_selection not in valid_selections:
|
||||
@@ -735,17 +732,41 @@ async def get_preview_video(
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
async def submit_annotation(
|
||||
job_id: str,
|
||||
annotation: Dict[str, Any],
|
||||
payload: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Submit a correction annotation for ML training data.
|
||||
|
||||
For now, just log and acknowledge - full annotation support
|
||||
would require a database.
|
||||
Submit correction annotations for ML training data.
|
||||
|
||||
Accepts either a single annotation dict or {"annotations": [...]} batch.
|
||||
Stores to GCS at jobs/{job_id}/lyrics/annotations.json.
|
||||
"""
|
||||
logger.info(f"Job {job_id}: Annotation submitted (logged but not stored)")
|
||||
return {"status": "success", "annotation_id": "stub"}
|
||||
annotations = payload.get("annotations", [payload]) if isinstance(payload, dict) else [payload]
|
||||
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
|
||||
|
||||
# Merge with any existing annotations
|
||||
existing: list = []
|
||||
try:
|
||||
existing_data = storage.download_json(gcs_path)
|
||||
if isinstance(existing_data, list):
|
||||
existing = existing_data
|
||||
elif isinstance(existing_data, dict) and "annotations" in existing_data:
|
||||
existing = existing_data["annotations"]
|
||||
except Exception:
|
||||
pass # No existing file, start fresh
|
||||
|
||||
merged = existing + annotations
|
||||
storage.upload_json(gcs_path, {"annotations": merged})
|
||||
|
||||
logger.info(f"Job {job_id}: {len(annotations)} annotation(s) saved ({len(merged)} total)")
|
||||
return {"status": "success", "saved_count": len(annotations), "total_count": len(merged)}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error saving annotations: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{job_id}/v1/annotations/stats")
|
||||
@@ -754,11 +775,18 @@ async def get_annotation_stats(
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Get annotation statistics."""
|
||||
return {
|
||||
"total_annotations": 0,
|
||||
"by_type": {},
|
||||
"message": "Annotation stats not yet implemented"
|
||||
}
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
|
||||
data = storage.download_json(gcs_path)
|
||||
annotations = data.get("annotations", []) if isinstance(data, dict) else data
|
||||
by_type: Dict[str, int] = {}
|
||||
for a in annotations:
|
||||
atype = a.get("annotation_type", "unknown")
|
||||
by_type[atype] = by_type.get(atype, 0) + 1
|
||||
return {"total_annotations": len(annotations), "by_type": by_type}
|
||||
except Exception:
|
||||
return {"total_annotations": 0, "by_type": {}}
|
||||
|
||||
|
||||
@router.get("/{job_id}/instrumental-analysis")
|
||||
@@ -785,23 +813,29 @@ async def get_instrumental_analysis(
|
||||
backing_analysis = job.state_data.get('backing_vocals_analysis', {})
|
||||
|
||||
# Get stem URLs
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
transcoding = AudioTranscodingService(storage_service=storage)
|
||||
|
||||
stems = job.file_urls.get('stems', {})
|
||||
clean_url = stems.get('instrumental_clean')
|
||||
backing_url = stems.get('instrumental_with_backing')
|
||||
|
||||
# Build audio URLs with signed access
|
||||
audio_urls = {}
|
||||
if clean_url:
|
||||
audio_urls['clean'] = storage.generate_signed_url(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
audio_urls['with_backing'] = storage.generate_signed_url(backing_url, expiration_minutes=120)
|
||||
if job.input_media_gcs_path:
|
||||
audio_urls['original'] = storage.generate_signed_url(job.input_media_gcs_path, expiration_minutes=120)
|
||||
|
||||
# Check for backing vocals stem for playback
|
||||
backing_vocals_path = stems.get('backing_vocals')
|
||||
|
||||
# Build audio URLs with transcoded signed access (OGG Opus, parallel)
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
if job.input_media_gcs_path:
|
||||
url_tasks['original'] = transcoding.get_review_audio_url_async(job.input_media_gcs_path, expiration_minutes=120)
|
||||
if backing_vocals_path:
|
||||
audio_urls['backing_vocals'] = storage.generate_signed_url(backing_vocals_path, expiration_minutes=120)
|
||||
url_tasks['backing_vocals'] = transcoding.get_review_audio_url_async(backing_vocals_path, expiration_minutes=120)
|
||||
|
||||
audio_urls = {}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
audio_urls = dict(zip(url_tasks.keys(), results))
|
||||
|
||||
# Format response to match InstrumentalAnalysis type
|
||||
return {
|
||||
|
||||
+210
-4
@@ -48,6 +48,10 @@ from backend.models.user import (
|
||||
BetaFeedbackRequest,
|
||||
BetaFeedbackResponse,
|
||||
BetaTesterFeedback,
|
||||
UserFeedback,
|
||||
UserFeedbackRequest,
|
||||
UserFeedbackResponse,
|
||||
FeedbackEligibilityResponse,
|
||||
)
|
||||
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
|
||||
from backend.services.email_service import get_email_service, EmailService
|
||||
@@ -182,13 +186,23 @@ async def send_magic_link(
|
||||
tenant_id=tenant_id
|
||||
)
|
||||
|
||||
# Get tenant-specific sender email
|
||||
# Get tenant-specific email configuration
|
||||
sender_email = None
|
||||
tenant_frontend_url = None
|
||||
tenant_name = None
|
||||
if tenant_config:
|
||||
sender_email = tenant_config.get_sender_email()
|
||||
tenant_frontend_url = tenant_config.get_frontend_url()
|
||||
tenant_name = tenant_config.name
|
||||
|
||||
# Send email (with tenant-specific sender if configured)
|
||||
sent = email_service.send_magic_link(email, magic_link.token, sender_email=sender_email)
|
||||
# Send email (with tenant-specific sender, URL, and name if configured)
|
||||
sent = email_service.send_magic_link(
|
||||
email,
|
||||
magic_link.token,
|
||||
sender_email=sender_email,
|
||||
tenant_frontend_url=tenant_frontend_url,
|
||||
tenant_name=tenant_name,
|
||||
)
|
||||
|
||||
if not sent:
|
||||
logger.error(f"Failed to send magic link email to {email}")
|
||||
@@ -265,11 +279,21 @@ async def verify_magic_link(
|
||||
tenant_id=user.tenant_id,
|
||||
)
|
||||
|
||||
# Resolve tenant subdomain for cross-domain redirect safety
|
||||
tenant_subdomain = None
|
||||
if magic_link_tenant_id:
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
tenant_service = get_tenant_service()
|
||||
tenant_cfg = tenant_service.get_tenant_config(magic_link_tenant_id)
|
||||
if tenant_cfg:
|
||||
tenant_subdomain = tenant_cfg.subdomain
|
||||
|
||||
return VerifyMagicLinkResponse(
|
||||
status="success",
|
||||
session_token=session.token,
|
||||
user=user_public,
|
||||
message="Successfully signed in"
|
||||
message="Successfully signed in",
|
||||
tenant_subdomain=tenant_subdomain,
|
||||
)
|
||||
|
||||
|
||||
@@ -321,6 +345,10 @@ async def get_current_user(
|
||||
if auth_result.is_valid and auth_result.user_email:
|
||||
# Get or create user record for the authenticated email
|
||||
user = user_service.get_or_create_user(auth_result.user_email)
|
||||
feedback_eligible = (
|
||||
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,
|
||||
@@ -328,6 +356,7 @@ async def get_current_user(
|
||||
display_name=user.display_name,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
feedback_eligible=feedback_eligible,
|
||||
)
|
||||
return UserProfileResponse(user=user_public, has_session=True)
|
||||
|
||||
@@ -337,6 +366,10 @@ async def get_current_user(
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
feedback_eligible = (
|
||||
user.total_jobs_completed >= 2
|
||||
and not user.has_submitted_feedback
|
||||
)
|
||||
user_public = UserPublic(
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
@@ -344,6 +377,7 @@ async def get_current_user(
|
||||
display_name=user.display_name,
|
||||
total_jobs_created=user.total_jobs_created,
|
||||
total_jobs_completed=user.total_jobs_completed,
|
||||
feedback_eligible=feedback_eligible,
|
||||
)
|
||||
|
||||
return UserProfileResponse(user=user_public, has_session=True)
|
||||
@@ -1130,6 +1164,153 @@ async def get_feedback_form_data(
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# User Feedback-for-Credits Endpoints
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
|
||||
async def check_feedback_eligibility(
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Check if the current user is eligible to submit feedback for credits.
|
||||
|
||||
Eligible if: total_jobs_completed >= 2 AND has not already submitted feedback.
|
||||
"""
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
# Try auth service first (admin tokens, auth_tokens)
|
||||
from backend.services.auth_service import get_auth_service
|
||||
auth_service = get_auth_service()
|
||||
auth_result = auth_service.validate_token_full(token)
|
||||
|
||||
user = None
|
||||
if auth_result.is_valid and auth_result.user_email:
|
||||
user = user_service.get_or_create_user(auth_result.user_email)
|
||||
else:
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
eligible = user.total_jobs_completed >= 2 and not user.has_submitted_feedback
|
||||
|
||||
return FeedbackEligibilityResponse(
|
||||
eligible=eligible,
|
||||
has_submitted=user.has_submitted_feedback,
|
||||
jobs_completed=user.total_jobs_completed,
|
||||
credits_reward=2,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/feedback", response_model=UserFeedbackResponse)
|
||||
async def submit_user_feedback(
|
||||
request: UserFeedbackRequest,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Submit product feedback to earn 2 free credits.
|
||||
|
||||
Requires authentication. Users must have completed 2+ jobs and
|
||||
not have already submitted feedback. At least one text field
|
||||
must have >50 characters.
|
||||
"""
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization
|
||||
|
||||
# Try auth service first (admin tokens, auth_tokens)
|
||||
from backend.services.auth_service import get_auth_service
|
||||
auth_service = get_auth_service()
|
||||
auth_result = auth_service.validate_token_full(token)
|
||||
|
||||
user = None
|
||||
if auth_result.is_valid and auth_result.user_email:
|
||||
user = user_service.get_or_create_user(auth_result.user_email)
|
||||
else:
|
||||
valid, user, message = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail=message)
|
||||
|
||||
# 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."
|
||||
)
|
||||
|
||||
# Check if already submitted
|
||||
if user.has_submitted_feedback:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="You have already submitted feedback. Thank you!"
|
||||
)
|
||||
|
||||
# Validate: at least one text field has >50 characters
|
||||
has_detailed_feedback = (
|
||||
(request.what_went_well and len(request.what_went_well) > 50) or
|
||||
(request.what_could_improve and len(request.what_could_improve) > 50) or
|
||||
(request.additional_comments and len(request.additional_comments) > 50)
|
||||
)
|
||||
if not has_detailed_feedback:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Please provide detailed feedback in at least one text field (more than 50 characters)."
|
||||
)
|
||||
|
||||
# Save feedback to Firestore
|
||||
import uuid
|
||||
|
||||
feedback = UserFeedback(
|
||||
id=str(uuid.uuid4()),
|
||||
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,
|
||||
submitted_via="web",
|
||||
)
|
||||
|
||||
user_service.db.collection("user_feedback").document(feedback.id).set(
|
||||
feedback.model_dump(mode='json')
|
||||
)
|
||||
|
||||
# Mark user as having submitted feedback
|
||||
user_service.update_user(
|
||||
user.email,
|
||||
has_submitted_feedback=True,
|
||||
)
|
||||
|
||||
# Grant 2 credits
|
||||
credits_granted = 2
|
||||
user_service.add_credits(
|
||||
email=user.email,
|
||||
amount=credits_granted,
|
||||
reason="feedback_bonus",
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"User feedback received from {_mask_email(user.email)}, "
|
||||
f"credits granted: {credits_granted}"
|
||||
)
|
||||
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message=f"Thank you for your feedback! You earned {credits_granted} free credits.",
|
||||
credits_granted=credits_granted,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Endpoints
|
||||
# =============================================================================
|
||||
@@ -1410,6 +1591,31 @@ async def enable_user(
|
||||
return {"status": "success", "message": f"User {email} has been enabled"}
|
||||
|
||||
|
||||
@router.delete("/admin/users/{email}")
|
||||
async def delete_user(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Permanently delete a user and all associated data (admin only).
|
||||
|
||||
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"
|
||||
|
||||
try:
|
||||
success = user_service.delete_user(email, admin_email=admin_id)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
return {"status": "success", "message": f"User {email} has been deleted"}
|
||||
|
||||
|
||||
@router.post("/admin/users/{email}/role")
|
||||
async def set_user_role(
|
||||
email: str,
|
||||
|
||||
+23
-1
@@ -83,6 +83,9 @@ class Settings(BaseSettings):
|
||||
# Requires use_gce_encoding to be enabled and the GCE worker to support /encode-preview endpoint.
|
||||
use_gce_preview_encoding: bool = os.getenv("USE_GCE_PREVIEW_ENCODING", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
# Karaoke-Decide catalog API (for song/artist autocomplete)
|
||||
karaoke_decide_api_url: str = os.getenv("KARAOKE_DECIDE_API_URL", "https://decide.nomadkaraoke.com")
|
||||
|
||||
# Storage paths
|
||||
temp_dir: str = os.getenv("TEMP_DIR", "/tmp/karaoke-gen")
|
||||
|
||||
@@ -97,7 +100,13 @@ class Settings(BaseSettings):
|
||||
# This is required for torrent downloads since Cloud Run doesn't support BitTorrent.
|
||||
flacfetch_api_url: Optional[str] = os.getenv("FLACFETCH_API_URL") # e.g., http://10.0.0.5:8080
|
||||
flacfetch_api_key: Optional[str] = os.getenv("FLACFETCH_API_KEY")
|
||||
|
||||
|
||||
# Flacfetch client retry settings
|
||||
# Retries help handle transient network failures when calling the flacfetch service
|
||||
flacfetch_retry_max_attempts: int = int(os.getenv("FLACFETCH_RETRY_MAX_ATTEMPTS", "9")) # Total attempts (1 initial + 8 retries)
|
||||
flacfetch_retry_min_wait: float = float(os.getenv("FLACFETCH_RETRY_MIN_WAIT", "10.0")) # seconds
|
||||
flacfetch_retry_max_wait: float = float(os.getenv("FLACFETCH_RETRY_MAX_WAIT", "60.0")) # seconds
|
||||
|
||||
# Default distribution settings (can be overridden per-request)
|
||||
default_dropbox_path: Optional[str] = os.getenv("DEFAULT_DROPBOX_PATH")
|
||||
default_gdrive_folder_id: Optional[str] = os.getenv("DEFAULT_GDRIVE_FOLDER_ID")
|
||||
@@ -110,13 +119,26 @@ class Settings(BaseSettings):
|
||||
default_enable_youtube_upload: bool = os.getenv("DEFAULT_ENABLE_YOUTUBE_UPLOAD", "false").lower() in ("true", "1", "yes")
|
||||
default_brand_prefix: Optional[str] = os.getenv("DEFAULT_BRAND_PREFIX")
|
||||
|
||||
# Private (non-published) track distribution settings
|
||||
default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")
|
||||
default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")
|
||||
|
||||
# Rate Limiting Configuration
|
||||
# Enable/disable rate limiting system-wide (useful for development)
|
||||
enable_rate_limiting: bool = os.getenv("ENABLE_RATE_LIMITING", "true").lower() in ("true", "1", "yes")
|
||||
# Maximum jobs a user can create per day (0 = unlimited)
|
||||
rate_limit_jobs_per_day: int = int(os.getenv("RATE_LIMIT_JOBS_PER_DAY", "5"))
|
||||
# Maximum YouTube uploads system-wide per day (0 = unlimited)
|
||||
# DEPRECATED: Use youtube_quota_daily_limit instead. Kept for backward compatibility.
|
||||
rate_limit_youtube_uploads_per_day: int = int(os.getenv("RATE_LIMIT_YOUTUBE_UPLOADS_PER_DAY", "10"))
|
||||
|
||||
# YouTube Data API v3 Quota Configuration
|
||||
# Daily quota limit (YouTube grants 10,000 units/day by default)
|
||||
youtube_quota_daily_limit: int = int(os.getenv("YOUTUBE_QUOTA_DAILY_LIMIT", "10000"))
|
||||
# Estimated units consumed per upload (videos.insert=100 + search.list=100 + thumbnails.set=50 + buffer)
|
||||
youtube_quota_upload_cost: int = int(os.getenv("YOUTUBE_QUOTA_UPLOAD_COST", "300"))
|
||||
# Safety margin to reserve (avoid hitting exact limit)
|
||||
youtube_quota_safety_margin: int = int(os.getenv("YOUTUBE_QUOTA_SAFETY_MARGIN", "500"))
|
||||
# Maximum beta enrollments from same IP per day (0 = unlimited)
|
||||
rate_limit_beta_ip_per_day: int = int(os.getenv("RATE_LIMIT_BETA_IP_PER_DAY", "1"))
|
||||
|
||||
|
||||
@@ -66,6 +66,28 @@ class IPBlockedError(Exception):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class InsufficientCreditsError(Exception):
|
||||
"""
|
||||
Raised when a user attempts to create a job without sufficient credits.
|
||||
|
||||
Attributes:
|
||||
message: Human-readable error message
|
||||
credits_available: Number of credits the user currently has
|
||||
credits_required: Number of credits required (always 1 for now)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
credits_available: int = 0,
|
||||
credits_required: int = 1
|
||||
):
|
||||
self.message = message
|
||||
self.credits_available = credits_available
|
||||
self.credits_required = credits_required
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class InvalidStateTransitionError(Exception):
|
||||
"""
|
||||
Raised when an invalid job state transition is attempted.
|
||||
|
||||
+17
-2
@@ -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
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog
|
||||
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
|
||||
@@ -161,13 +161,14 @@ app.include_router(users.router, prefix="/api") # User auth, credits, and Strip
|
||||
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
|
||||
app.include_router(catalog.router, prefix="/api") # Catalog proxy for song/artist autocomplete
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
|
||||
|
||||
# Exception handler for rate limiting
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from backend.exceptions import RateLimitExceededError
|
||||
from backend.exceptions import RateLimitExceededError, InsufficientCreditsError
|
||||
|
||||
|
||||
@app.exception_handler(RateLimitExceededError)
|
||||
@@ -187,6 +188,20 @@ async def rate_limit_exception_handler(request: Request, exc: RateLimitExceededE
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(InsufficientCreditsError)
|
||||
async def insufficient_credits_exception_handler(request: Request, exc: InsufficientCreditsError):
|
||||
"""Handle insufficient credits errors with 402 Payment Required status."""
|
||||
return JSONResponse(
|
||||
status_code=402,
|
||||
content={
|
||||
"detail": exc.message,
|
||||
"credits_available": exc.credits_available,
|
||||
"credits_required": exc.credits_required,
|
||||
"buy_url": "/#pricing",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
"""Root endpoint."""
|
||||
|
||||
+17
-3
@@ -93,8 +93,9 @@ class JobStatus(str, Enum):
|
||||
|
||||
# Valid state transitions
|
||||
STATE_TRANSITIONS = {
|
||||
# PENDING can go to DOWNLOADING (file upload) or SEARCHING_AUDIO (artist+title search)
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
# PENDING can go to DOWNLOADING (file upload), SEARCHING_AUDIO (artist+title search),
|
||||
# or DOWNLOADING_AUDIO (create-from-search where audio is pre-selected)
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
|
||||
# Audio search flow (for artist+title search mode)
|
||||
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
|
||||
@@ -205,7 +206,14 @@ class Job(BaseModel):
|
||||
title: Optional[str] = None
|
||||
filename: Optional[str] = None # Original uploaded filename
|
||||
input_media_gcs_path: Optional[str] = None # GCS path to uploaded file
|
||||
|
||||
|
||||
# Audio source tracking (for retry capability)
|
||||
audio_source_type: Optional[str] = None # Source type: 'audio_search', 'youtube_url', 'file_upload'
|
||||
source_name: Optional[str] = None # Provider name (RED, OPS, YouTube, Spotify) - for audio_search
|
||||
source_id: Optional[str] = None # Source-specific ID (torrent ID, video ID, track ID) - for audio_search
|
||||
target_file: Optional[str] = None # For torrents, specific file to extract - for audio_search
|
||||
download_url: Optional[str] = None # Direct download URL if available - for audio_search
|
||||
|
||||
# User preferences
|
||||
enable_cdg: bool = False # Generate CDG+MP3 package (requires style config)
|
||||
enable_txt: bool = False # Generate TXT+MP3 package (requires style config)
|
||||
@@ -292,6 +300,9 @@ class Job(BaseModel):
|
||||
customer_email: Optional[str] = None # Customer email for final delivery (job owned by admin during processing)
|
||||
customer_notes: Optional[str] = None # Notes provided by customer with their order
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
|
||||
|
||||
# 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
|
||||
@@ -499,6 +510,9 @@ class JobCreate(BaseModel):
|
||||
customer_email: Optional[str] = None # Customer email for final delivery (job owned by admin during processing)
|
||||
customer_notes: Optional[str] = None # Notes provided by customer with their order
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
|
||||
|
||||
# Request metadata (set by API endpoint from request headers)
|
||||
request_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
|
||||
@@ -10,7 +10,7 @@ class URLSubmissionRequest(BaseModel):
|
||||
url: HttpUrl
|
||||
artist: Optional[str] = None # Auto-detected if not provided
|
||||
title: Optional[str] = None # Auto-detected if not provided
|
||||
|
||||
|
||||
# Optional preferences
|
||||
enable_cdg: bool = False # Requires style config
|
||||
enable_txt: bool = False # Requires style config
|
||||
@@ -18,6 +18,7 @@ class URLSubmissionRequest(BaseModel):
|
||||
youtube_description: Optional[str] = None
|
||||
webhook_url: Optional[str] = None
|
||||
user_email: Optional[str] = None
|
||||
is_private: Optional[bool] = None # Private (non-published) track mode
|
||||
|
||||
|
||||
class UploadSubmissionRequest(BaseModel):
|
||||
|
||||
@@ -139,6 +139,10 @@ class TenantConfig(BaseModel):
|
||||
created_at: Optional[datetime] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
def get_frontend_url(self) -> str:
|
||||
"""Get the frontend URL for this tenant's portal."""
|
||||
return f"https://{self.subdomain}"
|
||||
|
||||
def get_sender_email(self) -> str:
|
||||
"""Get the email sender address for this tenant."""
|
||||
if self.auth.sender_email:
|
||||
|
||||
@@ -104,6 +104,9 @@ class User(BaseModel):
|
||||
# Users can subscribe from multiple devices/browsers
|
||||
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
|
||||
|
||||
# Feedback-for-credits program
|
||||
has_submitted_feedback: bool = False
|
||||
|
||||
|
||||
class MagicLinkToken(BaseModel):
|
||||
"""
|
||||
@@ -174,6 +177,7 @@ class VerifyMagicLinkResponse(BaseModel):
|
||||
session_token: str
|
||||
user: "UserPublic"
|
||||
message: str
|
||||
tenant_subdomain: Optional[str] = None
|
||||
|
||||
|
||||
class UserPublic(BaseModel):
|
||||
@@ -185,6 +189,7 @@ class UserPublic(BaseModel):
|
||||
total_jobs_created: int = 0
|
||||
total_jobs_completed: int = 0
|
||||
tenant_id: Optional[str] = None
|
||||
feedback_eligible: bool = False
|
||||
|
||||
|
||||
class AddCreditsRequest(BaseModel):
|
||||
@@ -288,3 +293,70 @@ class BetaFeedbackResponse(BaseModel):
|
||||
status: str
|
||||
message: str
|
||||
bonus_credits: int = 0 # Bonus credits for great feedback
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# User Feedback-for-Credits Models
|
||||
# ============================================================================
|
||||
|
||||
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.
|
||||
"""
|
||||
id: str
|
||||
user_email: str
|
||||
|
||||
# Ratings (1-5 scale)
|
||||
overall_rating: int = Field(ge=1, le=5)
|
||||
ease_of_use_rating: int = Field(ge=1, le=5)
|
||||
lyrics_accuracy_rating: int = Field(ge=1, le=5)
|
||||
correction_experience_rating: int = Field(ge=1, le=5)
|
||||
|
||||
# Open-ended feedback
|
||||
what_went_well: Optional[str] = None
|
||||
what_could_improve: Optional[str] = None
|
||||
additional_comments: Optional[str] = None
|
||||
|
||||
# Would they recommend / use again?
|
||||
would_recommend: bool = True
|
||||
would_use_again: bool = True
|
||||
|
||||
# Metadata
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
submitted_via: str = "web"
|
||||
|
||||
|
||||
class UserFeedbackRequest(BaseModel):
|
||||
"""Request to submit user feedback for credits."""
|
||||
# Ratings (1-5 scale)
|
||||
overall_rating: int = Field(ge=1, le=5)
|
||||
ease_of_use_rating: int = Field(ge=1, le=5)
|
||||
lyrics_accuracy_rating: int = Field(ge=1, le=5)
|
||||
correction_experience_rating: int = Field(ge=1, le=5)
|
||||
|
||||
# Open-ended feedback
|
||||
what_went_well: Optional[str] = None
|
||||
what_could_improve: Optional[str] = None
|
||||
additional_comments: Optional[str] = None
|
||||
|
||||
# Would they recommend / use again?
|
||||
would_recommend: bool = True
|
||||
would_use_again: bool = True
|
||||
|
||||
|
||||
class UserFeedbackResponse(BaseModel):
|
||||
"""Response after submitting user feedback."""
|
||||
status: str
|
||||
message: str
|
||||
credits_granted: int = 0
|
||||
|
||||
|
||||
class FeedbackEligibilityResponse(BaseModel):
|
||||
"""Response for feedback eligibility check."""
|
||||
eligible: bool
|
||||
has_submitted: bool
|
||||
jobs_completed: int
|
||||
credits_reward: int = 2
|
||||
@@ -64,7 +64,7 @@ except ImportError:
|
||||
FINALIZING = "finalizing"
|
||||
|
||||
STATE_TRANSITIONS = {
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
|
||||
JobStatus.AWAITING_AUDIO_SELECTION: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
|
||||
|
||||
@@ -612,13 +612,13 @@ class AudioSearchService:
|
||||
async def search_async(self, artist: str, title: str) -> List[AudioSearchResult]:
|
||||
"""
|
||||
Async version of search for use in async routes.
|
||||
|
||||
Note: Currently wraps sync search in executor. Future optimization
|
||||
could make this fully async.
|
||||
|
||||
Runs the sync search in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(None, self.search, artist, title)
|
||||
|
||||
|
||||
async def download_async(
|
||||
self,
|
||||
result_index: int,
|
||||
@@ -630,10 +630,10 @@ class AudioSearchService:
|
||||
"""
|
||||
Async version of download for use in async routes.
|
||||
|
||||
Note: Currently wraps sync download in executor. Future optimization
|
||||
could make this fully async.
|
||||
Runs the sync download in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download(result_index, output_dir, output_filename, gcs_path, remote_search_id)
|
||||
@@ -651,8 +651,11 @@ class AudioSearchService:
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Async version of download_by_id for use in async routes.
|
||||
|
||||
Runs the sync download_by_id in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download_by_id(
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
Audio transcoding service for review UI optimization.
|
||||
|
||||
Transcodes FLAC audio files to OGG Opus for efficient browser playback.
|
||||
Original FLAC files are never modified — transcoded versions are cached
|
||||
in GCS at jobs/{job_id}/review-audio/{filename}.ogg.
|
||||
|
||||
Eager transcoding: called from screens_worker before AWAITING_REVIEW
|
||||
so all files are cached before the user opens the review UI.
|
||||
Falls back to original FLAC signed URLs if transcoded version is missing.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AudioTranscodingService:
|
||||
"""
|
||||
Transcodes audio files to OGG Opus and caches them in GCS.
|
||||
|
||||
Used by the review UI to serve ~3 MB OGG files instead of 35+ MB FLACs.
|
||||
"""
|
||||
|
||||
def __init__(self, storage_service: Optional[StorageService] = None):
|
||||
self.storage = storage_service or StorageService()
|
||||
|
||||
def _get_cache_path(self, source_gcs_path: str) -> str:
|
||||
"""
|
||||
Derive the cache path for a transcoded file.
|
||||
|
||||
Examples:
|
||||
jobs/abc123/input/song.flac -> jobs/abc123/review-audio/song.ogg
|
||||
jobs/abc123/stems/instrumental_clean.flac -> jobs/abc123/review-audio/instrumental_clean.ogg
|
||||
"""
|
||||
parts = Path(source_gcs_path).parts
|
||||
# Find "jobs/{job_id}" prefix
|
||||
try:
|
||||
jobs_idx = list(parts).index("jobs")
|
||||
job_id = parts[jobs_idx + 1]
|
||||
except (ValueError, IndexError):
|
||||
# Fallback: use a hash of the full path to avoid collisions
|
||||
job_id = "_" + hashlib.sha256(source_gcs_path.encode()).hexdigest()[:12]
|
||||
|
||||
filename = Path(source_gcs_path).stem + ".ogg"
|
||||
return f"jobs/{job_id}/review-audio/{filename}"
|
||||
|
||||
def _transcode_and_upload(self, source_gcs_path: str, cache_path: str) -> str:
|
||||
"""
|
||||
Download FLAC from GCS, transcode to OGG Opus, upload to cache path.
|
||||
|
||||
Returns the cache GCS path on success.
|
||||
Raises on failure.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_input = os.path.join(temp_dir, "input.flac")
|
||||
local_output = os.path.join(temp_dir, "output.ogg")
|
||||
|
||||
# Download source
|
||||
self.storage.download_file(source_gcs_path, local_input)
|
||||
|
||||
# Transcode: FLAC -> OGG Opus 128kbps
|
||||
cmd = [
|
||||
"ffmpeg", "-hide_banner", "-loglevel", "error",
|
||||
"-y",
|
||||
"-i", local_input,
|
||||
"-c:a", "libopus",
|
||||
"-b:a", "128k",
|
||||
"-vn",
|
||||
local_output,
|
||||
]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(
|
||||
f"ffmpeg transcoding failed (exit {result.returncode}): {result.stderr}"
|
||||
)
|
||||
|
||||
# Upload transcoded file
|
||||
self.storage.upload_file(local_output, cache_path)
|
||||
|
||||
return cache_path
|
||||
|
||||
def transcode_if_needed(self, source_gcs_path: str) -> str:
|
||||
"""
|
||||
Return the GCS path of the transcoded OGG file, transcoding if not cached.
|
||||
|
||||
Returns the cache path (always an OGG file in review-audio/).
|
||||
Raises if transcoding fails.
|
||||
"""
|
||||
cache_path = self._get_cache_path(source_gcs_path)
|
||||
|
||||
if self.storage.file_exists(cache_path):
|
||||
logger.debug(f"Cache hit: {cache_path}")
|
||||
return cache_path
|
||||
|
||||
logger.info(f"Cache miss, transcoding: {source_gcs_path} -> {cache_path}")
|
||||
return self._transcode_and_upload(source_gcs_path, cache_path)
|
||||
|
||||
def get_review_audio_url(
|
||||
self, source_gcs_path: str, expiration_minutes: int = 120
|
||||
) -> str:
|
||||
"""
|
||||
Get a signed URL for the transcoded audio, falling back to original FLAC.
|
||||
"""
|
||||
try:
|
||||
cache_path = self.transcode_if_needed(source_gcs_path)
|
||||
return self.storage.generate_signed_url(cache_path, expiration_minutes)
|
||||
except Exception as e:
|
||||
# Source may be deleted but cache from earlier transcode persists
|
||||
try:
|
||||
cache_path = self._get_cache_path(source_gcs_path)
|
||||
if self.storage.file_exists(cache_path):
|
||||
logger.info(f"Source gone but cache exists, serving: {cache_path}")
|
||||
return self.storage.generate_signed_url(cache_path, expiration_minutes)
|
||||
except Exception:
|
||||
pass # Fall through to FLAC fallback below
|
||||
logger.warning(
|
||||
f"Transcoding failed for {source_gcs_path}, falling back to FLAC: {e}"
|
||||
)
|
||||
return self.storage.generate_signed_url(source_gcs_path, expiration_minutes)
|
||||
|
||||
async def get_review_audio_url_async(
|
||||
self, source_gcs_path: str, expiration_minutes: int = 120
|
||||
) -> str:
|
||||
"""Async wrapper around get_review_audio_url via asyncio.to_thread."""
|
||||
return await asyncio.to_thread(
|
||||
self.get_review_audio_url, source_gcs_path, expiration_minutes
|
||||
)
|
||||
|
||||
def prepare_review_audio_for_job(self, job) -> list[str]:
|
||||
"""
|
||||
Transcode all review audio files for a job (eager transcoding).
|
||||
|
||||
Called from screens_worker before AWAITING_REVIEW transition
|
||||
and from the admin backfill endpoint.
|
||||
|
||||
Returns list of cache paths that were transcoded.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
transcoded = []
|
||||
|
||||
# Collect all audio paths to transcode
|
||||
paths_to_transcode = []
|
||||
|
||||
# Main input audio
|
||||
if job.input_media_gcs_path:
|
||||
paths_to_transcode.append(("input", job.input_media_gcs_path))
|
||||
|
||||
# Stems
|
||||
stems = job.file_urls.get("stems", {})
|
||||
for stem_key in ["instrumental_clean", "instrumental_with_backing", "backing_vocals"]:
|
||||
path = stems.get(stem_key)
|
||||
if path:
|
||||
paths_to_transcode.append((stem_key, path))
|
||||
|
||||
for label, source_path in paths_to_transcode:
|
||||
try:
|
||||
cache_path = self.transcode_if_needed(source_path)
|
||||
transcoded.append(cache_path)
|
||||
logger.info(f"[{job_id}] Transcoded {label}: {cache_path}")
|
||||
except Exception as e:
|
||||
# Non-fatal: review UI will fall back to FLAC
|
||||
logger.warning(
|
||||
f"[{job_id}] Failed to transcode {label} ({source_path}): {e}"
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"[{job_id}] Review audio preparation complete: "
|
||||
f"{len(transcoded)}/{len(paths_to_transcode)} files transcoded"
|
||||
)
|
||||
return transcoded
|
||||
@@ -49,6 +49,7 @@ class AuthResult:
|
||||
user_email: Optional[str] = None # Email if authenticated via session/API key
|
||||
is_admin: bool = False # True if admin token or admin email domain
|
||||
api_key_id: Optional[str] = None # API key ID if authenticated via API key
|
||||
tenant_id: Optional[str] = None # Tenant scope from token or session
|
||||
|
||||
def __iter__(self):
|
||||
"""Allow unpacking as tuple for backward compatibility."""
|
||||
@@ -284,6 +285,7 @@ class AuthService:
|
||||
# All auth_tokens must have an associated user_email for job ownership
|
||||
token_user_email = token_data.get("user_email")
|
||||
api_key_id = token_data.get("api_key_id")
|
||||
token_tenant_id = token_data.get("tenant_id")
|
||||
|
||||
# Require user_email on all auth_tokens (no anonymous token auth)
|
||||
if not token_user_email:
|
||||
@@ -307,7 +309,8 @@ class AuthService:
|
||||
message="Unlimited access granted",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
# LIMITED tokens: check usage count
|
||||
@@ -320,7 +323,8 @@ class AuthService:
|
||||
message="Limited token with unlimited uses",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
current_uses = token_data.get("usage_count", 0)
|
||||
@@ -333,7 +337,8 @@ class AuthService:
|
||||
remaining_uses=0,
|
||||
message="Token usage limit exceeded",
|
||||
user_email=token_user_email,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -343,7 +348,8 @@ class AuthService:
|
||||
message=f"Limited token: {remaining} uses remaining",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
# STRIPE tokens: check expiration and usage
|
||||
@@ -357,7 +363,8 @@ class AuthService:
|
||||
remaining_uses=0,
|
||||
message="Token has expired",
|
||||
user_email=token_user_email,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
if max_uses > 0:
|
||||
@@ -371,7 +378,8 @@ class AuthService:
|
||||
remaining_uses=0,
|
||||
message="Token usage limit exceeded",
|
||||
user_email=token_user_email,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -381,7 +389,8 @@ class AuthService:
|
||||
message=f"Stripe token: {remaining} uses remaining",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -391,7 +400,8 @@ class AuthService:
|
||||
message="Stripe access granted",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
# API_KEY tokens
|
||||
@@ -406,7 +416,8 @@ class AuthService:
|
||||
remaining_uses=0,
|
||||
message="API key usage limit exceeded",
|
||||
user_email=token_user_email,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
@@ -415,7 +426,8 @@ class AuthService:
|
||||
message=f"API key valid: {remaining} uses remaining",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -425,7 +437,8 @@ class AuthService:
|
||||
message="API key access granted",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -437,10 +450,11 @@ class AuthService:
|
||||
|
||||
def increment_token_usage(self, token: str, job_id: str) -> bool:
|
||||
"""
|
||||
Increment usage count for a token and track the job.
|
||||
Increment usage count for an auth_token and track the job.
|
||||
|
||||
For session tokens (magic link auth), this deducts a credit from the user.
|
||||
For auth_tokens, this increments the usage count.
|
||||
Note: Credit deduction for session-based users is handled in
|
||||
JobManager.create_job(), not here. This method only tracks usage
|
||||
for legacy auth_tokens stored in Firestore.
|
||||
|
||||
Args:
|
||||
token: The access token
|
||||
@@ -465,32 +479,11 @@ class AuthService:
|
||||
if token in self.admin_tokens:
|
||||
return True
|
||||
|
||||
# Check if this is a session token (STRIPE type from validate_token means it's a session)
|
||||
# Session tokens are not in auth_tokens collection
|
||||
# Only increment usage for auth_tokens in Firestore
|
||||
# Session tokens (magic link auth) have credits managed by JobManager.create_job()
|
||||
token_data = self.firestore.get_token(token)
|
||||
|
||||
if not token_data:
|
||||
# This is a session token - deduct credit from user
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
|
||||
# Get the user email from the session
|
||||
is_valid, user, _ = user_service.validate_session(token)
|
||||
if not is_valid or not user:
|
||||
logger.error(f"Session token validation failed during usage increment")
|
||||
return False
|
||||
|
||||
# Deduct one credit
|
||||
success, new_balance, deduct_message = user_service.deduct_credit(
|
||||
user.email, job_id, reason="job_creation"
|
||||
)
|
||||
|
||||
if success:
|
||||
logger.info(f"Deducted credit for user {user.email} (remaining: {new_balance})")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Failed to deduct credit for user {user.email}: {deduct_message}")
|
||||
return False
|
||||
return True
|
||||
|
||||
# Regular auth_token - increment usage in Firestore
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""
|
||||
Brand code allocation service using Firestore atomic counters.
|
||||
|
||||
Replaces the previous Dropbox folder-scanning approach which was susceptible to
|
||||
TOCTOU race conditions when concurrent jobs read the same folder state.
|
||||
|
||||
Uses Firestore transactions to atomically allocate unique brand codes.
|
||||
Supports recycling numbers when E2E cleanup deletes test brand codes.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BRAND_CODE_COUNTERS_COLLECTION = "brand_code_counters"
|
||||
|
||||
# Singleton instance
|
||||
_brand_code_service: Optional["BrandCodeService"] = None
|
||||
|
||||
|
||||
class BrandCodeService:
|
||||
"""Atomic brand code allocation using Firestore counters."""
|
||||
|
||||
def __init__(self, db: Optional[firestore.Client] = None):
|
||||
if db is None:
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
else:
|
||||
self.db = db
|
||||
|
||||
def allocate_brand_code(self, prefix: str, dropbox_path: str) -> str:
|
||||
"""
|
||||
Atomically allocate the next brand code for a given prefix.
|
||||
|
||||
Uses a Firestore transaction to ensure no two concurrent callers
|
||||
receive the same number. If recycled numbers are available (from
|
||||
E2E cleanup), the smallest recycled number is reused first.
|
||||
|
||||
On first use for a prefix, initializes the counter by scanning
|
||||
Dropbox to find the current max number.
|
||||
|
||||
Args:
|
||||
prefix: Brand prefix (e.g., "NOMAD" or "NOMADNP")
|
||||
dropbox_path: Dropbox path for one-time initialization scan
|
||||
|
||||
Returns:
|
||||
Brand code string (e.g., "NOMAD-1264")
|
||||
"""
|
||||
doc_ref = self.db.collection(BRAND_CODE_COUNTERS_COLLECTION).document(prefix)
|
||||
|
||||
@firestore.transactional
|
||||
def allocate_in_transaction(transaction):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
|
||||
if not doc.exists:
|
||||
# First use — initialize from Dropbox scan
|
||||
next_number = self._get_initial_next_number(prefix, dropbox_path)
|
||||
allocated = next_number
|
||||
transaction.set(doc_ref, {
|
||||
"prefix": prefix,
|
||||
"next_number": next_number + 1,
|
||||
"recycled": [],
|
||||
"initialized_at": datetime.now(timezone.utc),
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
return allocated
|
||||
|
||||
data = doc.to_dict()
|
||||
recycled = data.get("recycled", [])
|
||||
|
||||
if recycled:
|
||||
# Reuse smallest recycled number
|
||||
recycled.sort()
|
||||
allocated = recycled.pop(0)
|
||||
transaction.update(doc_ref, {
|
||||
"recycled": recycled,
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
else:
|
||||
# Allocate next sequential number
|
||||
allocated = data["next_number"]
|
||||
transaction.update(doc_ref, {
|
||||
"next_number": allocated + 1,
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
return allocated
|
||||
|
||||
transaction = self.db.transaction()
|
||||
number = allocate_in_transaction(transaction)
|
||||
brand_code = f"{prefix}-{number:04d}"
|
||||
logger.info(f"Allocated brand code: {brand_code}")
|
||||
return brand_code
|
||||
|
||||
def recycle_brand_code(self, prefix: str, number: int) -> None:
|
||||
"""
|
||||
Return a brand code number to the recycled pool.
|
||||
|
||||
Called when E2E cleanup deletes a brand code's distribution.
|
||||
The number will be reused on the next allocation for this prefix.
|
||||
|
||||
Args:
|
||||
prefix: Brand prefix (e.g., "NOMAD")
|
||||
number: The numeric portion to recycle (e.g., 1234)
|
||||
"""
|
||||
doc_ref = self.db.collection(BRAND_CODE_COUNTERS_COLLECTION).document(prefix)
|
||||
|
||||
@firestore.transactional
|
||||
def recycle_in_transaction(transaction):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
|
||||
if not doc.exists:
|
||||
# Counter doesn't exist yet — nothing to recycle into.
|
||||
# The number will naturally be below next_number when
|
||||
# the counter is initialized, so it would create a gap.
|
||||
# Just log and skip.
|
||||
logger.warning(
|
||||
f"Cannot recycle {prefix}-{number:04d}: counter doc doesn't exist"
|
||||
)
|
||||
return
|
||||
|
||||
data = doc.to_dict()
|
||||
next_number = data.get("next_number", 0)
|
||||
|
||||
if number <= 0 or number >= next_number:
|
||||
logger.warning(
|
||||
f"Cannot recycle {prefix}-{number:04d}: "
|
||||
f"invalid (next_number={next_number})"
|
||||
)
|
||||
return
|
||||
|
||||
recycled = data.get("recycled", [])
|
||||
|
||||
if number not in recycled:
|
||||
recycled.append(number)
|
||||
transaction.update(doc_ref, {
|
||||
"recycled": recycled,
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
logger.info(f"Recycled brand code number: {prefix}-{number:04d}")
|
||||
else:
|
||||
logger.warning(f"Number {number} already in recycled pool for {prefix}")
|
||||
|
||||
transaction = self.db.transaction()
|
||||
recycle_in_transaction(transaction)
|
||||
|
||||
def _get_initial_next_number(self, prefix: str, dropbox_path: str) -> int:
|
||||
"""
|
||||
Scan Dropbox once to determine the starting next_number.
|
||||
|
||||
This is only called when the counter document doesn't exist yet
|
||||
(one-time migration from the old Dropbox-scanning approach).
|
||||
|
||||
Args:
|
||||
prefix: Brand prefix to scan for
|
||||
dropbox_path: Dropbox path containing organized folders
|
||||
|
||||
Returns:
|
||||
The next number to allocate (max existing + 1, minimum 1)
|
||||
"""
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
dropbox = get_dropbox_service()
|
||||
if not dropbox.is_configured:
|
||||
logger.warning(
|
||||
f"Dropbox not configured for initialization of {prefix} counter, starting at 1"
|
||||
)
|
||||
return 1
|
||||
|
||||
folders = dropbox.list_folders(dropbox_path)
|
||||
pattern = re.compile(rf"^{re.escape(prefix)}-(\d{{4}})")
|
||||
|
||||
existing_nums: set[int] = set()
|
||||
for folder in folders:
|
||||
match = pattern.match(folder)
|
||||
if match:
|
||||
existing_nums.add(int(match.group(1)))
|
||||
|
||||
if existing_nums:
|
||||
next_num = max(existing_nums) + 1
|
||||
logger.info(
|
||||
f"Initialized {prefix} counter from Dropbox: "
|
||||
f"max existing={max(existing_nums)}, next_number={next_num}"
|
||||
)
|
||||
return next_num
|
||||
|
||||
logger.info(f"No existing {prefix} codes found in Dropbox, starting at 1")
|
||||
return 1
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize {prefix} counter from Dropbox: {e}")
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def parse_brand_code(brand_code: str) -> tuple[str, int]:
|
||||
"""
|
||||
Parse a brand code string into prefix and number.
|
||||
|
||||
Args:
|
||||
brand_code: e.g., "NOMAD-1234" or "NOMADNP-0012"
|
||||
|
||||
Returns:
|
||||
Tuple of (prefix, number), e.g., ("NOMAD", 1234)
|
||||
|
||||
Raises:
|
||||
ValueError: If brand_code doesn't match expected format
|
||||
"""
|
||||
match = re.match(r"^([A-Z]+)-(\d+)$", brand_code)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid brand code format: {brand_code}")
|
||||
return match.group(1), int(match.group(2))
|
||||
|
||||
|
||||
def get_brand_code_service() -> BrandCodeService:
|
||||
"""Get or create the singleton BrandCodeService instance."""
|
||||
global _brand_code_service
|
||||
if _brand_code_service is None:
|
||||
_brand_code_service = BrandCodeService()
|
||||
return _brand_code_service
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
Proxy service for karaoke-decide catalog API.
|
||||
|
||||
Forwards artist and track search requests to the karaoke-decide backend,
|
||||
providing autocomplete data from MusicBrainz + Spotify catalogs.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
|
||||
_cache: dict[str, tuple[float, Any]] = {}
|
||||
CACHE_TTL_SECONDS = 300 # 5 minutes
|
||||
|
||||
KARAOKE_DECIDE_BASE_URL = "https://decide.nomadkaraoke.com"
|
||||
REQUEST_TIMEOUT = 10 # seconds
|
||||
|
||||
|
||||
def _get_base_url() -> str:
|
||||
"""Get the karaoke-decide API base URL from config or default."""
|
||||
return getattr(settings, "karaoke_decide_api_url", None) or KARAOKE_DECIDE_BASE_URL
|
||||
|
||||
|
||||
def _cache_get(key: str) -> Any | None:
|
||||
"""Get a value from cache if it exists and hasn't expired."""
|
||||
if key in _cache:
|
||||
expiry, data = _cache[key]
|
||||
if time.monotonic() < expiry:
|
||||
return data
|
||||
del _cache[key]
|
||||
return None
|
||||
|
||||
|
||||
def _cache_set(key: str, data: Any, ttl: float = CACHE_TTL_SECONDS) -> None:
|
||||
"""Store a value in cache with TTL."""
|
||||
_cache[key] = (time.monotonic() + ttl, data)
|
||||
|
||||
|
||||
async def search_artists(query: str, limit: int = 10) -> list[dict]:
|
||||
"""
|
||||
Search for artists via karaoke-decide catalog API.
|
||||
|
||||
Returns list of artist dicts with canonical MusicBrainz names.
|
||||
Falls back to empty list on any error.
|
||||
"""
|
||||
cache_key = f"artists:{query.lower()}:{limit}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
base_url = _get_base_url()
|
||||
url = f"{base_url}/api/catalog/artists"
|
||||
params = {"q": query, "limit": limit}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(url, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
# karaoke-decide wraps results: {"artists": [...], "total": N}
|
||||
results = data.get("artists", data) if isinstance(data, dict) else data
|
||||
_cache_set(cache_key, results)
|
||||
return results
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to search artists from karaoke-decide: {e}")
|
||||
return []
|
||||
|
||||
|
||||
async def search_tracks(query: str, artist: str | None = None, limit: int = 10) -> list[dict]:
|
||||
"""
|
||||
Search for tracks via karaoke-decide catalog API.
|
||||
|
||||
Returns list of track dicts with canonical Spotify/MusicBrainz names.
|
||||
Falls back to empty list on any error.
|
||||
"""
|
||||
cache_key = f"tracks:{query.lower()}:{(artist or '').lower()}:{limit}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
base_url = _get_base_url()
|
||||
url = f"{base_url}/api/catalog/tracks"
|
||||
params: dict[str, Any] = {"q": query, "limit": limit}
|
||||
if artist:
|
||||
params["artist"] = artist
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(url, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
# karaoke-decide wraps results: {"tracks": [...], "total": N}
|
||||
results = data.get("tracks", data) if isinstance(data, dict) else data
|
||||
_cache_set(cache_key, results)
|
||||
return results
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to search tracks from karaoke-decide: {e}")
|
||||
return []
|
||||
@@ -111,6 +111,10 @@ class DropboxService:
|
||||
"""
|
||||
Calculate next brand code from existing folders, filling gaps in the sequence.
|
||||
|
||||
NOTE: This method is only used for one-time initialization of the Firestore
|
||||
counter (see brand_code_service.py). All runtime brand code allocation now
|
||||
goes through BrandCodeService.allocate_brand_code() for atomic safety.
|
||||
|
||||
Scans the folder for existing brand codes like "NOMAD-0001" and
|
||||
returns the first available code, filling any gaps left by deleted outputs.
|
||||
|
||||
|
||||
@@ -247,6 +247,8 @@ class EmailService:
|
||||
email: str,
|
||||
token: str,
|
||||
sender_email: Optional[str] = None,
|
||||
tenant_frontend_url: Optional[str] = None,
|
||||
tenant_name: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send a magic link email for authentication.
|
||||
@@ -255,13 +257,17 @@ class EmailService:
|
||||
email: User's email address
|
||||
token: Magic link token
|
||||
sender_email: Override sender email address (for multi-tenant)
|
||||
tenant_frontend_url: Override frontend URL for tenant portals (e.g., https://vocalstar.nomadkaraoke.com)
|
||||
tenant_name: Override brand name for tenant portals (e.g., "Vocal Star")
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
magic_link_url = f"{self.frontend_url}/auth/verify?token={token}"
|
||||
base_url = tenant_frontend_url or self.frontend_url
|
||||
magic_link_url = f"{base_url}/auth/verify?token={token}"
|
||||
|
||||
subject = "Sign in to Nomad Karaoke"
|
||||
brand_name = tenant_name or "Nomad Karaoke"
|
||||
subject = f"Sign in to {brand_name}"
|
||||
|
||||
extra_styles = """
|
||||
.warning {
|
||||
@@ -277,7 +283,7 @@ class EmailService:
|
||||
content = f"""
|
||||
<p>Hi there,</p>
|
||||
|
||||
<p>Click the button below to sign in to Nomad Karaoke:</p>
|
||||
<p>Click the button below to sign in to {html.escape(brand_name)}:</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{magic_link_url}" class="button">Sign In</a>
|
||||
@@ -298,7 +304,7 @@ class EmailService:
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
text_content = f"""
|
||||
Sign in to Nomad Karaoke
|
||||
Sign in to {brand_name}
|
||||
========================
|
||||
|
||||
Click this link to sign in:
|
||||
@@ -309,7 +315,7 @@ This link expires in 15 minutes and can only be used once.
|
||||
If you didn't request this email, you can safely ignore it.
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
© {self._get_year()} {brand_name}
|
||||
"""
|
||||
|
||||
return self.provider.send_email(
|
||||
@@ -400,9 +406,31 @@ Start creating: {self.frontend_url}
|
||||
"""
|
||||
subject = "Welcome to Nomad Karaoke! 🎤"
|
||||
|
||||
credits_text = f"You have <strong>{credits} credits</strong> to get started!" if credits > 0 else ""
|
||||
|
||||
extra_styles = """
|
||||
.credits-box {
|
||||
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
||||
border: 2px solid #e2b714;
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
margin: 24px 0;
|
||||
}
|
||||
.credits-box .credits-number {
|
||||
font-size: 48px;
|
||||
font-weight: bold;
|
||||
color: #e2b714;
|
||||
line-height: 1;
|
||||
}
|
||||
.credits-box .credits-label {
|
||||
font-size: 16px;
|
||||
color: #ccc;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.credits-box .credits-note {
|
||||
font-size: 13px;
|
||||
color: #999;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.feature {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
@@ -414,10 +442,22 @@ Start creating: {self.frontend_url}
|
||||
}
|
||||
"""
|
||||
|
||||
credits_box = ""
|
||||
if credits > 0:
|
||||
credits_box = f"""
|
||||
<div class="credits-box">
|
||||
<div class="credits-number">{credits}</div>
|
||||
<div class="credits-label">Free Credits</div>
|
||||
<div class="credits-note">Each credit creates one professional karaoke video</div>
|
||||
</div>
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>Welcome to Nomad Karaoke!</p>
|
||||
|
||||
<p>Turn any song into a professional karaoke video in minutes. {credits_text}</p>
|
||||
<p>Turn any song into a professional karaoke video in minutes.</p>
|
||||
|
||||
{credits_box}
|
||||
|
||||
<p><strong>Here's how it works:</strong></p>
|
||||
|
||||
@@ -453,6 +493,10 @@ Start creating: {self.frontend_url}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p style="text-align: center; font-size: 14px; color: #999; margin-top: 20px;">
|
||||
Complete 2 videos and earn 2 more free credits by sharing your feedback!
|
||||
</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{self.frontend_url}" class="button">Get Started</a>
|
||||
</p>
|
||||
@@ -460,11 +504,13 @@ Start creating: {self.frontend_url}
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
credits_text = f"\nYou have {credits} free credits to get started!\nEach credit creates one professional karaoke video.\n" if credits > 0 else ""
|
||||
|
||||
text_content = f"""
|
||||
Welcome to Nomad Karaoke!
|
||||
|
||||
Turn any song into a professional karaoke video in minutes.
|
||||
|
||||
{credits_text}
|
||||
Here's how it works:
|
||||
|
||||
1. Search for a song
|
||||
@@ -479,6 +525,8 @@ Here's how it works:
|
||||
4. Get your video
|
||||
Download your 4K karaoke video or upload directly to YouTube.
|
||||
|
||||
Complete 2 videos and earn 2 more free credits by sharing your feedback!
|
||||
|
||||
Get started: {self.frontend_url}
|
||||
|
||||
---
|
||||
@@ -1131,6 +1179,56 @@ Thanks for being part of making Nomad Karaoke better!
|
||||
text_content=message_content,
|
||||
)
|
||||
|
||||
def send_youtube_upload_complete(
|
||||
self,
|
||||
to_email: str,
|
||||
message_content: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send follow-up email when a deferred YouTube upload completes.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
message_content: Pre-rendered message content (plain text)
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
brand_code: Release ID for subject line
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
safe_artist = sanitize_filename(artist) if artist else None
|
||||
safe_title = sanitize_filename(title) if title else None
|
||||
if brand_code and safe_artist and safe_title:
|
||||
subject = f"{brand_code}: {safe_artist} - {safe_title} (YouTube upload ready!)"
|
||||
elif safe_artist and safe_title:
|
||||
subject = f"{safe_artist} - {safe_title} (YouTube upload ready!)"
|
||||
else:
|
||||
subject = "Your YouTube upload is ready!"
|
||||
|
||||
extra_styles = """
|
||||
.content {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<div class="content">{html.escape(message_content)}</div>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=message_content,
|
||||
cc_emails=["gen@nomadkaraoke.com"],
|
||||
)
|
||||
|
||||
def send_made_for_you_order_confirmation(
|
||||
self,
|
||||
to_email: str,
|
||||
|
||||
@@ -198,7 +198,24 @@ class EncodingService:
|
||||
if resp["status"] == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp["status"] == 409:
|
||||
raise RuntimeError(f"Encoding job {job_id} already exists")
|
||||
# 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}] Job already complete on GCE worker, returning cached result")
|
||||
return {"status": "cached", "job_id": job_id, "output_files": status.get("output_files")}
|
||||
elif job_status in ("pending", "running"):
|
||||
logger.info(f"[job:{job_id}] Job still in progress on GCE worker")
|
||||
return {"status": "in_progress", "job_id": job_id}
|
||||
else:
|
||||
raise RuntimeError(f"Encoding job {job_id} already exists with status: {job_status}")
|
||||
except RuntimeError as e:
|
||||
if "not found" in str(e).lower():
|
||||
# Job was in worker memory but got cleared (restart) — safe to raise original error
|
||||
raise RuntimeError(f"Encoding job {job_id} conflict: 409 but job not found on status check")
|
||||
raise
|
||||
if resp["status"] != 200:
|
||||
raise RuntimeError(f"Failed to submit encoding job: {resp['status']} - {resp['text']}")
|
||||
|
||||
@@ -331,7 +348,17 @@ class EncodingService:
|
||||
config = encoding_config or {"formats": ["mp4_4k", "mp4_720p"]}
|
||||
|
||||
# Submit the job
|
||||
await self.submit_encoding_job(job_id, input_gcs_path, output_gcs_path, config)
|
||||
submit_result = await self.submit_encoding_job(job_id, input_gcs_path, output_gcs_path, config)
|
||||
|
||||
# If cached, return immediately — encoding already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Encoding already cached, returning immediately")
|
||||
return {"status": "complete", "output_files": submit_result.get("output_files")}
|
||||
|
||||
# If in_progress, another request is encoding it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
|
||||
|
||||
# Wait for completion
|
||||
return await self.wait_for_completion(
|
||||
|
||||
@@ -173,6 +173,82 @@ class FirestoreService:
|
||||
logger.error(f"Error listing jobs: {e}")
|
||||
raise
|
||||
|
||||
# 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',
|
||||
'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',
|
||||
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
|
||||
]
|
||||
|
||||
def list_jobs_summary(
|
||||
self,
|
||||
status: Optional[JobStatus] = None,
|
||||
exclude_statuses: Optional[List[str]] = None,
|
||||
environment: Optional[str] = None,
|
||||
client_id: Optional[str] = None,
|
||||
created_after: Optional[datetime] = None,
|
||||
created_before: Optional[datetime] = None,
|
||||
user_email: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None,
|
||||
limit: int = 100,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
List jobs with Firestore field projection for reduced payload.
|
||||
|
||||
Uses ``query.select()`` so Firestore only reads the requested fields,
|
||||
drastically cutting bandwidth and deserialization cost.
|
||||
|
||||
Returns raw dicts (not Job models) because projected documents would
|
||||
fail Pydantic validation for missing required fields.
|
||||
"""
|
||||
try:
|
||||
query = self.db.collection(self.collection)
|
||||
|
||||
if status:
|
||||
query = query.where(filter=FieldFilter('status', '==', status.value))
|
||||
|
||||
# NOTE: exclude_statuses is filtered in Python after the query
|
||||
# because Firestore's not-in filter combined with order_by(created_at)
|
||||
# requires a composite index. Since documents are tiny after select(),
|
||||
# Python filtering is fast and avoids the index requirement.
|
||||
|
||||
if environment:
|
||||
query = query.where(filter=FieldFilter('request_metadata.environment', '==', environment))
|
||||
|
||||
if client_id:
|
||||
query = query.where(filter=FieldFilter('request_metadata.client_id', '==', client_id))
|
||||
|
||||
if user_email:
|
||||
query = query.where(filter=FieldFilter('user_email', '==', user_email.lower()))
|
||||
|
||||
if tenant_id:
|
||||
query = query.where(filter=FieldFilter('tenant_id', '==', tenant_id))
|
||||
|
||||
if created_after:
|
||||
query = query.where(filter=FieldFilter('created_at', '>=', created_after))
|
||||
|
||||
if created_before:
|
||||
query = query.where(filter=FieldFilter('created_at', '<=', created_before))
|
||||
|
||||
query = query.order_by('created_at', direction=firestore.Query.DESCENDING).limit(limit)
|
||||
query = query.select(self.SUMMARY_FIELD_PATHS)
|
||||
|
||||
docs = query.stream()
|
||||
results = [doc.to_dict() for doc in docs]
|
||||
|
||||
# Apply exclude_statuses filter in Python (see note above)
|
||||
if exclude_statuses:
|
||||
results = [r for r in results if r.get('status') not in exclude_statuses]
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing jobs summary: {e}")
|
||||
raise
|
||||
|
||||
def delete_jobs_by_filter(
|
||||
self,
|
||||
environment: Optional[str] = None,
|
||||
@@ -516,6 +592,101 @@ class FirestoreService:
|
||||
logger.error(f"Error listing tokens: {e}")
|
||||
return []
|
||||
|
||||
# ============================================
|
||||
# Search Session Methods
|
||||
# ============================================
|
||||
|
||||
def create_search_session(self, session_data: dict) -> str:
|
||||
"""Store a search session for the guided job creation flow.
|
||||
|
||||
Sessions are short-lived (TTL enforced via Firestore TTL policy) and
|
||||
represent a completed audio search that hasn't yet been converted into
|
||||
a job. The document is consumed (deleted) when create-from-search runs.
|
||||
|
||||
Args:
|
||||
session_data: Dict with session_id, user_email, tenant_id, artist,
|
||||
title, results, remote_search_id, ttl_expiry.
|
||||
|
||||
Returns:
|
||||
session_id from session_data.
|
||||
"""
|
||||
try:
|
||||
session_id = session_data['session_id']
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
doc_ref.set(session_data)
|
||||
logger.info(f"Created search session {session_id}")
|
||||
return session_id
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating search session: {e}")
|
||||
raise
|
||||
|
||||
def get_search_session(self, session_id: str) -> Optional[dict]:
|
||||
"""Retrieve a search session by ID.
|
||||
|
||||
Returns None only if the document does not exist.
|
||||
Raises on Firestore errors so callers can distinguish a missing session
|
||||
from a transient datastore failure.
|
||||
|
||||
TTL-expired documents may still appear briefly; callers should check
|
||||
ttl_expiry and treat expired sessions as missing.
|
||||
|
||||
Args:
|
||||
session_id: UUID string identifying the session.
|
||||
|
||||
Returns:
|
||||
Session dict or None.
|
||||
"""
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
return doc.to_dict()
|
||||
|
||||
def consume_search_session(self, session_id: str) -> Optional[dict]:
|
||||
"""Atomically read and delete a search session.
|
||||
|
||||
Uses a Firestore transaction to prevent two concurrent job-creation
|
||||
requests from both reading the same session and creating duplicate jobs.
|
||||
|
||||
Returns the session dict if it existed, None if it did not exist.
|
||||
Raises on Firestore errors.
|
||||
|
||||
Args:
|
||||
session_id: UUID string identifying the session.
|
||||
|
||||
Returns:
|
||||
Session dict or None.
|
||||
"""
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
|
||||
@firestore.transactional
|
||||
def _read_and_delete(transaction, ref):
|
||||
doc = ref.get(transaction=transaction)
|
||||
if not doc.exists:
|
||||
return None
|
||||
session_data = doc.to_dict()
|
||||
transaction.delete(ref)
|
||||
return session_data
|
||||
|
||||
transaction = self.db.transaction()
|
||||
return _read_and_delete(transaction, doc_ref)
|
||||
|
||||
def delete_search_session(self, session_id: str) -> None:
|
||||
"""Delete a search session after it has been consumed by job creation.
|
||||
|
||||
Errors are logged but not re-raised — a missing or already-deleted
|
||||
session is a no-op.
|
||||
|
||||
Args:
|
||||
session_id: UUID string identifying the session.
|
||||
"""
|
||||
try:
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
doc_ref.delete()
|
||||
logger.debug(f"Deleted search session {session_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting search session {session_id}: {e}")
|
||||
|
||||
|
||||
# Singleton client instance
|
||||
_firestore_client: Optional[firestore.Client] = None
|
||||
|
||||
@@ -34,6 +34,8 @@ from typing import Any, Dict, List, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -42,6 +44,104 @@ class FlacfetchServiceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _format_httpx_error(e: Exception) -> str:
|
||||
"""
|
||||
Format an httpx exception into a descriptive error string.
|
||||
|
||||
httpx.RequestError subclasses (ConnectError, ReadError, etc.) often have
|
||||
empty str() representations, which produces useless messages like
|
||||
"Status request failed: ". This helper always returns something meaningful.
|
||||
"""
|
||||
error_str = str(e)
|
||||
error_type = type(e).__name__
|
||||
|
||||
if error_str:
|
||||
return f"{error_type}: {error_str}"
|
||||
|
||||
# str(e) is empty - try to include request URL for context
|
||||
if isinstance(e, httpx.RequestError):
|
||||
try:
|
||||
request = e.request
|
||||
if request:
|
||||
return f"{error_type} for {request.method} {request.url}"
|
||||
except RuntimeError:
|
||||
pass # .request not set
|
||||
return error_type
|
||||
|
||||
|
||||
def should_retry_flacfetch_error(exception: Exception) -> bool:
|
||||
"""
|
||||
Determine if a flacfetch exception should be retried.
|
||||
|
||||
Retry on:
|
||||
- httpx.RequestError (network failures: timeout, connection refused, etc.)
|
||||
- httpx.HTTPStatusError with 5xx status (server errors)
|
||||
|
||||
Don't retry on:
|
||||
- httpx.HTTPStatusError with 4xx status (client errors: bad request, auth, not found)
|
||||
"""
|
||||
if isinstance(exception, httpx.RequestError):
|
||||
# Network-level failures - always retry
|
||||
return True
|
||||
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
# HTTP errors - only retry on 5xx (server errors)
|
||||
return exception.response.status_code >= 500
|
||||
|
||||
# Don't retry on other exceptions (e.g., FlacfetchServiceError after wrapping)
|
||||
return False
|
||||
|
||||
|
||||
async def with_retry(func, *args, **kwargs):
|
||||
"""
|
||||
Execute an async function with retry logic using exponential backoff.
|
||||
|
||||
This implementation uses manual retry logic instead of tenacity decorators
|
||||
for better testability and runtime configuration.
|
||||
"""
|
||||
settings = get_settings()
|
||||
max_attempts = settings.flacfetch_retry_max_attempts
|
||||
min_wait = settings.flacfetch_retry_min_wait
|
||||
max_wait = settings.flacfetch_retry_max_wait
|
||||
|
||||
last_exception = None
|
||||
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return await func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
last_exception = e
|
||||
|
||||
# Check if we should retry this exception
|
||||
if not should_retry_flacfetch_error(e):
|
||||
# Don't retry - raise immediately
|
||||
raise
|
||||
|
||||
# Check if we have more attempts left
|
||||
if attempt >= max_attempts:
|
||||
# No more attempts - raise the last exception
|
||||
logger.warning(
|
||||
f"Flacfetch request failed after {max_attempts} attempts: "
|
||||
f"{_format_httpx_error(e) if isinstance(e, httpx.RequestError) else e}"
|
||||
)
|
||||
raise
|
||||
|
||||
# Calculate wait time with exponential backoff
|
||||
wait_time = min(min_wait * (2 ** (attempt - 1)), max_wait)
|
||||
|
||||
logger.warning(
|
||||
f"Flacfetch request failed (attempt {attempt}/{max_attempts}): "
|
||||
f"{_format_httpx_error(e) if isinstance(e, httpx.RequestError) else e}. "
|
||||
f"Retrying in {wait_time:.1f}s..."
|
||||
)
|
||||
|
||||
# Wait before next attempt
|
||||
await asyncio.sleep(wait_time)
|
||||
|
||||
# Should never reach here, but just in case
|
||||
raise last_exception
|
||||
|
||||
|
||||
class FlacfetchClient:
|
||||
"""
|
||||
Client for remote flacfetch HTTP API.
|
||||
@@ -100,7 +200,7 @@ class FlacfetchClient:
|
||||
|
||||
return data
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Cannot reach flacfetch service: {e}")
|
||||
raise FlacfetchServiceError(f"Cannot reach flacfetch service: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Health check failed: {e.response.status_code}")
|
||||
|
||||
@@ -145,10 +245,10 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Search request failed: {e}")
|
||||
raise FlacfetchServiceError(f"Search request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Search failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
|
||||
async def download(
|
||||
self,
|
||||
search_id: str,
|
||||
@@ -158,47 +258,59 @@ class FlacfetchClient:
|
||||
) -> str:
|
||||
"""
|
||||
Start downloading an audio file.
|
||||
|
||||
|
||||
Retries automatically on network errors and server errors (5xx) using
|
||||
exponential backoff. Configured via FLACFETCH_RETRY_* environment variables.
|
||||
|
||||
Args:
|
||||
search_id: Search ID from previous search
|
||||
result_index: Index of result to download
|
||||
output_filename: Optional custom filename (without extension)
|
||||
gcs_path: GCS path for upload (e.g., "uploads/job123/audio/")
|
||||
|
||||
|
||||
Returns:
|
||||
Download ID for tracking progress
|
||||
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On download start failure
|
||||
FlacfetchServiceError: On download start failure (after all retries exhausted)
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
payload = {
|
||||
"search_id": search_id,
|
||||
"result_index": result_index,
|
||||
}
|
||||
if output_filename:
|
||||
payload["output_filename"] = output_filename
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
data = resp.json()
|
||||
return data["download_id"]
|
||||
|
||||
return await with_retry(self._download_impl, search_id, result_index, output_filename, gcs_path)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download request failed: {e}")
|
||||
raise FlacfetchServiceError(f"Download request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Download start failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
|
||||
async def _download_impl(
|
||||
self,
|
||||
search_id: str,
|
||||
result_index: int,
|
||||
output_filename: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Implementation of download without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
payload = {
|
||||
"search_id": search_id,
|
||||
"result_index": result_index,
|
||||
}
|
||||
if output_filename:
|
||||
payload["output_filename"] = output_filename
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
data = resp.json()
|
||||
return data["download_id"]
|
||||
|
||||
async def download_by_id(
|
||||
self,
|
||||
source_name: str,
|
||||
@@ -214,6 +326,9 @@ class FlacfetchClient:
|
||||
This is useful when you have stored the source_id from a previous search
|
||||
and want to download later without re-searching.
|
||||
|
||||
Retries automatically on network errors and server errors (5xx) using
|
||||
exponential backoff. Configured via FLACFETCH_RETRY_* environment variables.
|
||||
|
||||
Args:
|
||||
source_name: Provider name (RED, OPS, YouTube, Spotify)
|
||||
source_id: Source-specific ID (torrent ID, video ID, track ID)
|
||||
@@ -226,52 +341,68 @@ class FlacfetchClient:
|
||||
Download ID for tracking progress
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On download start failure
|
||||
FlacfetchServiceError: On download start failure (after all retries exhausted)
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
payload = {
|
||||
"source_name": source_name,
|
||||
"source_id": source_id,
|
||||
}
|
||||
if output_filename:
|
||||
payload["output_filename"] = output_filename
|
||||
if target_file:
|
||||
payload["target_file"] = target_file
|
||||
if download_url:
|
||||
payload["download_url"] = download_url
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download-by-id",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
data = resp.json()
|
||||
return data["download_id"]
|
||||
|
||||
return await with_retry(
|
||||
self._download_by_id_impl,
|
||||
source_name, source_id, output_filename, target_file, download_url, gcs_path
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID request failed: {e}")
|
||||
raise FlacfetchServiceError(f"Download by ID request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
async def _download_by_id_impl(
|
||||
self,
|
||||
source_name: str,
|
||||
source_id: str,
|
||||
output_filename: Optional[str] = None,
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Implementation of download_by_id without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
payload = {
|
||||
"source_name": source_name,
|
||||
"source_id": source_id,
|
||||
}
|
||||
if output_filename:
|
||||
payload["output_filename"] = output_filename
|
||||
if target_file:
|
||||
payload["target_file"] = target_file
|
||||
if download_url:
|
||||
payload["download_url"] = download_url
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download-by-id",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
data = resp.json()
|
||||
return data["download_id"]
|
||||
|
||||
async def get_download_status(self, download_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get the current status of a download.
|
||||
|
||||
|
||||
Args:
|
||||
download_id: Download ID from start_download
|
||||
|
||||
|
||||
Returns:
|
||||
Status dict with progress, speed, path info
|
||||
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On status check failure
|
||||
httpx.RequestError: On network-level failures (connection refused, timeout, etc.)
|
||||
These are NOT wrapped so wait_for_download can handle retries.
|
||||
FlacfetchServiceError: On application-level failures (404, other HTTP errors)
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
@@ -282,9 +413,10 @@ class FlacfetchClient:
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Status request failed: {e}")
|
||||
|
||||
except httpx.RequestError:
|
||||
# Let network errors bubble up so wait_for_download can handle retries
|
||||
raise
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
raise FlacfetchServiceError(f"Download not found: {download_id}")
|
||||
@@ -296,35 +428,59 @@ class FlacfetchClient:
|
||||
timeout: int = 600,
|
||||
poll_interval: float = 2.0,
|
||||
progress_callback: Optional[callable] = None,
|
||||
max_consecutive_errors: int = 3,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Wait for a download to complete.
|
||||
|
||||
|
||||
Tolerates transient network errors during status polling. A single
|
||||
connection hiccup won't fail the entire download -- only N consecutive
|
||||
poll failures will.
|
||||
|
||||
Args:
|
||||
download_id: Download ID to wait for
|
||||
timeout: Maximum wait time in seconds
|
||||
poll_interval: Time between status checks
|
||||
progress_callback: Optional callback(status_dict) for progress updates
|
||||
|
||||
max_consecutive_errors: Number of consecutive poll failures before giving up
|
||||
|
||||
Returns:
|
||||
Final status dict with output_path or gcs_path
|
||||
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On download failure or timeout
|
||||
FlacfetchServiceError: On download failure, timeout, or too many consecutive poll errors
|
||||
"""
|
||||
elapsed = 0.0
|
||||
|
||||
consecutive_errors = 0
|
||||
|
||||
while elapsed < timeout:
|
||||
status = await self.get_download_status(download_id)
|
||||
|
||||
try:
|
||||
status = await self.get_download_status(download_id)
|
||||
consecutive_errors = 0 # Reset on success
|
||||
except httpx.RequestError as e:
|
||||
consecutive_errors += 1
|
||||
error_desc = _format_httpx_error(e)
|
||||
logger.warning(
|
||||
f"Status poll failed for download {download_id} "
|
||||
f"({consecutive_errors}/{max_consecutive_errors}): {error_desc}"
|
||||
)
|
||||
if consecutive_errors >= max_consecutive_errors:
|
||||
raise FlacfetchServiceError(
|
||||
f"Status polling failed after {consecutive_errors} consecutive "
|
||||
f"network errors (last: {error_desc})"
|
||||
)
|
||||
await asyncio.sleep(poll_interval)
|
||||
elapsed += poll_interval
|
||||
continue
|
||||
|
||||
if progress_callback:
|
||||
try:
|
||||
progress_callback(status)
|
||||
except Exception as e:
|
||||
logger.warning(f"Progress callback error: {e}")
|
||||
|
||||
|
||||
download_status = status.get("status")
|
||||
|
||||
|
||||
if download_status in ["complete", "seeding"]:
|
||||
logger.info(f"Download {download_id} complete: {status.get('gcs_path') or status.get('output_path')}")
|
||||
return status
|
||||
@@ -333,7 +489,7 @@ class FlacfetchClient:
|
||||
raise FlacfetchServiceError(f"Download failed: {error}")
|
||||
elif download_status == "cancelled":
|
||||
raise FlacfetchServiceError("Download was cancelled")
|
||||
|
||||
|
||||
# Log progress
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
@@ -342,10 +498,10 @@ class FlacfetchClient:
|
||||
f"Download {download_id}: {progress:.1f}% "
|
||||
f"({speed:.1f} KB/s, {peers} peers)"
|
||||
)
|
||||
|
||||
|
||||
await asyncio.sleep(poll_interval)
|
||||
elapsed += poll_interval
|
||||
|
||||
|
||||
raise FlacfetchServiceError(f"Download timed out after {timeout}s")
|
||||
|
||||
async def list_torrents(self) -> Dict[str, Any]:
|
||||
@@ -366,7 +522,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"List torrents failed: {e}")
|
||||
raise FlacfetchServiceError(f"List torrents failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"List torrents failed: {e.response.status_code}")
|
||||
|
||||
@@ -397,7 +553,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Delete torrent failed: {e}")
|
||||
raise FlacfetchServiceError(f"Delete torrent failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Delete torrent failed: {e.response.status_code}")
|
||||
|
||||
@@ -431,7 +587,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Cleanup failed: {e}")
|
||||
raise FlacfetchServiceError(f"Cleanup failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Cleanup failed: {e.response.status_code}")
|
||||
|
||||
@@ -472,7 +628,7 @@ class FlacfetchClient:
|
||||
return deleted
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Clear search cache request failed: {e}")
|
||||
raise FlacfetchServiceError(f"Clear search cache request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"Clear search cache failed: {e.response.status_code} - {e.response.text}"
|
||||
@@ -502,7 +658,7 @@ class FlacfetchClient:
|
||||
return deleted_count
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Clear all cache request failed: {e}")
|
||||
raise FlacfetchServiceError(f"Clear all cache request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"Clear all cache failed: {e.response.status_code} - {e.response.text}"
|
||||
@@ -529,7 +685,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Get cache stats request failed: {e}")
|
||||
raise FlacfetchServiceError(f"Get cache stats request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"Get cache stats failed: {e.response.status_code} - {e.response.text}"
|
||||
|
||||
@@ -3,6 +3,7 @@ import glob as glob_module
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -13,6 +14,7 @@ from typing import Optional
|
||||
|
||||
from fastapi import FastAPI, BackgroundTasks, HTTPException, Header, Depends
|
||||
from google.cloud import storage
|
||||
from packaging.version import Version
|
||||
from pydantic import BaseModel
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
@@ -254,12 +256,23 @@ def ensure_latest_wheel():
|
||||
|
||||
# Find the downloaded wheel (get the latest by version sorting)
|
||||
wheels = glob_module.glob("/tmp/karaoke_gen-*.whl")
|
||||
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
|
||||
wheels = [w for w in wheels if '-current' not in w]
|
||||
|
||||
if not wheels:
|
||||
logger.warning("No wheel found in GCS, using fallback encoding logic")
|
||||
return False
|
||||
|
||||
# Sort to get latest version
|
||||
wheel_path = sorted(wheels)[-1]
|
||||
# Sort to get latest version (by semantic version, not alphabetically)
|
||||
def extract_version(wheel_path):
|
||||
"""Extract version from wheel filename like karaoke_gen-0.116.1-py3-none-any.whl"""
|
||||
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
|
||||
if match:
|
||||
return Version(match.group(1))
|
||||
return Version("0.0.0") # Fallback for unparseable filenames
|
||||
|
||||
wheels.sort(key=extract_version, reverse=True)
|
||||
wheel_path = wheels[0]
|
||||
logger.info(f"Installing wheel: {wheel_path}")
|
||||
|
||||
# Install (or upgrade) the wheel
|
||||
@@ -359,7 +372,14 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
instrumental_selection = config.get("instrumental_selection", "clean")
|
||||
logger.info(f"Instrumental selection from config: {instrumental_selection}")
|
||||
|
||||
if instrumental_selection == "with_backing":
|
||||
if instrumental_selection == "custom":
|
||||
# User uploaded a custom instrumental or created one via mute-region editing
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*custom_instrumental*.flac", "*Instrumental Custom*.flac",
|
||||
"*custom_instrumental*.mp3",
|
||||
)
|
||||
elif instrumental_selection == "with_backing":
|
||||
# User selected instrumental with backing vocals
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
@@ -576,8 +596,18 @@ async def submit_encode_job(request: EncodeRequest, background_tasks: Background
|
||||
# Submit an encoding job
|
||||
job_id = request.job_id
|
||||
|
||||
# If job already exists, return cached result or current status
|
||||
if job_id in jobs:
|
||||
raise HTTPException(status_code=409, detail=f"Job {job_id} already exists")
|
||||
existing_job = jobs[job_id]
|
||||
if existing_job["status"] == "complete":
|
||||
# Return cached result - encoding already done
|
||||
return {"status": "cached", "job_id": job_id, "output_files": existing_job.get("output_files")}
|
||||
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,
|
||||
|
||||
@@ -12,13 +12,19 @@ shared with YouTube credentials if scopes include drive.file.
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import ssl
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from tenacity import Retrying, stop_after_attempt, wait_exponential, retry_if_exception_type
|
||||
|
||||
from backend.config import get_settings
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Transient errors that indicate a stale HTTP connection (Cloud Run idle containers)
|
||||
TRANSIENT_ERRORS = (BrokenPipeError, ConnectionResetError, ConnectionError, ssl.SSLError)
|
||||
|
||||
|
||||
class GoogleDriveService:
|
||||
"""Google Drive operations using native API."""
|
||||
@@ -33,6 +39,11 @@ class GoogleDriveService:
|
||||
self._credentials_data: Optional[Dict[str, Any]] = None
|
||||
self._loaded = False
|
||||
|
||||
def _reset_service(self):
|
||||
"""Reset the cached Drive service to force a fresh connection on next use."""
|
||||
logger.info("Resetting Google Drive service connection")
|
||||
self._service = None
|
||||
|
||||
def _load_credentials(self) -> Optional[Dict[str, Any]]:
|
||||
"""Load OAuth credentials from Secret Manager."""
|
||||
if self._loaded:
|
||||
@@ -127,6 +138,9 @@ class GoogleDriveService:
|
||||
"""
|
||||
Get existing folder or create new one, return folder ID.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
parent_id: Parent folder ID
|
||||
folder_name: Name of folder to find or create
|
||||
@@ -134,33 +148,41 @@ class GoogleDriveService:
|
||||
Returns:
|
||||
Folder ID
|
||||
"""
|
||||
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
|
||||
|
||||
# Search for existing folder
|
||||
# Escape single quotes in folder name for Google Drive API query syntax
|
||||
escaped_folder_name = folder_name.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id, name)").execute()
|
||||
# Search for existing folder
|
||||
# Escape single quotes in folder name for Google Drive API query syntax
|
||||
escaped_folder_name = folder_name.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id, name)").execute()
|
||||
|
||||
if results.get("files"):
|
||||
folder_id = results["files"][0]["id"]
|
||||
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
if results.get("files"):
|
||||
folder_id = results["files"][0]["id"]
|
||||
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
|
||||
# Create folder
|
||||
logger.info(f"Creating new folder '{folder_name}'")
|
||||
metadata = {
|
||||
"name": folder_name,
|
||||
"mimeType": "application/vnd.google-apps.folder",
|
||||
"parents": [parent_id],
|
||||
}
|
||||
folder = self.service.files().create(body=metadata, fields="id").execute()
|
||||
folder_id = folder["id"]
|
||||
logger.info(f"Created folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
# Create folder
|
||||
logger.info(f"Creating new folder '{folder_name}'")
|
||||
metadata = {
|
||||
"name": folder_name,
|
||||
"mimeType": "application/vnd.google-apps.folder",
|
||||
"parents": [parent_id],
|
||||
}
|
||||
folder = self.service.files().create(body=metadata, fields="id").execute()
|
||||
folder_id = folder["id"]
|
||||
logger.info(f"Created folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
|
||||
def upload_file(
|
||||
self,
|
||||
@@ -172,6 +194,9 @@ class GoogleDriveService:
|
||||
"""
|
||||
Upload a file to a specific Drive folder.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
local_path: Local file path
|
||||
parent_id: Parent folder ID in Google Drive
|
||||
@@ -183,49 +208,57 @@ class GoogleDriveService:
|
||||
"""
|
||||
from googleapiclient.http import MediaFileUpload
|
||||
|
||||
file_size = os.path.getsize(local_path)
|
||||
logger.info(
|
||||
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
|
||||
f"as '{filename}' to folder {parent_id}"
|
||||
)
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
file_size = os.path.getsize(local_path)
|
||||
logger.info(
|
||||
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
|
||||
f"as '{filename}' to folder {parent_id}"
|
||||
)
|
||||
|
||||
# Determine MIME type
|
||||
ext = os.path.splitext(local_path)[1].lower()
|
||||
mime_types = {
|
||||
".mp4": "video/mp4",
|
||||
".mkv": "video/x-matroska",
|
||||
".zip": "application/zip",
|
||||
".flac": "audio/flac",
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
}
|
||||
mime_type = mime_types.get(ext, "application/octet-stream")
|
||||
# Determine MIME type
|
||||
ext = os.path.splitext(local_path)[1].lower()
|
||||
mime_types = {
|
||||
".mp4": "video/mp4",
|
||||
".mkv": "video/x-matroska",
|
||||
".zip": "application/zip",
|
||||
".flac": "audio/flac",
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
}
|
||||
mime_type = mime_types.get(ext, "application/octet-stream")
|
||||
|
||||
# Check for existing file with same name
|
||||
if replace_existing:
|
||||
# Escape single quotes in filename for Google Drive API query syntax
|
||||
escaped_filename = filename.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id)").execute()
|
||||
for existing_file in results.get("files", []):
|
||||
logger.info(f"Deleting existing file: {existing_file['id']}")
|
||||
self.service.files().delete(fileId=existing_file["id"]).execute()
|
||||
# Check for existing file with same name
|
||||
if replace_existing:
|
||||
# Escape single quotes in filename for Google Drive API query syntax
|
||||
escaped_filename = filename.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id)").execute()
|
||||
for existing_file in results.get("files", []):
|
||||
logger.info(f"Deleting existing file: {existing_file['id']}")
|
||||
self.service.files().delete(fileId=existing_file["id"]).execute()
|
||||
|
||||
# Upload file
|
||||
metadata = {"name": filename, "parents": [parent_id]}
|
||||
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
|
||||
# Upload file
|
||||
metadata = {"name": filename, "parents": [parent_id]}
|
||||
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
|
||||
|
||||
file_result = (
|
||||
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
|
||||
)
|
||||
file_id = file_result["id"]
|
||||
logger.info(f"Successfully uploaded '{filename}': {file_id}")
|
||||
return file_id
|
||||
file_result = (
|
||||
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
|
||||
)
|
||||
file_id = file_result["id"]
|
||||
logger.info(f"Successfully uploaded '{filename}': {file_id}")
|
||||
return file_id
|
||||
|
||||
def upload_to_public_share(
|
||||
self,
|
||||
@@ -308,6 +341,9 @@ class GoogleDriveService:
|
||||
"""
|
||||
Delete a file from Google Drive.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
file_id: Google Drive file ID to delete
|
||||
|
||||
@@ -317,9 +353,17 @@ class GoogleDriveService:
|
||||
logger.info(f"Deleting Google Drive file: {file_id}")
|
||||
|
||||
try:
|
||||
self.service.files().delete(fileId=file_id).execute()
|
||||
logger.info(f"Successfully deleted file: {file_id}")
|
||||
return True
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
self.service.files().delete(fileId=file_id).execute()
|
||||
logger.info(f"Successfully deleted file: {file_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
# Check if it's a 404 (already deleted)
|
||||
if hasattr(e, 'resp') and e.resp.status == 404:
|
||||
@@ -343,6 +387,85 @@ class GoogleDriveService:
|
||||
results[file_id] = self.delete_file(file_id)
|
||||
return results
|
||||
|
||||
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
|
||||
"""
|
||||
Search for files in public share subfolders matching a brand code prefix.
|
||||
|
||||
Used as a fallback when gdrive_files is not tracked in state_data (e.g., old
|
||||
jobs uploaded before file ID tracking was implemented, or jobs where GDrive
|
||||
upload succeeded but file IDs were not saved due to a bug).
|
||||
|
||||
Searches CDG/, MP4/, MP4-720p/ subfolders for files whose name starts with
|
||||
'{brand_code} - '.
|
||||
|
||||
Args:
|
||||
root_folder_id: Root Google Drive folder ID for the public share
|
||||
brand_code: Brand code prefix to search for (e.g., "NOMAD-1271")
|
||||
|
||||
Returns:
|
||||
List of file IDs found matching the brand code
|
||||
"""
|
||||
found_ids = []
|
||||
subfolders = ["CDG", "MP4", "MP4-720p"]
|
||||
search_errors: list[Exception] = []
|
||||
|
||||
for subfolder in subfolders:
|
||||
try:
|
||||
# Find the subfolder
|
||||
escaped_subfolder = subfolder.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(
|
||||
q=query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
if not results.get("files"):
|
||||
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
|
||||
continue
|
||||
|
||||
subfolder_id = results["files"][0]["id"]
|
||||
|
||||
# Search for files whose name starts with the brand code
|
||||
# Use contains for efficiency, then filter by exact prefix
|
||||
escaped_brand = brand_code.replace("'", "\\'")
|
||||
file_query = (
|
||||
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
|
||||
f"and trashed=false"
|
||||
)
|
||||
file_results = self.service.files().list(
|
||||
q=file_query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
for f in file_results.get("files", []):
|
||||
if f["name"].startswith(f"{brand_code} - "):
|
||||
found_ids.append(f["id"])
|
||||
logger.info(
|
||||
f"Found GDrive file to clean up in {subfolder}/: "
|
||||
f"{f['name']} ({f['id']})"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
search_errors.append(e)
|
||||
|
||||
if search_errors:
|
||||
# Raise so the caller knows the search was incomplete.
|
||||
# This prevents the cleanup endpoint from treating an uncertain result
|
||||
# as "GDrive is clean" and incorrectly recycling the brand code.
|
||||
raise RuntimeError(
|
||||
f"GDrive brand_code search incomplete: "
|
||||
f"{len(search_errors)}/{len(subfolders)} subfolder(s) failed"
|
||||
)
|
||||
|
||||
return found_ids
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_gdrive_service: Optional[GoogleDriveService] = None
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""
|
||||
GDrive Validator Cloud Function client.
|
||||
|
||||
Lightweight HTTP client for invoking the gdrive-validator Cloud Function
|
||||
from the backend (e.g., after job completion). Uses OIDC authentication
|
||||
via the backend's service account.
|
||||
|
||||
Fire-and-forget pattern: never blocks or fails the caller.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
|
||||
import requests
|
||||
import google.auth.transport.requests
|
||||
import google.oauth2.id_token
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Cloud Function URL - set via environment variable
|
||||
GDRIVE_VALIDATOR_URL = os.environ.get("GDRIVE_VALIDATOR_URL", "")
|
||||
|
||||
|
||||
def trigger_gdrive_validation() -> dict | None:
|
||||
"""
|
||||
Invoke the GDrive validator Cloud Function.
|
||||
|
||||
Uses the backend service account's OIDC token for authentication.
|
||||
|
||||
Returns:
|
||||
Parsed JSON response from the function, or None on error.
|
||||
"""
|
||||
if not GDRIVE_VALIDATOR_URL:
|
||||
logger.debug("GDRIVE_VALIDATOR_URL not set, skipping GDrive validation trigger")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Get OIDC token for the Cloud Function URL
|
||||
auth_request = google.auth.transport.requests.Request()
|
||||
token = google.oauth2.id_token.fetch_id_token(auth_request, GDRIVE_VALIDATOR_URL)
|
||||
|
||||
response = requests.post(
|
||||
GDRIVE_VALIDATOR_URL,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
status = result.get("status", "unknown")
|
||||
|
||||
if status == "issues_found":
|
||||
logger.warning("GDrive validation found issues (notification sent)")
|
||||
elif status == "ok":
|
||||
logger.info("GDrive validation: all clear")
|
||||
else:
|
||||
logger.info(f"GDrive validation returned status: {status}")
|
||||
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to trigger GDrive validation (non-fatal)")
|
||||
return None
|
||||
@@ -61,6 +61,45 @@ def get_effective_distribution_settings(
|
||||
)
|
||||
|
||||
|
||||
def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings:
|
||||
"""
|
||||
Get effective distribution settings for a job, applying private overrides if is_private=True.
|
||||
|
||||
For private (non-published) jobs, this overrides:
|
||||
- dropbox_path → private Dropbox path (Tracks-NonPublished)
|
||||
- brand_prefix → private brand prefix (NOMADNP)
|
||||
- enable_youtube_upload → False (no YouTube for private)
|
||||
- gdrive_folder_id → None (no Google Drive for private)
|
||||
|
||||
For non-private jobs, returns the job's own distribution settings unchanged.
|
||||
|
||||
Args:
|
||||
job: Job object (or any object with distribution fields)
|
||||
|
||||
Returns:
|
||||
EffectiveDistributionSettings with private overrides applied if needed
|
||||
"""
|
||||
if getattr(job, 'is_private', False):
|
||||
settings = get_settings()
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=settings.default_private_dropbox_path,
|
||||
brand_prefix=settings.default_private_brand_prefix,
|
||||
enable_youtube_upload=False,
|
||||
gdrive_folder_id=None,
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=None,
|
||||
)
|
||||
# Non-private: return job's own settings
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=getattr(job, 'dropbox_path', None),
|
||||
brand_prefix=getattr(job, 'brand_prefix', None),
|
||||
enable_youtube_upload=getattr(job, 'enable_youtube_upload', False),
|
||||
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=getattr(job, 'youtube_description_template', None),
|
||||
)
|
||||
|
||||
|
||||
def resolve_cdg_txt_defaults(
|
||||
theme_id: Optional[str],
|
||||
enable_cdg: Optional[bool] = None,
|
||||
|
||||
@@ -7,6 +7,7 @@ bugs in the state machine or trigger logic.
|
||||
Created as part of state machine robustness improvements (2026-02-02).
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
@@ -104,6 +105,21 @@ def check_job_consistency(job: Job) -> List[str]:
|
||||
f"pending_with_input_media: has input_media_gcs_path but status=pending (may be stuck)"
|
||||
)
|
||||
|
||||
# Check: job stuck in encoding status beyond 50 minutes
|
||||
# Encoding timeout is 1 hour; if updated_at hasn't advanced in 50 min,
|
||||
# the poller likely died (e.g., Cloud Run deployment killed the instance)
|
||||
if status == JobStatus.ENCODING 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)
|
||||
encoding_age = now - updated_at
|
||||
if encoding_age > timedelta(minutes=50):
|
||||
minutes = int(encoding_age.total_seconds() / 60)
|
||||
issues.append(
|
||||
f"encoding_stuck: status=encoding for {minutes} min without update (updated_at={updated_at.isoformat()})"
|
||||
)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from datetime import datetime
|
||||
from typing import Optional, Dict, Any, List
|
||||
|
||||
from backend.config import settings
|
||||
from backend.exceptions import RateLimitExceededError, InvalidStateTransitionError
|
||||
from backend.exceptions import RateLimitExceededError, InvalidStateTransitionError, InsufficientCreditsError
|
||||
from backend.models.job import Job, JobStatus, JobCreate, STATE_TRANSITIONS
|
||||
from backend.models.worker_log import WorkerLogEntry
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
@@ -80,6 +80,18 @@ class JobManager:
|
||||
limit_value=settings.rate_limit_jobs_per_day
|
||||
)
|
||||
|
||||
# Check credits (skip for admins)
|
||||
if job_create.user_email and not is_admin:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
if not user_service.has_credits(job_create.user_email):
|
||||
credits_available = user_service.check_credits(job_create.user_email)
|
||||
raise InsufficientCreditsError(
|
||||
message="You're out of credits. Buy more to continue creating karaoke videos.",
|
||||
credits_available=credits_available,
|
||||
credits_required=1,
|
||||
)
|
||||
|
||||
# Enforce theme requirement - all jobs must have a theme
|
||||
# This prevents unstyled videos from ever being generated
|
||||
if not job_create.theme_id:
|
||||
@@ -130,11 +142,33 @@ class JobManager:
|
||||
made_for_you=job_create.made_for_you,
|
||||
customer_email=job_create.customer_email,
|
||||
customer_notes=job_create.customer_notes,
|
||||
# Private (non-published) track mode
|
||||
is_private=job_create.is_private,
|
||||
)
|
||||
|
||||
self.firestore.create_job(job)
|
||||
logger.info(f"Created new job {job_id} with status PENDING")
|
||||
|
||||
# Deduct credit atomically (after job is persisted so we have job_id for transaction record)
|
||||
if job_create.user_email and not is_admin:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
success, _remaining, deduct_msg = user_service.deduct_credit(
|
||||
job_create.user_email, job_id, reason="job_creation"
|
||||
)
|
||||
if not success:
|
||||
# Deduction failed (e.g., race condition) - delete the job and raise error
|
||||
logger.error(f"Credit deduction failed for job {job_id}: {deduct_msg}")
|
||||
try:
|
||||
self.firestore.delete_job(job_id)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to delete job {job_id} after credit deduction failure")
|
||||
raise InsufficientCreditsError(
|
||||
message="Failed to deduct credit. Please try again.",
|
||||
credits_available=0,
|
||||
credits_required=1,
|
||||
)
|
||||
|
||||
# Record job creation for rate limiting (after successful persistence)
|
||||
if job_create.user_email:
|
||||
try:
|
||||
@@ -210,6 +244,31 @@ class JobManager:
|
||||
limit=limit
|
||||
)
|
||||
|
||||
def list_jobs_summary(
|
||||
self,
|
||||
status: Optional[JobStatus] = None,
|
||||
exclude_statuses: Optional[List[str]] = None,
|
||||
environment: Optional[str] = None,
|
||||
client_id: Optional[str] = None,
|
||||
created_after: Optional[datetime] = None,
|
||||
created_before: Optional[datetime] = None,
|
||||
user_email: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None,
|
||||
limit: int = 100,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""List jobs with field projection (summary mode)."""
|
||||
return self.firestore.list_jobs_summary(
|
||||
status=status,
|
||||
exclude_statuses=exclude_statuses,
|
||||
environment=environment,
|
||||
client_id=client_id,
|
||||
created_after=created_after,
|
||||
created_before=created_before,
|
||||
user_email=user_email,
|
||||
tenant_id=tenant_id,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
def delete_jobs_by_filter(
|
||||
self,
|
||||
environment: Optional[str] = None,
|
||||
@@ -509,6 +568,7 @@ class JobManager:
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
dropbox_url = state_data.get('dropbox_link')
|
||||
brand_code = state_data.get('brand_code')
|
||||
youtube_queued = state_data.get('youtube_upload_queued', False)
|
||||
|
||||
# For made-for-you orders, send to customer and transfer ownership
|
||||
recipient_email = job.user_email
|
||||
@@ -532,6 +592,8 @@ class JobManager:
|
||||
youtube_url=youtube_url,
|
||||
dropbox_url=dropbox_url,
|
||||
brand_code=brand_code,
|
||||
is_private=getattr(job, 'is_private', False),
|
||||
youtube_queued=youtube_queued,
|
||||
)
|
||||
|
||||
# Try to get existing event loop, create new one if none exists
|
||||
@@ -755,11 +817,32 @@ class JobManager:
|
||||
)
|
||||
|
||||
logger.error(f"Job {job_id} failed: {error_message}")
|
||||
|
||||
# Auto-refund credit on failure (skip for admin-owned jobs)
|
||||
try:
|
||||
job = self.get_job(job_id)
|
||||
if job and job.user_email:
|
||||
from backend.services.auth_service import is_admin_email
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
if not is_admin_email(job.user_email):
|
||||
user_service = get_user_service()
|
||||
refund_ok, new_balance, refund_msg = user_service.refund_credit(
|
||||
job.user_email, job_id, reason="job_failed"
|
||||
)
|
||||
if refund_ok:
|
||||
logger.info(f"Refunded credit for failed job {job_id} to {_mask_email(job.user_email)} (balance: {new_balance})")
|
||||
else:
|
||||
logger.warning(f"Credit refund failed for job {job_id}: {refund_msg}")
|
||||
except Exception as refund_err:
|
||||
# Don't fail the fail_job call if refund fails
|
||||
logger.warning(f"Error refunding credit for job {job_id}: {refund_err}")
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Error marking job {job_id} as failed: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def update_file_url(self, job_id: str, category: str, file_type: str, url: str) -> None:
|
||||
"""
|
||||
Update a file URL in the job's file_urls structure.
|
||||
|
||||
@@ -71,6 +71,8 @@ class JobNotificationService:
|
||||
youtube_url: Optional[str] = None,
|
||||
dropbox_url: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
is_private: bool = False,
|
||||
youtube_queued: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
Send job completion email to user.
|
||||
@@ -84,6 +86,8 @@ class JobNotificationService:
|
||||
youtube_url: YouTube video URL
|
||||
dropbox_url: Dropbox folder URL
|
||||
brand_code: Release ID (e.g., "NOMAD-1178")
|
||||
is_private: If True, omit YouTube section (private/non-published tracks)
|
||||
youtube_queued: If True, YouTube upload was deferred due to quota
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
@@ -106,6 +110,8 @@ class JobNotificationService:
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
feedback_url=FEEDBACK_FORM_URL,
|
||||
is_private=is_private,
|
||||
youtube_queued=youtube_queued,
|
||||
)
|
||||
|
||||
# Send the email with CC to admin
|
||||
@@ -129,6 +135,63 @@ class JobNotificationService:
|
||||
logger.exception(f"Error sending completion email for job {job_id}: {e}")
|
||||
return False
|
||||
|
||||
async def send_youtube_upload_complete_email(
|
||||
self,
|
||||
job_id: str,
|
||||
user_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send follow-up email when a deferred YouTube upload completes.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
user_email: User's email address
|
||||
artist: Artist name
|
||||
title: Song title
|
||||
youtube_url: YouTube video URL
|
||||
brand_code: Release ID
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
if not ENABLE_AUTO_EMAILS:
|
||||
logger.info(f"Auto emails disabled, skipping YouTube notification for job {job_id}")
|
||||
return False
|
||||
|
||||
if not user_email:
|
||||
logger.warning(f"No user email for job {job_id}, skipping YouTube notification")
|
||||
return False
|
||||
|
||||
try:
|
||||
message_content = self.template_service.render_youtube_upload_complete(
|
||||
artist=artist,
|
||||
title=title,
|
||||
youtube_url=youtube_url,
|
||||
)
|
||||
|
||||
success = self.email_service.send_youtube_upload_complete(
|
||||
to_email=user_email,
|
||||
message_content=message_content,
|
||||
artist=artist,
|
||||
title=title,
|
||||
brand_code=brand_code,
|
||||
)
|
||||
|
||||
if success:
|
||||
logger.info(f"Sent YouTube upload notification for job {job_id} to {_mask_email(user_email)}")
|
||||
else:
|
||||
logger.error(f"Failed to send YouTube upload notification for job {job_id}")
|
||||
|
||||
return success
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error sending YouTube upload notification for job {job_id}: {e}")
|
||||
return False
|
||||
|
||||
async def send_action_reminder_email(
|
||||
self,
|
||||
job_id: str,
|
||||
@@ -218,6 +281,8 @@ class JobNotificationService:
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
dropbox_url: Optional[str] = None,
|
||||
is_private: bool = False,
|
||||
youtube_queued: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
Get the rendered completion message for a job (for admin copy functionality).
|
||||
@@ -229,6 +294,8 @@ class JobNotificationService:
|
||||
title: Song title
|
||||
youtube_url: YouTube video URL
|
||||
dropbox_url: Dropbox folder URL
|
||||
is_private: If True, omit YouTube section (private/non-published tracks)
|
||||
youtube_queued: If True, YouTube upload was deferred
|
||||
|
||||
Returns:
|
||||
Rendered message content as plain text
|
||||
@@ -241,6 +308,8 @@ class JobNotificationService:
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
feedback_url=FEEDBACK_FORM_URL,
|
||||
is_private=is_private,
|
||||
youtube_queued=youtube_queued,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""
|
||||
KaraokeNerds community version detection service.
|
||||
|
||||
Scrapes karaokenerds.com to check if a song already has community-approved
|
||||
karaoke versions available on YouTube. Ported from kjbox/kj-controller/karaoke_nerds.py.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SEARCH_URL = "https://karaokenerds.com/Search"
|
||||
REQUEST_TIMEOUT = 8
|
||||
USER_AGENT = "NomadKaraokeGen/1.0"
|
||||
|
||||
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
|
||||
_cache: dict[str, tuple[float, Any]] = {}
|
||||
CACHE_TTL_SECONDS = 3600 # 1 hour
|
||||
|
||||
|
||||
def _cache_get(key: str) -> Any | None:
|
||||
"""Get a value from cache if it exists and hasn't expired."""
|
||||
if key in _cache:
|
||||
expiry, data = _cache[key]
|
||||
if time.monotonic() < expiry:
|
||||
return data
|
||||
del _cache[key]
|
||||
return None
|
||||
|
||||
|
||||
def _cache_set(key: str, data: Any, ttl: float = CACHE_TTL_SECONDS) -> None:
|
||||
"""Store a value in cache with TTL."""
|
||||
_cache[key] = (time.monotonic() + ttl, data)
|
||||
|
||||
|
||||
def _clean_youtube_url(url: str) -> str:
|
||||
"""Strip playlist params from YouTube URLs, keep just the video URL."""
|
||||
return re.sub(r"&list=[^&]*", "", url)
|
||||
|
||||
|
||||
def _parse_single_track(li) -> dict | None:
|
||||
"""Parse a single track <li> element from karaokenerds search results."""
|
||||
# Brand name: first <a> in the li
|
||||
brand_link = li.find("a")
|
||||
brand_name = brand_link.get_text(strip=True) if brand_link else ""
|
||||
|
||||
# Brand code: text inside .badge span
|
||||
badge = li.find("span", class_="badge")
|
||||
brand_code = ""
|
||||
if badge:
|
||||
brand_code = badge.get_text(strip=True)
|
||||
|
||||
# YouTube URL: link containing youtube.com
|
||||
youtube_url = None
|
||||
for a in li.find_all("a", href=True):
|
||||
href = a["href"]
|
||||
if "youtube.com" in href:
|
||||
youtube_url = _clean_youtube_url(href)
|
||||
break
|
||||
|
||||
# Community: presence of img.check
|
||||
is_community = bool(li.find("img", class_="check"))
|
||||
|
||||
if not youtube_url:
|
||||
return None
|
||||
|
||||
return {
|
||||
"brand_name": brand_name,
|
||||
"brand_code": brand_code,
|
||||
"youtube_url": youtube_url,
|
||||
"is_community": is_community,
|
||||
}
|
||||
|
||||
|
||||
def _parse_tracks(details_row) -> list[dict]:
|
||||
"""Parse track list items from a details row."""
|
||||
tracks = []
|
||||
for li in details_row.find_all("li", class_="track"):
|
||||
track = _parse_single_track(li)
|
||||
if track:
|
||||
tracks.append(track)
|
||||
return tracks
|
||||
|
||||
|
||||
def parse_results(html: str) -> list[dict]:
|
||||
"""Parse karaokenerds.com search results HTML into structured data."""
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
table = soup.find("table")
|
||||
if not table:
|
||||
return []
|
||||
|
||||
tbody = table.find("tbody")
|
||||
if not tbody:
|
||||
return []
|
||||
|
||||
songs = []
|
||||
rows = tbody.find_all("tr", recursive=False)
|
||||
|
||||
i = 0
|
||||
while i < len(rows):
|
||||
row = rows[i]
|
||||
|
||||
# Song rows have class "group"
|
||||
if "group" not in row.get("class", []):
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Extract title and artist from the song row
|
||||
cells = row.find_all("td")
|
||||
if len(cells) < 3:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
title_link = cells[0].find("a")
|
||||
artist_link = cells[1].find("a")
|
||||
title = title_link.get_text(strip=True) if title_link else ""
|
||||
artist = artist_link.get_text(strip=True) if artist_link else ""
|
||||
|
||||
# The next row should be the details row with tracks
|
||||
tracks = []
|
||||
if i + 1 < len(rows):
|
||||
details_row = rows[i + 1]
|
||||
if "details" in details_row.get("class", []):
|
||||
tracks = _parse_tracks(details_row)
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
else:
|
||||
i += 1
|
||||
|
||||
if title:
|
||||
songs.append({
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"tracks": tracks,
|
||||
})
|
||||
|
||||
return songs
|
||||
|
||||
|
||||
async def check_community_versions(artist: str, title: str) -> dict:
|
||||
"""
|
||||
Check if a song has community-approved karaoke versions on karaokenerds.
|
||||
|
||||
Returns a dict with:
|
||||
- has_community: bool
|
||||
- songs: list of matched songs with community tracks
|
||||
- best_youtube_url: URL of the top community version (if any)
|
||||
"""
|
||||
query = f"{artist} {title}"
|
||||
cache_key = f"community:{query.lower().strip()}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
|
||||
url = f"{SEARCH_URL}?{params}"
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
|
||||
result = {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
songs = parse_results(resp.text)
|
||||
|
||||
# Filter to only songs that have community tracks with YouTube URLs
|
||||
community_songs = []
|
||||
best_youtube_url = None
|
||||
|
||||
for song in songs:
|
||||
community_tracks = [t for t in song["tracks"] if t["is_community"]]
|
||||
if community_tracks:
|
||||
community_songs.append({
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": community_tracks,
|
||||
})
|
||||
if best_youtube_url is None:
|
||||
best_youtube_url = community_tracks[0]["youtube_url"]
|
||||
|
||||
result = {
|
||||
"has_community": len(community_songs) > 0,
|
||||
"songs": community_songs,
|
||||
"best_youtube_url": best_youtube_url,
|
||||
}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
@@ -57,6 +57,8 @@ class PackagingService:
|
||||
title: str,
|
||||
output_mp3_path: Optional[str] = None,
|
||||
output_cdg_path: Optional[str] = None,
|
||||
lrc_has_countdown_padding: bool = False,
|
||||
countdown_padding_seconds: float = 3.0,
|
||||
) -> Tuple[str, Optional[str], Optional[str]]:
|
||||
"""
|
||||
Create a CDG package (ZIP containing CDG and MP3 files).
|
||||
@@ -69,6 +71,9 @@ class PackagingService:
|
||||
title: Song title for metadata
|
||||
output_mp3_path: Optional path for the extracted MP3 file
|
||||
output_cdg_path: Optional path for the extracted CDG file
|
||||
lrc_has_countdown_padding: If True, LRC contains countdown-shifted timestamps
|
||||
that need adjustment since CDG uses instrumental audio without padding
|
||||
countdown_padding_seconds: Duration of countdown padding to compensate for
|
||||
|
||||
Returns:
|
||||
Tuple of (zip_path, mp3_path, cdg_path)
|
||||
@@ -131,6 +136,8 @@ class PackagingService:
|
||||
title=title,
|
||||
artist=artist,
|
||||
cdg_styles=self.cdg_styles,
|
||||
lrc_has_countdown_padding=lrc_has_countdown_padding,
|
||||
countdown_padding_seconds=countdown_padding_seconds,
|
||||
)
|
||||
|
||||
# Rename ZIP to expected output path if different
|
||||
|
||||
@@ -164,39 +164,44 @@ class RateLimitService:
|
||||
logger.info(f"Recorded job {job_id} for user {user_email} rate limiting")
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# YouTube Upload Rate Limiting
|
||||
# YouTube Upload Rate Limiting (DEPRECATED - use YouTubeQuotaService)
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
def check_youtube_upload_limit(self) -> Tuple[bool, int, str]:
|
||||
"""
|
||||
Check if the system can perform a YouTube upload.
|
||||
|
||||
YouTube uploads are limited system-wide due to API quota constraints.
|
||||
DEPRECATED: Use YouTubeQuotaService.check_quota_available() instead.
|
||||
This method now delegates to the quota service for backward compatibility.
|
||||
|
||||
Returns:
|
||||
Tuple of (allowed, remaining, message)
|
||||
"""
|
||||
try:
|
||||
from backend.services.youtube_quota_service import get_youtube_quota_service
|
||||
quota_service = get_youtube_quota_service()
|
||||
except (ImportError, Exception) as e:
|
||||
logger.warning(f"Quota service unavailable, falling back to legacy check: {e}")
|
||||
# Fallback to legacy behavior below
|
||||
quota_service = None
|
||||
|
||||
if quota_service is not None:
|
||||
try:
|
||||
return quota_service.check_quota_available()
|
||||
except Exception as e:
|
||||
logger.error(f"Quota service check failed: {e}")
|
||||
return False, 0, f"Quota service error: {e}"
|
||||
|
||||
# Fallback to legacy behavior
|
||||
if not settings.enable_rate_limiting:
|
||||
return True, -1, "Rate limiting disabled"
|
||||
|
||||
limit = settings.rate_limit_youtube_uploads_per_day
|
||||
if limit == 0:
|
||||
return True, -1, "No YouTube upload limit configured"
|
||||
|
||||
current_count = self.get_youtube_uploads_today()
|
||||
remaining = max(0, limit - current_count)
|
||||
|
||||
if current_count >= limit:
|
||||
seconds = _seconds_until_midnight_utc()
|
||||
logger.warning(
|
||||
f"YouTube upload limit exceeded: {current_count}/{limit} uploads today"
|
||||
)
|
||||
return (
|
||||
False,
|
||||
0,
|
||||
f"Daily YouTube upload limit reached ({limit} uploads per day). Resets in {seconds // 3600}h {(seconds % 3600) // 60}m."
|
||||
)
|
||||
|
||||
return False, 0, f"Daily YouTube upload limit reached ({limit} per day)"
|
||||
return True, remaining, f"{remaining} YouTube uploads remaining today"
|
||||
|
||||
def get_youtube_uploads_today(self) -> int:
|
||||
@@ -216,7 +221,8 @@ class RateLimitService:
|
||||
"""
|
||||
Record a YouTube upload for rate limiting.
|
||||
|
||||
Uses Firestore transactions for atomic increment.
|
||||
DEPRECATED: Use YouTubeQuotaService.record_operation() instead.
|
||||
This method still records to the legacy collection for backward compatibility.
|
||||
"""
|
||||
if not settings.enable_rate_limiting:
|
||||
return
|
||||
|
||||
@@ -48,7 +48,7 @@ CREDIT_PACKAGES = {
|
||||
|
||||
# Made-for-you service package (not a credit package - creates a job directly)
|
||||
MADE_FOR_YOU_PACKAGE = {
|
||||
"price_cents": 1500, # $15.00
|
||||
"price_cents": 5000, # $50.00
|
||||
"name": "Made For You Karaoke Video",
|
||||
"description": "Professional 4K karaoke video with perfectly synced lyrics, delivered to your email within 24 hours",
|
||||
"images": ["https://gen.nomadkaraoke.com/nomad-logo.png"],
|
||||
|
||||
@@ -79,6 +79,18 @@ Thanks!
|
||||
"""
|
||||
|
||||
|
||||
DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE = """Hi {name},
|
||||
|
||||
Great news! Your karaoke video for "{artist} - {title}" has been uploaded to YouTube:
|
||||
{youtube_url}
|
||||
|
||||
This upload was briefly delayed while our systems processed other uploads, but everything is all set now.
|
||||
|
||||
Thanks!
|
||||
-Andrew
|
||||
"""
|
||||
|
||||
|
||||
class TemplateService:
|
||||
"""
|
||||
Service for fetching and rendering email templates from GCS.
|
||||
@@ -212,6 +224,8 @@ class TemplateService:
|
||||
title: Optional[str] = None,
|
||||
job_id: Optional[str] = None,
|
||||
feedback_url: Optional[str] = None,
|
||||
is_private: bool = False,
|
||||
youtube_queued: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
Render the job completion email template.
|
||||
@@ -224,11 +238,29 @@ class TemplateService:
|
||||
title: Song title
|
||||
job_id: Job ID
|
||||
feedback_url: Feedback form URL (optional)
|
||||
is_private: If True, remove YouTube section entirely (private/non-published tracks)
|
||||
youtube_queued: If True, YouTube upload was deferred - show pending message
|
||||
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self.get_job_completion_template()
|
||||
|
||||
# For private tracks, remove the YouTube section entirely
|
||||
if is_private:
|
||||
template = re.sub(
|
||||
r"\n*Here's the link for the karaoke video published to YouTube:\n\{youtube_url\}\n*",
|
||||
'\n',
|
||||
template,
|
||||
)
|
||||
elif youtube_queued and not youtube_url:
|
||||
# Replace YouTube URL with pending message
|
||||
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."
|
||||
)
|
||||
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"youtube_url": youtube_url or "[YouTube URL not available]",
|
||||
@@ -303,6 +335,39 @@ class TemplateService:
|
||||
}
|
||||
return self.render_template(template, variables)
|
||||
|
||||
def render_youtube_upload_complete(
|
||||
self,
|
||||
name: Optional[str] = None,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Render the YouTube upload complete follow-up email template.
|
||||
|
||||
Sent when a deferred YouTube upload completes after quota becomes available.
|
||||
|
||||
Args:
|
||||
name: User's display name
|
||||
artist: Artist name
|
||||
title: Song title
|
||||
youtube_url: YouTube video URL
|
||||
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
|
||||
if template is None:
|
||||
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE
|
||||
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"artist": artist or "Unknown Artist",
|
||||
"title": title or "Unknown Title",
|
||||
"youtube_url": youtube_url or "[YouTube URL not available]",
|
||||
}
|
||||
return self.render_template(template, variables)
|
||||
|
||||
def upload_template(self, template_name: str, content: str) -> bool:
|
||||
"""
|
||||
Upload a template to GCS.
|
||||
|
||||
@@ -48,7 +48,7 @@ class UserService:
|
||||
"""Service for user management and authentication."""
|
||||
|
||||
# Number of free credits granted to new users
|
||||
NEW_USER_FREE_CREDITS = 1
|
||||
NEW_USER_FREE_CREDITS = 2
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize user service with Firestore client."""
|
||||
@@ -768,6 +768,55 @@ class UserService:
|
||||
logger.exception("Error enabling user")
|
||||
return False
|
||||
|
||||
def delete_user(self, email: str, admin_email: str) -> bool:
|
||||
"""
|
||||
Permanently delete a user and all their associated data.
|
||||
|
||||
Deletes: user document, sessions, magic links.
|
||||
Does NOT delete jobs (they remain as historical records).
|
||||
|
||||
Args:
|
||||
email: Email of the user to delete
|
||||
admin_email: Email/ID of the admin performing the action
|
||||
|
||||
Returns:
|
||||
True if user was deleted, False if user not found
|
||||
|
||||
Raises:
|
||||
ValueError: If trying to delete an admin user
|
||||
"""
|
||||
try:
|
||||
email = email.lower()
|
||||
user = self.get_user(email)
|
||||
|
||||
if not user:
|
||||
return False
|
||||
|
||||
if user.role == UserRole.ADMIN:
|
||||
raise ValueError("Cannot delete admin users")
|
||||
|
||||
# Revoke all active sessions
|
||||
self.revoke_all_sessions(email)
|
||||
|
||||
# Delete magic links for the user
|
||||
magic_links = self.db.collection(MAGIC_LINKS_COLLECTION).where(
|
||||
filter=FieldFilter('email', '==', email)
|
||||
).stream()
|
||||
for doc in magic_links:
|
||||
doc.reference.delete()
|
||||
|
||||
# Delete the user document
|
||||
self.db.collection(USERS_COLLECTION).document(email).delete()
|
||||
|
||||
logger.info(f"Admin {admin_email} permanently deleted user {email}")
|
||||
return True
|
||||
|
||||
except ValueError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(f"Error deleting user {email}")
|
||||
return False
|
||||
|
||||
def increment_jobs_completed(self, email: str) -> bool:
|
||||
"""Increment the completed jobs counter for a user using atomic increment."""
|
||||
try:
|
||||
|
||||
@@ -38,6 +38,7 @@ WORKER_QUEUES = {
|
||||
"render-video": "render-worker-queue",
|
||||
"video": "video-worker-queue",
|
||||
"idle-reminder": "idle-reminder-queue", # For delayed idle reminder checks
|
||||
"gdrive-validation": "gdrive-validation-queue", # For delayed post-job validation
|
||||
}
|
||||
|
||||
# Dispatch deadlines for each worker type (in seconds)
|
||||
@@ -51,10 +52,15 @@ WORKER_DISPATCH_DEADLINES = {
|
||||
"render-video": 1800, # 30 min - Video encoding can be slow
|
||||
"video": 1800, # 30 min - Video encoding can be slow
|
||||
"idle-reminder": 60, # 1 min - Quick check and potential email send
|
||||
"gdrive-validation": 120, # 2 min - Calls Cloud Function which validates GDrive
|
||||
}
|
||||
|
||||
# Default delay for idle reminders (seconds)
|
||||
IDLE_REMINDER_DELAY_SECONDS = 5 * 60 # 5 minutes
|
||||
IDLE_REMINDER_DELAY_SECONDS = 2 * 60 # 2 minutes
|
||||
|
||||
# Default delay for post-job GDrive validation (seconds)
|
||||
# Gives E2E tests time to verify output and clean up before validator runs
|
||||
GDRIVE_VALIDATION_DELAY_SECONDS = 5 * 60 # 5 minutes
|
||||
|
||||
|
||||
class WorkerService:
|
||||
@@ -582,6 +588,93 @@ class WorkerService:
|
||||
)
|
||||
return False
|
||||
|
||||
async def schedule_gdrive_validation(
|
||||
self,
|
||||
delay_seconds: int = GDRIVE_VALIDATION_DELAY_SECONDS
|
||||
) -> bool:
|
||||
"""
|
||||
Schedule a delayed GDrive validation check.
|
||||
|
||||
Fires after the specified delay so that E2E test cleanup completes
|
||||
before the validator runs, avoiding false "all clear" reports.
|
||||
|
||||
Args:
|
||||
delay_seconds: Delay before executing the validation (default: 5 minutes)
|
||||
|
||||
Returns:
|
||||
True if task was scheduled successfully, False otherwise
|
||||
"""
|
||||
if not self._use_cloud_tasks:
|
||||
logger.info(
|
||||
f"GDrive validation not scheduled (Cloud Tasks disabled). "
|
||||
f"Would have fired in {delay_seconds}s."
|
||||
)
|
||||
return True
|
||||
|
||||
try:
|
||||
from google.cloud import tasks_v2
|
||||
from google.protobuf import timestamp_pb2
|
||||
import time
|
||||
|
||||
queue_name = WORKER_QUEUES.get("gdrive-validation")
|
||||
if not queue_name:
|
||||
logger.error("GDrive validation queue not configured")
|
||||
return False
|
||||
|
||||
project = self.settings.google_cloud_project
|
||||
if not project:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
|
||||
# Build queue path
|
||||
parent = self.tasks_client.queue_path(project, location, queue_name)
|
||||
|
||||
# Build headers
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
if self._admin_token:
|
||||
headers["X-Admin-Token"] = self._admin_token
|
||||
|
||||
headers = inject_trace_context(headers)
|
||||
|
||||
# Calculate schedule time
|
||||
schedule_time = timestamp_pb2.Timestamp()
|
||||
schedule_time.FromSeconds(int(time.time()) + delay_seconds)
|
||||
|
||||
dispatch_deadline_seconds = WORKER_DISPATCH_DEADLINES.get("gdrive-validation", 120)
|
||||
|
||||
# Build task payload
|
||||
task = {
|
||||
"http_request": {
|
||||
"http_method": tasks_v2.HttpMethod.POST,
|
||||
"url": f"{self._base_url}/api/internal/trigger-gdrive-validation",
|
||||
"headers": headers,
|
||||
"body": b"{}",
|
||||
"oidc_token": {
|
||||
"service_account_email": f"karaoke-backend@{project}.iam.gserviceaccount.com",
|
||||
},
|
||||
},
|
||||
"schedule_time": schedule_time,
|
||||
"dispatch_deadline": duration_pb2.Duration(seconds=dispatch_deadline_seconds),
|
||||
}
|
||||
|
||||
response = self.tasks_client.create_task(parent=parent, task=task)
|
||||
logger.info(
|
||||
f"Scheduled GDrive validation in {delay_seconds}s: {response.name}"
|
||||
)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Failed to schedule GDrive validation: {e}",
|
||||
exc_info=True
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
# Global worker service instance
|
||||
_worker_service: Optional[WorkerService] = None
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
"""
|
||||
YouTube Data API v3 quota tracking service.
|
||||
|
||||
Tracks quota unit consumption in Firestore with daily documents keyed by
|
||||
Pacific Time date (YouTube quota resets at midnight PT).
|
||||
|
||||
Replaces the old hard-coded upload count limit with unit-based tracking
|
||||
that reflects actual API quota costs:
|
||||
- videos.insert: 100 units
|
||||
- search.list: 100 units
|
||||
- thumbnails.set: 50 units
|
||||
- videos.delete: 50 units
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Tuple, Optional, Dict, Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
YOUTUBE_QUOTA_COLLECTION = "youtube_quota"
|
||||
PACIFIC_TZ = ZoneInfo("America/Los_Angeles")
|
||||
|
||||
# Known quota costs per YouTube Data API v3 operation
|
||||
QUOTA_COSTS = {
|
||||
"videos.insert": 100,
|
||||
"search.list": 100,
|
||||
"thumbnails.set": 50,
|
||||
"videos.delete": 50,
|
||||
"channels.list": 1,
|
||||
}
|
||||
|
||||
|
||||
def _get_today_date_pt() -> str:
|
||||
"""Get today's date in Pacific Time as YYYY-MM-DD string."""
|
||||
return datetime.now(PACIFIC_TZ).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _seconds_until_midnight_pt() -> int:
|
||||
"""Calculate seconds until Pacific Time midnight (when YouTube quota resets)."""
|
||||
from datetime import timedelta
|
||||
now = datetime.now(PACIFIC_TZ)
|
||||
midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
next_midnight = midnight + timedelta(days=1)
|
||||
return int((next_midnight - now).total_seconds())
|
||||
|
||||
|
||||
class YouTubeQuotaService:
|
||||
"""
|
||||
Service for tracking YouTube Data API v3 quota consumption.
|
||||
|
||||
Uses Firestore for distributed tracking with daily documents
|
||||
that automatically correspond to YouTube's quota reset at midnight PT.
|
||||
"""
|
||||
|
||||
def __init__(self, db: Optional[firestore.Client] = None):
|
||||
if db is None:
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
else:
|
||||
self.db = db
|
||||
|
||||
def check_quota_available(self, estimated_units: Optional[int] = None) -> Tuple[bool, int, str]:
|
||||
"""
|
||||
Check if enough quota is available for an upload.
|
||||
|
||||
Args:
|
||||
estimated_units: Estimated units needed. Defaults to settings.youtube_quota_upload_cost.
|
||||
|
||||
Returns:
|
||||
Tuple of (allowed, remaining_units, message)
|
||||
"""
|
||||
if estimated_units is None:
|
||||
estimated_units = settings.youtube_quota_upload_cost
|
||||
|
||||
limit = settings.youtube_quota_daily_limit
|
||||
safety_margin = settings.youtube_quota_safety_margin
|
||||
effective_limit = limit - safety_margin
|
||||
|
||||
if limit == 0:
|
||||
return True, -1, "No YouTube quota limit configured"
|
||||
|
||||
consumed = self._get_units_consumed_today()
|
||||
remaining = max(0, effective_limit - consumed)
|
||||
|
||||
if consumed + estimated_units > effective_limit:
|
||||
seconds = _seconds_until_midnight_pt()
|
||||
hours = seconds // 3600
|
||||
minutes = (seconds % 3600) // 60
|
||||
logger.warning(
|
||||
f"YouTube quota insufficient: {consumed}/{effective_limit} units used "
|
||||
f"(need {estimated_units} more), resets in {hours}h {minutes}m"
|
||||
)
|
||||
return (
|
||||
False,
|
||||
remaining,
|
||||
f"YouTube API quota insufficient ({consumed}/{effective_limit} units used, "
|
||||
f"need {estimated_units}). Resets in {hours}h {minutes}m."
|
||||
)
|
||||
|
||||
return True, remaining, f"{remaining} quota units remaining today"
|
||||
|
||||
def record_operation(
|
||||
self,
|
||||
job_id: str,
|
||||
user_email: str,
|
||||
operation: str,
|
||||
units: Optional[int] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Record a YouTube API operation for quota tracking.
|
||||
|
||||
Uses Firestore transactions for atomic updates.
|
||||
|
||||
Args:
|
||||
job_id: Job ID that triggered the operation
|
||||
user_email: User who owns the job
|
||||
operation: API operation name (e.g., "videos.insert")
|
||||
units: Quota units consumed. If None, looks up from QUOTA_COSTS.
|
||||
"""
|
||||
if units is None:
|
||||
units = QUOTA_COSTS.get(operation, 0)
|
||||
if units == 0:
|
||||
logger.warning(f"Unknown YouTube API operation: {operation}, recording 0 units")
|
||||
|
||||
date_str = _get_today_date_pt()
|
||||
doc_ref = self.db.collection(YOUTUBE_QUOTA_COLLECTION).document(date_str)
|
||||
|
||||
@firestore.transactional
|
||||
def update_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
units_consumed = data.get("units_consumed", 0) + units
|
||||
operations = data.get("operations", [])
|
||||
else:
|
||||
units_consumed = units
|
||||
operations = []
|
||||
|
||||
operations.append({
|
||||
"job_id": job_id,
|
||||
"operation": operation,
|
||||
"units": units,
|
||||
"user_email": user_email,
|
||||
"timestamp": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
|
||||
transaction.set(doc_ref, {
|
||||
"date_pt": date_str,
|
||||
"units_consumed": units_consumed,
|
||||
"units_limit": settings.youtube_quota_daily_limit,
|
||||
"operations": operations,
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
|
||||
transaction = self.db.transaction()
|
||||
update_in_transaction(transaction, doc_ref)
|
||||
logger.info(
|
||||
f"Recorded YouTube quota: {operation}={units} units for job {job_id} "
|
||||
f"(user: {user_email})"
|
||||
)
|
||||
|
||||
def get_quota_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Get current quota statistics for admin dashboard.
|
||||
|
||||
Returns:
|
||||
Dict with quota usage stats
|
||||
"""
|
||||
date_str = _get_today_date_pt()
|
||||
doc_ref = self.db.collection(YOUTUBE_QUOTA_COLLECTION).document(date_str)
|
||||
doc = doc_ref.get()
|
||||
|
||||
limit = settings.youtube_quota_daily_limit
|
||||
safety_margin = settings.youtube_quota_safety_margin
|
||||
effective_limit = limit - safety_margin
|
||||
|
||||
if not doc.exists:
|
||||
return {
|
||||
"date_pt": date_str,
|
||||
"units_consumed": 0,
|
||||
"units_limit": limit,
|
||||
"effective_limit": effective_limit,
|
||||
"units_remaining": effective_limit,
|
||||
"upload_cost": settings.youtube_quota_upload_cost,
|
||||
"estimated_uploads_remaining": effective_limit // settings.youtube_quota_upload_cost if settings.youtube_quota_upload_cost > 0 else -1,
|
||||
"seconds_until_reset": _seconds_until_midnight_pt(),
|
||||
"operations_count": 0,
|
||||
}
|
||||
|
||||
data = doc.to_dict()
|
||||
consumed = data.get("units_consumed", 0)
|
||||
remaining = max(0, effective_limit - consumed)
|
||||
|
||||
return {
|
||||
"date_pt": date_str,
|
||||
"units_consumed": consumed,
|
||||
"units_limit": limit,
|
||||
"effective_limit": effective_limit,
|
||||
"units_remaining": remaining,
|
||||
"upload_cost": settings.youtube_quota_upload_cost,
|
||||
"estimated_uploads_remaining": remaining // settings.youtube_quota_upload_cost if settings.youtube_quota_upload_cost > 0 else -1,
|
||||
"seconds_until_reset": _seconds_until_midnight_pt(),
|
||||
"operations_count": len(data.get("operations", [])),
|
||||
}
|
||||
|
||||
def _get_units_consumed_today(self) -> int:
|
||||
"""Get total quota units consumed today (Pacific Time)."""
|
||||
date_str = _get_today_date_pt()
|
||||
doc_ref = self.db.collection(YOUTUBE_QUOTA_COLLECTION).document(date_str)
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return 0
|
||||
|
||||
return doc.to_dict().get("units_consumed", 0)
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_youtube_quota_service: Optional[YouTubeQuotaService] = None
|
||||
|
||||
|
||||
def get_youtube_quota_service() -> YouTubeQuotaService:
|
||||
"""Get the singleton YouTubeQuotaService instance."""
|
||||
global _youtube_quota_service
|
||||
if _youtube_quota_service is None:
|
||||
_youtube_quota_service = YouTubeQuotaService()
|
||||
return _youtube_quota_service
|
||||
@@ -0,0 +1,282 @@
|
||||
"""
|
||||
YouTube upload queue service.
|
||||
|
||||
When YouTube API quota is insufficient during job completion, uploads are
|
||||
queued here instead of being silently skipped. A scheduled processor
|
||||
retries queued uploads when quota is available.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Optional, List, Dict, Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
YOUTUBE_UPLOAD_QUEUE_COLLECTION = "youtube_upload_queue"
|
||||
PACIFIC_TZ = ZoneInfo("America/Los_Angeles")
|
||||
|
||||
|
||||
class YouTubeUploadQueueService:
|
||||
"""
|
||||
Service for managing deferred YouTube uploads.
|
||||
|
||||
When quota is exhausted during job completion, uploads are queued
|
||||
and retried by a scheduled processor.
|
||||
"""
|
||||
|
||||
def __init__(self, db: Optional[firestore.Client] = None):
|
||||
if db is None:
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
else:
|
||||
self.db = db
|
||||
|
||||
def queue_upload(
|
||||
self,
|
||||
job_id: str,
|
||||
user_email: str,
|
||||
artist: str,
|
||||
title: str,
|
||||
brand_code: Optional[str],
|
||||
reason: str = "quota_exceeded",
|
||||
) -> None:
|
||||
"""
|
||||
Queue a YouTube upload for later processing.
|
||||
|
||||
Args:
|
||||
job_id: Job ID to upload
|
||||
user_email: User's email address
|
||||
artist: Artist name
|
||||
title: Song title
|
||||
brand_code: Release ID (e.g., "NOMAD-1287")
|
||||
reason: Why the upload was deferred
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
now = datetime.now(PACIFIC_TZ)
|
||||
|
||||
doc_ref.set({
|
||||
"job_id": job_id,
|
||||
"status": "queued",
|
||||
"reason": reason,
|
||||
"user_email": user_email,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"brand_code": brand_code,
|
||||
"queued_at": now,
|
||||
"attempts": 0,
|
||||
"max_attempts": 5,
|
||||
"last_error": None,
|
||||
"youtube_url": None,
|
||||
"notification_sent": False,
|
||||
"updated_at": now,
|
||||
})
|
||||
|
||||
logger.info(
|
||||
f"Queued YouTube upload for job {job_id} ({artist} - {title}), "
|
||||
f"reason: {reason}"
|
||||
)
|
||||
|
||||
def get_queued_uploads(self, limit: int = 20) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get queued uploads ordered by queued_at (oldest first).
|
||||
|
||||
Args:
|
||||
limit: Maximum number of entries to return
|
||||
|
||||
Returns:
|
||||
List of queued upload dicts
|
||||
"""
|
||||
query = (
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "queued")
|
||||
.order_by("queued_at")
|
||||
.limit(limit)
|
||||
)
|
||||
|
||||
return [doc.to_dict() for doc in query.stream()]
|
||||
|
||||
def get_all_queue_entries(self, limit: int = 50) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get all queue entries (any status) for admin dashboard.
|
||||
|
||||
Args:
|
||||
limit: Maximum entries to return
|
||||
|
||||
Returns:
|
||||
List of queue entry dicts, newest first
|
||||
"""
|
||||
query = (
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.order_by("queued_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(limit)
|
||||
)
|
||||
|
||||
return [doc.to_dict() for doc in query.stream()]
|
||||
|
||||
def mark_processing(self, job_id: str) -> bool:
|
||||
"""
|
||||
Atomically mark a queued upload as processing.
|
||||
|
||||
Uses a transaction to prevent concurrent processing.
|
||||
|
||||
Returns:
|
||||
True if successfully claimed, False if already processing/completed
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
|
||||
@firestore.transactional
|
||||
def claim_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if not doc.exists:
|
||||
return False
|
||||
|
||||
data = doc.to_dict()
|
||||
if data.get("status") != "queued":
|
||||
return False
|
||||
|
||||
attempts = data.get("attempts", 0)
|
||||
max_attempts = data.get("max_attempts", 5)
|
||||
if attempts >= max_attempts:
|
||||
transaction.update(doc_ref, {
|
||||
"status": "failed",
|
||||
"last_error": f"Max attempts ({max_attempts}) exceeded",
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
return False
|
||||
|
||||
transaction.update(doc_ref, {
|
||||
"status": "processing",
|
||||
"attempts": attempts + 1,
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
return True
|
||||
|
||||
transaction = self.db.transaction()
|
||||
return claim_in_transaction(transaction, doc_ref)
|
||||
|
||||
def mark_completed(self, job_id: str, youtube_url: str) -> None:
|
||||
"""Mark a queued upload as completed with the YouTube URL."""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
doc_ref.update({
|
||||
"status": "completed",
|
||||
"youtube_url": youtube_url,
|
||||
"completed_at": datetime.now(PACIFIC_TZ),
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
logger.info(f"YouTube upload completed for queued job {job_id}: {youtube_url}")
|
||||
|
||||
def mark_failed(self, job_id: str, error: str) -> None:
|
||||
"""
|
||||
Mark a queued upload as failed.
|
||||
|
||||
If max attempts haven't been reached, resets to 'queued' for retry.
|
||||
Uses a transaction for atomic read-then-write.
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
|
||||
@firestore.transactional
|
||||
def update_in_transaction(transaction):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
|
||||
if not doc.exists:
|
||||
return None
|
||||
|
||||
data = doc.to_dict()
|
||||
attempts = data.get("attempts", 0)
|
||||
max_attempts = data.get("max_attempts", 5)
|
||||
|
||||
new_status = "failed" if attempts >= max_attempts else "queued"
|
||||
|
||||
transaction.update(doc_ref, {
|
||||
"status": new_status,
|
||||
"last_error": error,
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
return (new_status, attempts, max_attempts)
|
||||
|
||||
transaction = self.db.transaction()
|
||||
result = update_in_transaction(transaction)
|
||||
|
||||
if result:
|
||||
new_status, attempts, max_attempts = result
|
||||
logger.warning(
|
||||
f"YouTube upload {'failed permanently' if new_status == 'failed' else 'will retry'} "
|
||||
f"for job {job_id} (attempt {attempts}/{max_attempts}): {error}"
|
||||
)
|
||||
|
||||
def retry_upload(self, job_id: str) -> bool:
|
||||
"""
|
||||
Admin manual retry: reset a failed upload back to queued.
|
||||
|
||||
Returns:
|
||||
True if reset, False if not found or not in failed/queued state
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return False
|
||||
|
||||
data = doc.to_dict()
|
||||
if data.get("status") not in ("failed", "queued"):
|
||||
return False
|
||||
|
||||
doc_ref.update({
|
||||
"status": "queued",
|
||||
"attempts": 0,
|
||||
"last_error": None,
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
logger.info(f"Admin retry: reset YouTube upload for job {job_id} to queued")
|
||||
return True
|
||||
|
||||
def get_queue_stats(self) -> Dict[str, Any]:
|
||||
"""Get queue statistics for admin dashboard."""
|
||||
queued = len(list(
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "queued")
|
||||
.select([])
|
||||
.stream()
|
||||
))
|
||||
processing = len(list(
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "processing")
|
||||
.select([])
|
||||
.stream()
|
||||
))
|
||||
failed = len(list(
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "failed")
|
||||
.select([])
|
||||
.stream()
|
||||
))
|
||||
completed = len(list(
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "completed")
|
||||
.select([])
|
||||
.stream()
|
||||
))
|
||||
|
||||
return {
|
||||
"queued": queued,
|
||||
"processing": processing,
|
||||
"failed": failed,
|
||||
"completed": completed,
|
||||
"total": queued + processing + failed + completed,
|
||||
}
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_youtube_upload_queue_service: Optional[YouTubeUploadQueueService] = None
|
||||
|
||||
|
||||
def get_youtube_upload_queue_service() -> YouTubeUploadQueueService:
|
||||
"""Get the singleton YouTubeUploadQueueService instance."""
|
||||
global _youtube_upload_queue_service
|
||||
if _youtube_upload_queue_service is None:
|
||||
_youtube_upload_queue_service = YouTubeUploadQueueService()
|
||||
return _youtube_upload_queue_service
|
||||
@@ -117,7 +117,8 @@ def mock_auth_dependency(request):
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Test admin token",
|
||||
is_admin=True
|
||||
is_admin=True,
|
||||
user_email="test@example.com",
|
||||
)
|
||||
|
||||
async def mock_require_admin():
|
||||
@@ -127,7 +128,8 @@ def mock_auth_dependency(request):
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Test admin token",
|
||||
is_admin=True
|
||||
is_admin=True,
|
||||
user_email="test@example.com",
|
||||
)
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
|
||||
@@ -75,7 +75,7 @@ class TestAudioSearchYouTubeFlow:
|
||||
}
|
||||
|
||||
# Import the route function
|
||||
from backend.api.routes.audio_search import _download_and_start_processing
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
|
||||
# Patch dependencies
|
||||
with patch(
|
||||
@@ -87,20 +87,19 @@ class TestAudioSearchYouTubeFlow:
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.storage_service',
|
||||
mock_services['storage_service']
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.worker_service',
|
||||
mock_services['worker_service']
|
||||
):
|
||||
# Create a mock audio_search_service
|
||||
mock_audio_search_service = MagicMock()
|
||||
mock_audio_search_service.is_remote_enabled = MagicMock(return_value=True)
|
||||
|
||||
# Create a mock background_tasks
|
||||
mock_background_tasks = MagicMock()
|
||||
|
||||
# Call the download function
|
||||
result = await _download_and_start_processing(
|
||||
# Call the download function (now runs as background task, returns None)
|
||||
await _download_audio_and_trigger_workers(
|
||||
job_id="test_job_123",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_search_service,
|
||||
background_tasks=mock_background_tasks,
|
||||
)
|
||||
|
||||
# Verify YouTubeDownloadService was used
|
||||
@@ -116,6 +115,7 @@ class TestAudioSearchYouTubeFlow:
|
||||
async def test_torrent_download_does_not_use_youtube_service(self, mock_youtube_service, mock_services):
|
||||
"""
|
||||
When selecting a torrent result (RED/OPS), should NOT use YouTubeDownloadService.
|
||||
Should use FlacfetchClient directly instead.
|
||||
"""
|
||||
mock_job = mock_services['job_manager'].get_job.return_value
|
||||
mock_job.status = "awaiting_audio_selection"
|
||||
@@ -131,39 +131,45 @@ class TestAudioSearchYouTubeFlow:
|
||||
'audio_search_count': 1,
|
||||
}
|
||||
|
||||
from backend.api.routes.audio_search import _download_and_start_processing
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
|
||||
# Mock audio_search_service for torrent download
|
||||
mock_audio_search_service = MagicMock()
|
||||
mock_audio_search_service.is_remote_enabled = MagicMock(return_value=True)
|
||||
mock_result = MagicMock()
|
||||
mock_result.filepath = "gs://bucket/uploads/test/audio/test.flac"
|
||||
mock_audio_search_service.download_by_id = MagicMock(return_value=mock_result)
|
||||
|
||||
# Mock FlacfetchClient for direct async download
|
||||
mock_flacfetch = MagicMock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-test-123")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/test/audio/test.flac",
|
||||
})
|
||||
|
||||
with patch(
|
||||
'backend.api.routes.audio_search.get_youtube_download_service',
|
||||
return_value=mock_youtube_service
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.get_flacfetch_client',
|
||||
return_value=mock_flacfetch
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.job_manager',
|
||||
mock_services['job_manager']
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.storage_service',
|
||||
mock_services['storage_service']
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.worker_service',
|
||||
mock_services['worker_service']
|
||||
):
|
||||
mock_background_tasks = MagicMock()
|
||||
|
||||
result = await _download_and_start_processing(
|
||||
await _download_audio_and_trigger_workers(
|
||||
job_id="test_job_123",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_search_service,
|
||||
background_tasks=mock_background_tasks,
|
||||
)
|
||||
|
||||
# YouTubeDownloadService should NOT be called for torrent
|
||||
mock_youtube_service.download_by_id.assert_not_called()
|
||||
|
||||
# audio_search_service.download_by_id should be called instead
|
||||
mock_audio_search_service.download_by_id.assert_called_once()
|
||||
# FlacfetchClient.download_by_id should be called directly
|
||||
mock_flacfetch.download_by_id.assert_called_once()
|
||||
|
||||
|
||||
class TestDirectUrlSubmissionFlow:
|
||||
|
||||
@@ -470,3 +470,107 @@ class TestDeleteOutputsGCSFinals:
|
||||
assert response.status_code == 200
|
||||
# Verify path format is jobs/{job_id}/finals/
|
||||
mock_storage.delete_folder.assert_called_once_with("jobs/abc-123-xyz/finals/")
|
||||
|
||||
|
||||
class TestDeleteOutputsBrandCodeRecycling:
|
||||
"""Tests for brand code recycling during output deletion."""
|
||||
|
||||
def test_brand_code_recycled_on_success(self, client, mock_complete_job):
|
||||
"""Test that brand code is recycled when Dropbox and GDrive cleanup succeed."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code') as mock_parse, \
|
||||
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
mock_parse.return_value = ("NOMAD", 1234)
|
||||
mock_svc = Mock()
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Brand code should be recycled (all services skip = success condition)
|
||||
assert "brand_code" in data["deleted_services"]
|
||||
assert data["deleted_services"]["brand_code"]["status"] == "recycled"
|
||||
assert data["deleted_services"]["brand_code"]["code"] == "NOMAD-1234"
|
||||
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 1234)
|
||||
|
||||
def test_brand_code_not_recycled_without_brand_code(self, client, mock_job_no_outputs):
|
||||
"""Test that no recycling happens when job has no brand code."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_no_outputs
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-456/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# No brand_code key in response since there's nothing to recycle
|
||||
assert "brand_code" not in data["deleted_services"]
|
||||
|
||||
def test_brand_code_skipped_when_dropbox_fails(self, client, mock_complete_job):
|
||||
"""Test that brand code is NOT recycled when Dropbox cleanup fails."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service') as mock_dropbox_svc:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
# Make Dropbox fail
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.side_effect = Exception("Dropbox error")
|
||||
mock_dropbox_svc.return_value = mock_dropbox
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["deleted_services"]["brand_code"]["status"] == "skipped"
|
||||
assert "incomplete" in data["deleted_services"]["brand_code"]["reason"].lower()
|
||||
|
||||
def test_brand_code_recycle_error_handled_gracefully(self, client, mock_complete_job):
|
||||
"""Test that brand code recycling errors don't crash the endpoint."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code') as mock_parse:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
# Make parse_brand_code raise an error
|
||||
mock_parse.side_effect = ValueError("Invalid brand code format")
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["deleted_services"]["brand_code"]["status"] == "failed"
|
||||
assert "Invalid brand code format" in data["deleted_services"]["brand_code"]["error"]
|
||||
+824
-118
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,396 @@
|
||||
"""
|
||||
Tests for audio_transcoding_service.py - Review audio transcoding to OGG Opus.
|
||||
|
||||
These tests mock StorageService and subprocess to verify:
|
||||
- Cache path derivation for various GCS paths
|
||||
- Cache hit path (no ffmpeg call)
|
||||
- Cache miss with successful transcode
|
||||
- Fallback to FLAC on transcoding failure
|
||||
- Bulk prepare_review_audio_for_job transcodes all expected files
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, call, ANY
|
||||
|
||||
|
||||
class TestGetCachePath:
|
||||
"""Test _get_cache_path() derivation logic."""
|
||||
|
||||
def _make_service(self):
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
return AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
def test_input_audio_path(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/abc123/input/song.flac")
|
||||
assert result == "jobs/abc123/review-audio/song.ogg"
|
||||
|
||||
def test_stem_path(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/abc123/stems/instrumental_clean.flac")
|
||||
assert result == "jobs/abc123/review-audio/instrumental_clean.ogg"
|
||||
|
||||
def test_backing_vocals_path(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/abc123/stems/backing_vocals.flac")
|
||||
assert result == "jobs/abc123/review-audio/backing_vocals.ogg"
|
||||
|
||||
def test_nested_job_path(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/4bed6f80/stems/instrumental_with_backing.flac")
|
||||
assert result == "jobs/4bed6f80/review-audio/instrumental_with_backing.ogg"
|
||||
|
||||
def test_wav_extension(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/abc123/input/song.wav")
|
||||
assert result == "jobs/abc123/review-audio/song.ogg"
|
||||
|
||||
def test_no_jobs_prefix_fallback_uses_hash(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("other/path/audio.flac")
|
||||
# Should use a hash-based fallback, not a literal "_unknown"
|
||||
assert result.startswith("jobs/_")
|
||||
assert result.endswith("/review-audio/audio.ogg")
|
||||
assert len(result.split("/")[1]) == 13 # "_" + 12-char hash
|
||||
|
||||
def test_no_jobs_prefix_different_paths_different_hashes(self):
|
||||
service = self._make_service()
|
||||
result1 = service._get_cache_path("other/path/audio.flac")
|
||||
result2 = service._get_cache_path("another/path/audio.flac")
|
||||
# Different source paths should produce different cache paths
|
||||
assert result1 != result2
|
||||
|
||||
|
||||
class TestTranscodeIfNeeded:
|
||||
"""Test transcode_if_needed() cache hit/miss logic."""
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_cache_hit_skips_transcode(self, mock_subprocess):
|
||||
"""When cached file exists, return it without transcoding."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.transcode_if_needed("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "jobs/abc/review-audio/song.ogg"
|
||||
mock_storage.file_exists.assert_called_once_with("jobs/abc/review-audio/song.ogg")
|
||||
mock_subprocess.run.assert_not_called()
|
||||
mock_storage.download_file.assert_not_called()
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_cache_miss_transcodes_and_uploads(self, mock_subprocess):
|
||||
"""When cached file is missing, download + transcode + upload."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
mock_subprocess.run.return_value = Mock(returncode=0, stderr="")
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.transcode_if_needed("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "jobs/abc/review-audio/song.ogg"
|
||||
|
||||
# Verify download from correct source path
|
||||
download_args = mock_storage.download_file.call_args[0]
|
||||
assert download_args[0] == "jobs/abc/input/song.flac"
|
||||
|
||||
# Verify ffmpeg command
|
||||
mock_subprocess.run.assert_called_once()
|
||||
ffmpeg_call = mock_subprocess.run.call_args
|
||||
ffmpeg_cmd = ffmpeg_call[0][0]
|
||||
assert "ffmpeg" in ffmpeg_cmd[0]
|
||||
assert "libopus" in ffmpeg_cmd
|
||||
assert "128k" in ffmpeg_cmd
|
||||
assert "-vn" in ffmpeg_cmd
|
||||
# Verify timeout is set
|
||||
assert ffmpeg_call[1]["timeout"] == 120
|
||||
|
||||
# Verify upload to correct cache path
|
||||
upload_args = mock_storage.upload_file.call_args[0]
|
||||
assert upload_args[1] == "jobs/abc/review-audio/song.ogg"
|
||||
|
||||
|
||||
class TestGetReviewAudioUrl:
|
||||
"""Test get_review_audio_url() with fallback behavior."""
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_returns_transcoded_url_on_success(self, mock_subprocess):
|
||||
"""On success, return signed URL for transcoded file."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.ogg"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed-url/song.ogg"
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/review-audio/song.ogg", 120
|
||||
)
|
||||
|
||||
def test_falls_back_to_flac_on_error(self):
|
||||
"""On transcoding error with no cache, fall back to original FLAC signed URL."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
mock_storage.download_file.side_effect = Exception("GCS download failed")
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.flac"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed-url/song.flac"
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/input/song.flac", 120
|
||||
)
|
||||
# file_exists called twice: once in transcode_if_needed (cache miss),
|
||||
# once in fallback (cache still missing → fall through to FLAC)
|
||||
assert mock_storage.file_exists.call_count == 2
|
||||
|
||||
def test_serves_cache_when_source_deleted(self):
|
||||
"""When source is deleted but OGG cache exists, serve the cache."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
# First file_exists (in transcode_if_needed): cache miss
|
||||
# download_file fails: source deleted
|
||||
# Second file_exists (in fallback): cache found
|
||||
mock_storage.file_exists.side_effect = [False, True]
|
||||
mock_storage.download_file.side_effect = Exception("blob not found")
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.ogg"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed-url/song.ogg"
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/review-audio/song.ogg", 120
|
||||
)
|
||||
|
||||
def test_falls_back_to_flac_when_cache_check_also_fails(self):
|
||||
"""When source is deleted and file_exists() also throws, fall back to FLAC."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
# First file_exists (in transcode_if_needed): cache miss
|
||||
# download_file fails: source deleted
|
||||
# Second file_exists (in fallback): also throws
|
||||
mock_storage.file_exists.side_effect = [False, Exception("GCS unavailable")]
|
||||
mock_storage.download_file.side_effect = Exception("blob not found")
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.flac"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed-url/song.flac"
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/input/song.flac", 120
|
||||
)
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_custom_expiration_minutes(self, mock_subprocess):
|
||||
"""Custom expiration_minutes is passed through to generate_signed_url."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.ogg"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
service.get_review_audio_url("jobs/abc/input/song.flac", expiration_minutes=60)
|
||||
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/review-audio/song.ogg", 60
|
||||
)
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_falls_back_on_ffmpeg_failure(self, mock_subprocess):
|
||||
"""On ffmpeg failure, fall back to original FLAC signed URL."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
mock_subprocess.run.return_value = Mock(returncode=1, stderr="codec error")
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
# Should fall back to FLAC URL
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/input/song.flac", 120
|
||||
)
|
||||
|
||||
|
||||
class TestPrepareReviewAudioForJob:
|
||||
"""Test prepare_review_audio_for_job() bulk transcoding."""
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_transcodes_all_expected_files(self, mock_subprocess):
|
||||
"""Should transcode input + all stems and return correct cache paths."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True # All cache hits
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.file_urls = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/abc123/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/abc123/stems/instrumental_with_backing.flac",
|
||||
"backing_vocals": "jobs/abc123/stems/backing_vocals.flac",
|
||||
}
|
||||
}
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
assert len(result) == 4
|
||||
assert "jobs/abc123/review-audio/song.ogg" in result
|
||||
assert "jobs/abc123/review-audio/instrumental_clean.ogg" in result
|
||||
assert "jobs/abc123/review-audio/instrumental_with_backing.ogg" in result
|
||||
assert "jobs/abc123/review-audio/backing_vocals.ogg" in result
|
||||
assert mock_storage.file_exists.call_count == 4
|
||||
# No ffmpeg calls since all are cache hits
|
||||
mock_subprocess.run.assert_not_called()
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_continues_on_individual_failure(self, mock_subprocess):
|
||||
"""If one file fails to transcode, others should still succeed."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
# First call (input): cache miss + download fails
|
||||
# Subsequent calls: cache hits
|
||||
mock_storage.file_exists.side_effect = [False, True, True, True]
|
||||
mock_storage.download_file.side_effect = Exception("download failed")
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.file_urls = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/abc123/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/abc123/stems/instrumental_with_backing.flac",
|
||||
"backing_vocals": "jobs/abc123/stems/backing_vocals.flac",
|
||||
}
|
||||
}
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
# 3 out of 4 succeeded (the 3 cache hits)
|
||||
assert len(result) == 3
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_handles_missing_stems(self, mock_subprocess):
|
||||
"""Should handle jobs with missing stem paths gracefully."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.file_urls = {"stems": {}} # No stems
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
# Only the input audio
|
||||
assert len(result) == 1
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_handles_no_input_audio(self, mock_subprocess):
|
||||
"""Should handle jobs with no input_media_gcs_path."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = None
|
||||
mock_job.file_urls = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/abc123/stems/instrumental_clean.flac",
|
||||
}
|
||||
}
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_handles_no_stems_key(self, mock_subprocess):
|
||||
"""Should handle jobs where file_urls has no stems key at all."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.file_urls = {} # No stems key
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0] == "jobs/abc123/review-audio/song.ogg"
|
||||
|
||||
|
||||
class TestInit:
|
||||
"""Test AudioTranscodingService initialization."""
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.StorageService")
|
||||
def test_creates_default_storage_service(self, mock_storage_class):
|
||||
"""Creates a StorageService when none is provided."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
service = AudioTranscodingService()
|
||||
|
||||
mock_storage_class.assert_called_once()
|
||||
assert service.storage is mock_storage_class.return_value
|
||||
|
||||
def test_uses_provided_storage_service(self):
|
||||
"""Uses the provided storage service instead of creating one."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
assert service.storage is mock_storage
|
||||
|
||||
|
||||
class TestGetReviewAudioUrlAsync:
|
||||
"""Test async wrapper."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
async def test_async_wrapper_delegates(self, mock_subprocess):
|
||||
"""Async wrapper should call sync method via to_thread."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed/url"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = await service.get_review_audio_url_async("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed/url"
|
||||
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
Tests for download_audio() upload persistence in audio_worker.py.
|
||||
|
||||
Verifies that uploaded files (uploads/ prefix) are copied to jobs/ prefix
|
||||
so they survive the 7-day GCS lifecycle rule on uploads/.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, AsyncMock
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
async def test_upload_persisted_to_jobs_prefix(MockJobManager):
|
||||
"""Uploaded audio (uploads/ prefix) should be copied to jobs/{id}/input/."""
|
||||
from backend.workers.audio_worker import download_audio
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_jm = Mock()
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.input_media_gcs_path = "uploads/abc123/audio/My Song.flac"
|
||||
mock_job.filename = "My Song.flac"
|
||||
mock_job.url = None
|
||||
mock_job.file_urls = {}
|
||||
|
||||
result = await download_audio(
|
||||
job_id="abc123",
|
||||
temp_dir="/tmp/test",
|
||||
storage=mock_storage,
|
||||
job=mock_job,
|
||||
job_manager_instance=mock_jm,
|
||||
)
|
||||
|
||||
# Should download from original upload path
|
||||
mock_storage.download_file.assert_called_once_with(
|
||||
"uploads/abc123/audio/My Song.flac", os.path.join("/tmp/test", "My Song.flac")
|
||||
)
|
||||
|
||||
# Should re-upload to persistent jobs/ path
|
||||
mock_storage.upload_file.assert_called_once_with(
|
||||
os.path.join("/tmp/test", "My Song.flac"),
|
||||
"jobs/abc123/input/My Song.flac",
|
||||
)
|
||||
|
||||
# Should update job metadata
|
||||
mock_jm.update_job.assert_called_once_with(
|
||||
"abc123", {"input_media_gcs_path": "jobs/abc123/input/My Song.flac"}
|
||||
)
|
||||
mock_jm.update_file_url.assert_called_once_with(
|
||||
"abc123", "input", "audio", "jobs/abc123/input/My Song.flac"
|
||||
)
|
||||
|
||||
assert result == os.path.join("/tmp/test", "My Song.flac")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
async def test_jobs_prefix_not_re_persisted(MockJobManager):
|
||||
"""Files already in jobs/ prefix should NOT be re-uploaded."""
|
||||
from backend.workers.audio_worker import download_audio
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_jm = Mock()
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.filename = "song.flac"
|
||||
mock_job.url = None
|
||||
mock_job.file_urls = {}
|
||||
|
||||
result = await download_audio(
|
||||
job_id="abc123",
|
||||
temp_dir="/tmp/test",
|
||||
storage=mock_storage,
|
||||
job=mock_job,
|
||||
job_manager_instance=mock_jm,
|
||||
)
|
||||
|
||||
# Should download but NOT re-upload
|
||||
mock_storage.download_file.assert_called_once()
|
||||
mock_storage.upload_file.assert_not_called()
|
||||
mock_jm.update_job.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
async def test_upload_persistence_creates_job_manager_if_none(MockJobManager):
|
||||
"""If no job_manager_instance provided, creates one for persistence."""
|
||||
from backend.workers.audio_worker import download_audio
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_jm_instance = Mock()
|
||||
MockJobManager.return_value = mock_jm_instance
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.input_media_gcs_path = "uploads/def456/audio/track.flac"
|
||||
mock_job.filename = "track.flac"
|
||||
mock_job.url = None
|
||||
mock_job.file_urls = {}
|
||||
|
||||
await download_audio(
|
||||
job_id="def456",
|
||||
temp_dir="/tmp/test",
|
||||
storage=mock_storage,
|
||||
job=mock_job,
|
||||
job_manager_instance=None,
|
||||
)
|
||||
|
||||
# Should have created a JobManager
|
||||
MockJobManager.assert_called_once()
|
||||
# Should use the created instance
|
||||
mock_jm_instance.update_job.assert_called_once()
|
||||
mock_jm_instance.update_file_url.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
async def test_persistence_failure_does_not_block_download(MockJobManager):
|
||||
"""If upload_file fails during persistence, download still succeeds."""
|
||||
from backend.workers.audio_worker import download_audio
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.upload_file.side_effect = Exception("GCS upload failed")
|
||||
mock_jm = Mock()
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.input_media_gcs_path = "uploads/abc123/audio/song.flac"
|
||||
mock_job.filename = "song.flac"
|
||||
mock_job.url = None
|
||||
mock_job.file_urls = {}
|
||||
|
||||
result = await download_audio(
|
||||
job_id="abc123",
|
||||
temp_dir="/tmp/test",
|
||||
storage=mock_storage,
|
||||
job=mock_job,
|
||||
job_manager_instance=mock_jm,
|
||||
)
|
||||
|
||||
# Download succeeded despite persistence failure
|
||||
assert result == os.path.join("/tmp/test", "song.flac")
|
||||
mock_storage.download_file.assert_called_once()
|
||||
# upload_file was attempted but failed
|
||||
mock_storage.upload_file.assert_called_once()
|
||||
# Metadata update should NOT have been called (upload failed first)
|
||||
mock_jm.update_job.assert_not_called()
|
||||
@@ -32,6 +32,35 @@ class TestAuthServiceBasics:
|
||||
assert hasattr(AuthService, 'validate_token') or hasattr(AuthService, 'verify_token')
|
||||
|
||||
|
||||
class TestIncrementTokenUsage:
|
||||
"""Tests for increment_token_usage after credit deduction cleanup."""
|
||||
|
||||
def test_session_token_does_not_deduct_credits(self):
|
||||
"""
|
||||
Verify that increment_token_usage does NOT deduct credits for session tokens.
|
||||
|
||||
Credit deduction is handled by JobManager.create_job(), not here.
|
||||
This test ensures the dead code removal didn't break the method.
|
||||
"""
|
||||
mock_firestore = MagicMock()
|
||||
# Session token: not in admin_tokens, not in Firestore auth_tokens
|
||||
mock_firestore.get_token.return_value = None
|
||||
|
||||
with patch('backend.services.auth_service.FirestoreService', return_value=mock_firestore), \
|
||||
patch.dict('os.environ', {'ADMIN_TOKENS': 'admin-token'}):
|
||||
from backend.services.auth_service import AuthService
|
||||
service = AuthService()
|
||||
|
||||
# Mock validate_token to return valid session user
|
||||
with patch.object(service, 'validate_token', return_value=(True, 'stripe', 5, 'OK')):
|
||||
result = service.increment_token_usage("session-token-123", "job-abc")
|
||||
|
||||
# Should return True (no-op for session tokens)
|
||||
assert result is True
|
||||
# Should NOT try to deduct credits via user_service
|
||||
# (If it did, it would fail since user_service is not mocked)
|
||||
|
||||
|
||||
class TestFirestoreServiceBasics:
|
||||
"""Basic tests for FirestoreService."""
|
||||
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
"""
|
||||
Tests for BrandCodeService - atomic brand code allocation via Firestore counters.
|
||||
|
||||
Tests cover:
|
||||
- Sequential allocation returns unique codes
|
||||
- Recycled numbers are reused (smallest first)
|
||||
- One-time initialization from Dropbox scan
|
||||
- Both NOMAD and NOMADNP prefixes work independently
|
||||
- Recycle then allocate round-trip
|
||||
- parse_brand_code utility
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.storage', MagicMock())
|
||||
|
||||
|
||||
def _make_doc_snapshot(exists, data=None):
|
||||
"""Create a mock Firestore document snapshot."""
|
||||
doc = Mock()
|
||||
doc.exists = exists
|
||||
if data:
|
||||
doc.to_dict.return_value = data
|
||||
return doc
|
||||
|
||||
|
||||
def _setup_service_and_mocks(mock_db, doc_snapshot):
|
||||
"""Common setup: create service with fake transactional decorator."""
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_doc_ref.get.return_value = doc_snapshot
|
||||
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
return mock_doc_ref, mock_transaction
|
||||
|
||||
|
||||
class TestBrandCodeServiceAllocate:
|
||||
"""Test allocate_brand_code method."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_allocate_sequential_number(self, mock_db):
|
||||
"""Test allocation returns next sequential number when no recycled numbers."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMAD", "/Karaoke/Tracks-Organized")
|
||||
|
||||
assert result == "NOMAD-1264"
|
||||
# Transaction.update should have been called to increment next_number
|
||||
mock_transaction.update.assert_called_once()
|
||||
update_args = mock_transaction.update.call_args[0]
|
||||
assert update_args[0] is mock_doc_ref # first arg is doc_ref
|
||||
assert update_args[1]["next_number"] == 1265
|
||||
|
||||
def test_allocate_uses_recycled_number(self, mock_db):
|
||||
"""Test allocation pops smallest recycled number first."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1250, 1230, 1245],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMAD", "/path")
|
||||
|
||||
assert result == "NOMAD-1230"
|
||||
# Verify recycled list was updated (1230 removed, sorted remainder)
|
||||
update_args = mock_transaction.update.call_args[0][1]
|
||||
assert update_args["recycled"] == [1245, 1250]
|
||||
|
||||
def test_allocate_initializes_from_dropbox_when_no_counter(self, mock_db):
|
||||
"""Test first allocation scans Dropbox and creates counter doc."""
|
||||
doc_snapshot = _make_doc_snapshot(False)
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
with patch.object(svc, '_get_initial_next_number', return_value=1264):
|
||||
result = svc.allocate_brand_code("NOMAD", "/Karaoke/Tracks-Organized")
|
||||
|
||||
assert result == "NOMAD-1264"
|
||||
# Verify counter doc was created via transaction.set
|
||||
mock_transaction.set.assert_called_once()
|
||||
set_args = mock_transaction.set.call_args[0]
|
||||
assert set_args[0] is mock_doc_ref
|
||||
assert set_args[1]["prefix"] == "NOMAD"
|
||||
assert set_args[1]["next_number"] == 1265
|
||||
assert set_args[1]["recycled"] == []
|
||||
|
||||
def test_allocate_nomadnp_prefix(self, mock_db):
|
||||
"""Test NOMADNP prefix works independently."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMADNP",
|
||||
"next_number": 13,
|
||||
"recycled": [],
|
||||
})
|
||||
_setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMADNP", "/Karaoke/NP")
|
||||
|
||||
assert result == "NOMADNP-0013"
|
||||
mock_db.collection.assert_called_with("brand_code_counters")
|
||||
mock_db.collection.return_value.document.assert_called_with("NOMADNP")
|
||||
|
||||
def test_allocate_formats_with_leading_zeros(self, mock_db):
|
||||
"""Test brand codes are zero-padded to 4 digits."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMADNP",
|
||||
"next_number": 5,
|
||||
"recycled": [],
|
||||
})
|
||||
_setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMADNP", "/path")
|
||||
|
||||
assert result == "NOMADNP-0005"
|
||||
|
||||
|
||||
class TestBrandCodeServiceRecycle:
|
||||
"""Test recycle_brand_code method."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_recycle_adds_number_to_pool(self, mock_db):
|
||||
"""Test recycling adds number to the recycled list."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1250],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 1230)
|
||||
|
||||
update_args = mock_transaction.update.call_args[0][1]
|
||||
assert 1230 in update_args["recycled"]
|
||||
assert 1250 in update_args["recycled"]
|
||||
|
||||
def test_recycle_rejects_number_at_or_above_next(self, mock_db):
|
||||
"""Test recycling a number >= next_number is rejected."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
# Number equal to next_number — hasn't been allocated yet
|
||||
svc.recycle_brand_code("NOMAD", 1264)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
def test_recycle_rejects_zero_or_negative(self, mock_db):
|
||||
"""Test recycling zero or negative numbers is rejected."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 0)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
def test_recycle_skips_duplicate(self, mock_db):
|
||||
"""Test recycling a number already in the pool doesn't duplicate it."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1250],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 1250)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
def test_recycle_no_counter_doc_logs_warning(self, mock_db):
|
||||
"""Test recycling when counter doc doesn't exist logs warning and returns."""
|
||||
doc_snapshot = _make_doc_snapshot(False)
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 1230)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
mock_transaction.set.assert_not_called()
|
||||
|
||||
|
||||
class TestBrandCodeServiceRecycleRoundTrip:
|
||||
"""Test recycle-then-allocate round trip."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_recycle_then_allocate_reuses_number(self, mock_db):
|
||||
"""Test that a recycled number is returned on next allocation."""
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
# Step 1: Recycle number 1230
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
svc.recycle_brand_code("NOMAD", 1230)
|
||||
|
||||
# Step 2: Allocate — should get recycled 1230
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1230],
|
||||
})
|
||||
result = svc.allocate_brand_code("NOMAD", "/path")
|
||||
|
||||
assert result == "NOMAD-1230"
|
||||
|
||||
|
||||
class TestInitializeFromDropbox:
|
||||
"""Test _get_initial_next_number."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_init_from_dropbox_finds_max(self, mock_db):
|
||||
"""Test initialization finds the max existing number and adds 1."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.list_folders.return_value = [
|
||||
"NOMAD-1260 - Artist A - Song A",
|
||||
"NOMAD-1261 - Artist B - Song B",
|
||||
"NOMAD-1263 - Artist C - Song C",
|
||||
"Some Other Folder",
|
||||
]
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMAD", "/Karaoke/Tracks-Organized")
|
||||
|
||||
assert result == 1264 # max(1260, 1261, 1263) + 1
|
||||
|
||||
def test_init_from_dropbox_no_existing(self, mock_db):
|
||||
"""Test initialization returns 1 when no existing codes found."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.list_folders.return_value = ["Some Random Folder"]
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMAD", "/path")
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_init_from_dropbox_not_configured(self, mock_db):
|
||||
"""Test initialization returns 1 when Dropbox not configured."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = False
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMAD", "/path")
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_init_nomadnp_prefix_independent(self, mock_db):
|
||||
"""Test NOMADNP initialization only finds NOMADNP codes, not NOMAD."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.list_folders.return_value = [
|
||||
"NOMADNP-0010 - Artist A",
|
||||
"NOMADNP-0012 - Artist B",
|
||||
"NOMAD-1263 - Artist C", # Should NOT match NOMADNP prefix
|
||||
]
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMADNP", "/Karaoke/NP")
|
||||
|
||||
assert result == 13 # max(10, 12) + 1
|
||||
|
||||
|
||||
class TestParseBrandCode:
|
||||
"""Test parse_brand_code static method."""
|
||||
|
||||
def test_parse_nomad_code(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMAD-1234")
|
||||
assert prefix == "NOMAD"
|
||||
assert number == 1234
|
||||
|
||||
def test_parse_nomadnp_code(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMADNP-0012")
|
||||
assert prefix == "NOMADNP"
|
||||
assert number == 12
|
||||
|
||||
def test_parse_leading_zeros(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMAD-0001")
|
||||
assert prefix == "NOMAD"
|
||||
assert number == 1
|
||||
|
||||
def test_parse_invalid_format_raises(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
with pytest.raises(ValueError, match="Invalid brand code format"):
|
||||
BrandCodeService.parse_brand_code("invalid")
|
||||
|
||||
def test_parse_no_dash_raises(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
with pytest.raises(ValueError, match="Invalid brand code format"):
|
||||
BrandCodeService.parse_brand_code("NOMAD1234")
|
||||
|
||||
def test_parse_lowercase_raises(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
with pytest.raises(ValueError, match="Invalid brand code format"):
|
||||
BrandCodeService.parse_brand_code("nomad-1234")
|
||||
|
||||
|
||||
class TestCleanupDistributionRecycling:
|
||||
"""Test that cleanup_distribution endpoint recycles brand codes correctly."""
|
||||
|
||||
def test_parse_and_recycle_nomad_brand_code(self):
|
||||
"""Test that a NOMAD brand code is correctly parsed and recycled."""
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMAD-1234")
|
||||
assert prefix == "NOMAD"
|
||||
assert number == 1234
|
||||
|
||||
def test_parse_and_recycle_nomadnp_brand_code(self):
|
||||
"""Test that a NOMADNP brand code is correctly parsed and recycled."""
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMADNP-0012")
|
||||
assert prefix == "NOMADNP"
|
||||
assert number == 12
|
||||
|
||||
def test_recycle_called_after_successful_dropbox_delete(self):
|
||||
"""Test the integration pattern: parse brand code, then recycle the number."""
|
||||
mock_db = MagicMock()
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
# Simulate what cleanup_distribution does:
|
||||
# 1. Parse the brand code
|
||||
brand_code = "NOMAD-1234"
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
# 2. Recycle it
|
||||
svc.recycle_brand_code(prefix, number)
|
||||
|
||||
# Verify transaction.update was called to add 1234 to recycled pool
|
||||
mock_transaction.update.assert_called_once()
|
||||
update_args = mock_transaction.update.call_args[0][1]
|
||||
assert 1234 in update_args["recycled"]
|
||||
|
||||
def test_recycle_failure_does_not_raise(self):
|
||||
"""Test that recycling a brand code with no counter doc doesn't raise."""
|
||||
mock_db = MagicMock()
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(False)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
# Should not raise — cleanup should be resilient
|
||||
svc.recycle_brand_code("NOMAD", 1234)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
|
||||
class TestGetBrandCodeService:
|
||||
"""Test singleton getter."""
|
||||
|
||||
def test_returns_same_instance(self):
|
||||
"""Test get_brand_code_service returns singleton."""
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
import backend.services.brand_code_service as module
|
||||
# Reset singleton
|
||||
module._brand_code_service = None
|
||||
|
||||
svc1 = module.get_brand_code_service()
|
||||
svc2 = module.get_brand_code_service()
|
||||
assert svc1 is svc2
|
||||
|
||||
# Clean up
|
||||
module._brand_code_service = None
|
||||
@@ -0,0 +1,194 @@
|
||||
"""
|
||||
Tests for catalog API routes — proxy endpoints and community check.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Test client with mocked auth."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers():
|
||||
"""Headers for authenticated requests."""
|
||||
return {"Authorization": "Bearer test-admin-token"}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_rate_limits():
|
||||
"""Clear rate limit state between tests."""
|
||||
from backend.api.routes.catalog import _rate_limit_windows
|
||||
_rate_limit_windows.clear()
|
||||
yield
|
||||
_rate_limit_windows.clear()
|
||||
|
||||
|
||||
# --- Artist search ---
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_artists", new_callable=AsyncMock)
|
||||
def test_search_artists_returns_results(mock_search, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_search.return_value = [
|
||||
{"name": "Fleetwood Mac", "mbid": "abc-123", "popularity": 85},
|
||||
{"name": "Fleet Foxes", "mbid": "def-456", "popularity": 72},
|
||||
]
|
||||
|
||||
response = client.get("/api/catalog/artists?q=flee", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) == 2
|
||||
assert data[0]["name"] == "Fleetwood Mac"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_artists", new_callable=AsyncMock)
|
||||
def test_search_artists_empty_results(mock_search, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_search.return_value = []
|
||||
|
||||
response = client.get("/api/catalog/artists?q=zzzzz", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == []
|
||||
|
||||
|
||||
def test_search_artists_requires_min_query_length(client, auth_headers):
|
||||
response = client.get("/api/catalog/artists?q=a", headers=auth_headers)
|
||||
assert response.status_code == 422 # Validation error
|
||||
|
||||
|
||||
# --- Track search ---
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_tracks", new_callable=AsyncMock)
|
||||
def test_search_tracks_returns_results(mock_search, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_search.return_value = [
|
||||
{"track_name": "Dreams", "artist_name": "Fleetwood Mac", "popularity": 82},
|
||||
]
|
||||
|
||||
response = client.get("/api/catalog/tracks?q=dreams", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) == 1
|
||||
assert data[0]["track_name"] == "Dreams"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_tracks", new_callable=AsyncMock)
|
||||
def test_search_tracks_with_artist_filter(mock_search, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_search.return_value = []
|
||||
|
||||
response = client.get(
|
||||
"/api/catalog/tracks?q=dreams&artist=Fleetwood+Mac",
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
mock_search.assert_called_once_with("dreams", "Fleetwood Mac", 10)
|
||||
|
||||
|
||||
# --- Community check ---
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.karaokenerds_service.check_community_versions", new_callable=AsyncMock)
|
||||
def test_community_check_found(mock_check, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_check.return_value = {
|
||||
"has_community": True,
|
||||
"songs": [
|
||||
{
|
||||
"title": "Dreams",
|
||||
"artist": "Fleetwood Mac",
|
||||
"community_tracks": [
|
||||
{
|
||||
"brand_name": "Karaoke Version",
|
||||
"brand_code": "KV",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=abc",
|
||||
"is_community": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
"best_youtube_url": "https://www.youtube.com/watch?v=abc",
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
"/api/catalog/community-check",
|
||||
json={"artist": "Fleetwood Mac", "title": "Dreams"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["has_community"] is True
|
||||
assert len(data["songs"]) == 1
|
||||
assert data["best_youtube_url"] == "https://www.youtube.com/watch?v=abc"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.karaokenerds_service.check_community_versions", new_callable=AsyncMock)
|
||||
def test_community_check_not_found(mock_check, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_check.return_value = {
|
||||
"has_community": False,
|
||||
"songs": [],
|
||||
"best_youtube_url": None,
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
"/api/catalog/community-check",
|
||||
json={"artist": "Unknown Artist", "title": "Unknown Song"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["has_community"] is False
|
||||
|
||||
|
||||
def test_community_check_validation_error(client, auth_headers):
|
||||
response = client.post(
|
||||
"/api/catalog/community-check",
|
||||
json={"artist": "", "title": "Dreams"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
# --- Rate limiting ---
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_artists", new_callable=AsyncMock)
|
||||
def test_rate_limit_enforced(mock_search, mock_auth, client, auth_headers):
|
||||
"""Rate limit allows up to 20 requests per minute, then returns 429."""
|
||||
# Use a unique email so other tests' requests don't interfere
|
||||
unique_email = "ratelimit-unique-test@test.com"
|
||||
mock_auth.return_value = MagicMock(user_email=unique_email, token_id="test")
|
||||
mock_search.return_value = []
|
||||
|
||||
# Clear any existing rate limit state for this user
|
||||
from backend.api.routes.catalog import _rate_limit_windows
|
||||
_rate_limit_windows.pop(unique_email, None)
|
||||
|
||||
# First 20 requests should succeed
|
||||
for i in range(20):
|
||||
resp = client.get("/api/catalog/artists?q=test", headers=auth_headers)
|
||||
assert resp.status_code == 200, f"Request {i+1}/20 failed with {resp.status_code}"
|
||||
|
||||
# 21st request should be rate limited
|
||||
resp = client.get("/api/catalog/artists?q=test", headers=auth_headers)
|
||||
assert resp.status_code == 429
|
||||
assert "Rate limit exceeded" in resp.json()["detail"]
|
||||
|
||||
# Clean up
|
||||
_rate_limit_windows.pop(unique_email, None)
|
||||
@@ -0,0 +1,249 @@
|
||||
"""
|
||||
Tests for CDG countdown handling.
|
||||
|
||||
Tests cover:
|
||||
- _remove_countdown_from_lyrics() helper method
|
||||
- CDG generation with countdown-padded LRC files
|
||||
- Timestamp adjustment for instrumental audio sync
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
|
||||
|
||||
|
||||
class TestCDGCountdownRemoval:
|
||||
"""Test the _remove_countdown_from_lyrics helper method."""
|
||||
|
||||
@pytest.fixture
|
||||
def generator(self, tmp_path):
|
||||
"""Create a CDGGenerator instance for testing."""
|
||||
return CDGGenerator(output_dir=str(tmp_path))
|
||||
|
||||
def test_removes_countdown_segment(self, generator):
|
||||
"""Test that countdown segment is removed from lyrics data."""
|
||||
# Simulated LRC data with countdown at 0.1s and first word at 3.6s
|
||||
lyrics_data = [
|
||||
{"timestamp": 10, "text": "3... 2... 1..."}, # 0.1s = 10 centiseconds
|
||||
{"timestamp": 360, "text": "IF"}, # 3.6s = 360 centiseconds
|
||||
{"timestamp": 380, "text": "YOU"},
|
||||
{"timestamp": 624, "text": "COULD"},
|
||||
]
|
||||
|
||||
# Remove 3 second countdown padding
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# Countdown segment should be removed (timestamp < 300cs)
|
||||
assert len(result) == 3
|
||||
assert result[0]["text"] == "IF"
|
||||
|
||||
# Timestamps should be shifted back by 300cs (3 seconds)
|
||||
assert result[0]["timestamp"] == 60 # 360 - 300
|
||||
assert result[1]["timestamp"] == 80 # 380 - 300
|
||||
assert result[2]["timestamp"] == 324 # 624 - 300
|
||||
|
||||
def test_handles_multiple_countdown_segments(self, generator):
|
||||
"""Test with multiple early segments (e.g., multi-part countdown)."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 10, "text": "3"},
|
||||
{"timestamp": 100, "text": "2"},
|
||||
{"timestamp": 200, "text": "1"},
|
||||
{"timestamp": 360, "text": "HELLO"},
|
||||
{"timestamp": 500, "text": "WORLD"},
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# All segments before 300cs should be removed
|
||||
assert len(result) == 2
|
||||
assert result[0]["text"] == "HELLO"
|
||||
assert result[0]["timestamp"] == 60 # 360 - 300
|
||||
assert result[1]["text"] == "WORLD"
|
||||
assert result[1]["timestamp"] == 200 # 500 - 300
|
||||
|
||||
def test_handles_no_countdown_segment(self, generator):
|
||||
"""Test when LRC has no countdown segment but flag is set."""
|
||||
# All timestamps are after the countdown duration
|
||||
lyrics_data = [
|
||||
{"timestamp": 400, "text": "FIRST"},
|
||||
{"timestamp": 500, "text": "SECOND"},
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# Should still shift timestamps back
|
||||
assert len(result) == 2
|
||||
assert result[0]["timestamp"] == 100 # 400 - 300
|
||||
assert result[1]["timestamp"] == 200 # 500 - 300
|
||||
|
||||
def test_handles_different_padding_durations(self, generator):
|
||||
"""Test with different countdown padding durations."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 50, "text": "COUNTDOWN"}, # 0.5s
|
||||
{"timestamp": 560, "text": "WORD"}, # 5.6s
|
||||
]
|
||||
|
||||
# With 5s padding (500cs)
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 5.0)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0]["text"] == "WORD"
|
||||
assert result[0]["timestamp"] == 60 # 560 - 500
|
||||
|
||||
def test_preserves_text_unchanged(self, generator):
|
||||
"""Test that text content is preserved exactly."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 10, "text": "3... 2... 1..."},
|
||||
{"timestamp": 360, "text": "HELLO, WORLD!"},
|
||||
{"timestamp": 500, "text": "IT'S ME"},
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
assert result[0]["text"] == "HELLO, WORLD!"
|
||||
assert result[1]["text"] == "IT'S ME"
|
||||
|
||||
def test_empty_lyrics_list(self, generator):
|
||||
"""Test with empty lyrics list."""
|
||||
result = generator._remove_countdown_from_lyrics([], 3.0)
|
||||
assert result == []
|
||||
|
||||
def test_all_segments_in_countdown_period(self, generator):
|
||||
"""Test when all segments are within countdown period."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 10, "text": "A"},
|
||||
{"timestamp": 100, "text": "B"},
|
||||
{"timestamp": 200, "text": "C"},
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# All segments removed - should return empty after shifting
|
||||
assert len(result) == 0
|
||||
|
||||
def test_segment_exactly_at_boundary(self, generator):
|
||||
"""Test with segment timestamp exactly at countdown boundary."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 299, "text": "ALMOST"}, # Just before 3s
|
||||
{"timestamp": 300, "text": "EXACTLY"}, # Exactly at 3s
|
||||
{"timestamp": 301, "text": "AFTER"}, # Just after 3s
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# timestamp < countdown_cs means 299 is removed, 300 and 301 stay
|
||||
assert len(result) == 2
|
||||
assert result[0]["text"] == "EXACTLY"
|
||||
assert result[0]["timestamp"] == 0 # 300 - 300
|
||||
assert result[1]["text"] == "AFTER"
|
||||
assert result[1]["timestamp"] == 1 # 301 - 300
|
||||
|
||||
def test_fractional_countdown_duration(self, generator):
|
||||
"""Test with fractional countdown duration (e.g., 3.5 seconds)."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 100, "text": "EARLY"}, # 1s
|
||||
{"timestamp": 340, "text": "MIDDLE"}, # 3.4s - still in countdown
|
||||
{"timestamp": 360, "text": "AFTER"}, # 3.6s - after 3.5s
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.5)
|
||||
|
||||
# 350cs boundary
|
||||
assert len(result) == 1
|
||||
assert result[0]["text"] == "AFTER"
|
||||
assert result[0]["timestamp"] == 10 # 360 - 350
|
||||
|
||||
|
||||
class TestCDGGenerateFromLRCWithCountdown:
|
||||
"""Test generate_cdg_from_lrc with countdown parameters."""
|
||||
|
||||
@pytest.fixture
|
||||
def generator(self, tmp_path):
|
||||
"""Create a CDGGenerator instance for testing."""
|
||||
return CDGGenerator(output_dir=str(tmp_path))
|
||||
|
||||
def test_passes_countdown_params_to_parse(self, generator, tmp_path, mocker):
|
||||
"""Test that countdown params are used when processing LRC."""
|
||||
# Create a test LRC file with countdown
|
||||
lrc_file = tmp_path / "test.lrc"
|
||||
lrc_file.write_text("""[re:MidiCo]
|
||||
[00:00.100]1:/3... 2... 1...
|
||||
[00:03.600]1:/If
|
||||
[00:03.800]1:you
|
||||
""")
|
||||
|
||||
audio_file = tmp_path / "test.flac"
|
||||
audio_file.write_text("fake audio")
|
||||
|
||||
# Mock the methods that would actually generate the CDG
|
||||
mock_remove = mocker.patch.object(
|
||||
generator, "_remove_countdown_from_lyrics", wraps=generator._remove_countdown_from_lyrics
|
||||
)
|
||||
mocker.patch.object(generator, "_validate_and_setup_font")
|
||||
mocker.patch.object(generator, "_create_toml_file", return_value=str(tmp_path / "test.toml"))
|
||||
mocker.patch.object(generator, "_compose_cdg")
|
||||
mocker.patch.object(generator, "_find_cdg_zip", return_value=str(tmp_path / "test.zip"))
|
||||
mocker.patch.object(generator, "_extract_cdg_files")
|
||||
mocker.patch.object(generator, "_get_cdg_path", return_value=str(tmp_path / "test.cdg"))
|
||||
mocker.patch.object(generator, "_get_mp3_path", return_value=str(tmp_path / "test.mp3"))
|
||||
mocker.patch.object(generator, "_verify_output_files")
|
||||
|
||||
# Create mock files
|
||||
(tmp_path / "test.toml").write_text("")
|
||||
(tmp_path / "test.zip").write_text("")
|
||||
(tmp_path / "test.cdg").write_text("")
|
||||
(tmp_path / "test.mp3").write_text("")
|
||||
|
||||
# Call with countdown padding enabled
|
||||
generator.generate_cdg_from_lrc(
|
||||
lrc_file=str(lrc_file),
|
||||
audio_file=str(audio_file),
|
||||
title="Test",
|
||||
artist="Artist",
|
||||
cdg_styles={"font_path": None}, # Minimal styles to avoid validation
|
||||
lrc_has_countdown_padding=True,
|
||||
countdown_padding_seconds=3.0,
|
||||
)
|
||||
|
||||
# Verify _remove_countdown_from_lyrics was called
|
||||
mock_remove.assert_called_once()
|
||||
# The method is called with (lyrics_data, countdown_padding_seconds)
|
||||
call_args = mock_remove.call_args
|
||||
# Check positional args - second arg should be countdown_padding_seconds
|
||||
assert call_args[0][1] == 3.0
|
||||
|
||||
def test_skips_countdown_processing_when_disabled(self, generator, tmp_path, mocker):
|
||||
"""Test that countdown processing is skipped when flag is False."""
|
||||
lrc_file = tmp_path / "test.lrc"
|
||||
lrc_file.write_text("[00:03.600]1:/Test\n")
|
||||
|
||||
audio_file = tmp_path / "test.flac"
|
||||
audio_file.write_text("fake audio")
|
||||
|
||||
mock_remove = mocker.patch.object(generator, "_remove_countdown_from_lyrics")
|
||||
mocker.patch.object(generator, "_validate_and_setup_font")
|
||||
mocker.patch.object(generator, "_create_toml_file", return_value=str(tmp_path / "test.toml"))
|
||||
mocker.patch.object(generator, "_compose_cdg")
|
||||
mocker.patch.object(generator, "_find_cdg_zip", return_value=str(tmp_path / "test.zip"))
|
||||
mocker.patch.object(generator, "_extract_cdg_files")
|
||||
mocker.patch.object(generator, "_get_cdg_path", return_value=str(tmp_path / "test.cdg"))
|
||||
mocker.patch.object(generator, "_get_mp3_path", return_value=str(tmp_path / "test.mp3"))
|
||||
mocker.patch.object(generator, "_verify_output_files")
|
||||
|
||||
# Create mock files
|
||||
(tmp_path / "test.toml").write_text("")
|
||||
(tmp_path / "test.zip").write_text("")
|
||||
(tmp_path / "test.cdg").write_text("")
|
||||
(tmp_path / "test.mp3").write_text("")
|
||||
|
||||
# Call with countdown padding DISABLED (default)
|
||||
generator.generate_cdg_from_lrc(
|
||||
lrc_file=str(lrc_file),
|
||||
audio_file=str(audio_file),
|
||||
title="Test",
|
||||
artist="Artist",
|
||||
cdg_styles={"font_path": None},
|
||||
lrc_has_countdown_padding=False,
|
||||
)
|
||||
|
||||
# Verify _remove_countdown_from_lyrics was NOT called
|
||||
mock_remove.assert_not_called()
|
||||
@@ -0,0 +1,381 @@
|
||||
"""
|
||||
Tests for the cleanup-distribution endpoint in jobs.py.
|
||||
|
||||
Verifies:
|
||||
- GDrive cleanup uses tracked file IDs from state_data when available (fast path)
|
||||
- GDrive cleanup falls back to brand_code search when gdrive_files is empty (fallback path)
|
||||
- Brand code is recycled ONLY after both Dropbox AND GDrive are confirmed clean
|
||||
- Brand code is NOT recycled when GDrive cleanup fails or is skipped
|
||||
- Endpoint returns correct status for each distribution service
|
||||
|
||||
The cleanup-distribution endpoint is used by the E2E happy-path test (Step 12)
|
||||
to remove test job files from YouTube, Dropbox, and Google Drive after the test.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from backend.api.routes.jobs import router
|
||||
from backend.api.dependencies import require_admin, require_auth, AuthResult, UserType
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# ─── Test App ────────────────────────────────────────────────────────────────
|
||||
|
||||
def get_mock_admin():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
app.dependency_overrides[require_auth] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
# ─── Fixtures ────────────────────────────────────────────────────────────────
|
||||
|
||||
def _make_job(
|
||||
*,
|
||||
brand_code="NOMAD-1271",
|
||||
gdrive_files=None,
|
||||
gdrive_folder_id="root-folder-id",
|
||||
dropbox_path="/Tracks-PublicShare",
|
||||
artist="piri",
|
||||
title="dog",
|
||||
):
|
||||
"""Make a mock Job in COMPLETE state with the given distribution data."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-id"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.artist = artist
|
||||
job.title = title
|
||||
job.dropbox_path = dropbox_path
|
||||
job.gdrive_folder_id = gdrive_folder_id
|
||||
job.state_data = {
|
||||
"brand_code": brand_code,
|
||||
"gdrive_files": gdrive_files if gdrive_files is not None else {},
|
||||
}
|
||||
return job
|
||||
|
||||
|
||||
# ─── GDrive Cleanup — Fast Path (tracked file IDs) ───────────────────────────
|
||||
|
||||
class TestCleanupDistributionGDriveTrackedFileIDs:
|
||||
"""GDrive cleanup uses tracked file IDs from state_data when available."""
|
||||
|
||||
def test_gdrive_cleanup_uses_tracked_file_ids(self, client):
|
||||
"""When gdrive_files has file IDs, delete_files is called with those IDs."""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"file-id-mp4": True, "file-id-cdg": True}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Should have used the tracked file IDs (fast path)
|
||||
mock_gdrive.delete_files.assert_called_once_with(["file-id-mp4", "file-id-cdg"])
|
||||
# Should NOT have searched by brand code
|
||||
mock_gdrive.find_files_by_brand_code.assert_not_called()
|
||||
|
||||
assert data["gdrive"]["status"] == "success"
|
||||
|
||||
def test_gdrive_cleanup_reports_partial_when_some_deletes_fail(self, client):
|
||||
"""When some file deletes fail, status is 'partial'."""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"file-id-mp4": True,
|
||||
"file-id-cdg": False, # This one failed
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["gdrive"]["status"] == "partial"
|
||||
|
||||
|
||||
# ─── GDrive Cleanup — Fallback Path (brand_code search) ──────────────────────
|
||||
|
||||
class TestCleanupDistributionGDriveFallback:
|
||||
"""GDrive cleanup searches by brand_code when gdrive_files is empty."""
|
||||
|
||||
def test_falls_back_to_brand_code_search_when_gdrive_files_empty(self, client):
|
||||
"""When gdrive_files={}, search GDrive by brand_code and delete found files."""
|
||||
job = _make_job(gdrive_files={}) # Empty — simulates old jobs / silently-failed uploads
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
# find_files_by_brand_code returns file IDs found by searching GDrive
|
||||
mock_gdrive.find_files_by_brand_code.return_value = ["old-file-id-cdg", "old-file-id-mp4"]
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"old-file-id-cdg": True,
|
||||
"old-file-id-mp4": True,
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Should have searched by brand code (fallback path)
|
||||
mock_gdrive.find_files_by_brand_code.assert_called_once_with(
|
||||
"root-folder-id", "NOMAD-1271"
|
||||
)
|
||||
# Should have deleted the found files
|
||||
mock_gdrive.delete_files.assert_called_once()
|
||||
assert data["gdrive"]["status"] == "success"
|
||||
|
||||
def test_falls_back_to_brand_code_search_when_gdrive_files_none(self, client):
|
||||
"""When gdrive_files not in state_data (old job), search by brand_code."""
|
||||
job = _make_job(gdrive_files=None)
|
||||
job.state_data = {"brand_code": "NOMAD-1271"} # No gdrive_files key at all
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = ["legacy-file-id"]
|
||||
mock_gdrive.delete_files.return_value = {"legacy-file-id": True}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_gdrive.find_files_by_brand_code.assert_called_once()
|
||||
|
||||
def test_reports_skipped_when_no_files_found_by_brand_code(self, client):
|
||||
"""When brand_code search finds nothing, GDrive status is 'skipped'."""
|
||||
job = _make_job(gdrive_files={})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = [] # Nothing found
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["gdrive"]["status"] == "skipped"
|
||||
assert "no files found" in data["gdrive"]["reason"]
|
||||
|
||||
|
||||
# ─── Brand Code Recycling — Gated on GDrive Success ──────────────────────────
|
||||
|
||||
class TestCleanupDistributionBrandCodeRecycling:
|
||||
"""Brand code is recycled only after BOTH Dropbox AND GDrive are confirmed clean."""
|
||||
|
||||
def test_brand_code_recycled_when_both_dropbox_and_gdrive_cleaned(self, client):
|
||||
"""Brand code is recycled when Dropbox delete succeeds and GDrive cleanup succeeds."""
|
||||
job = _make_job(gdrive_files={"cdg": "file-id"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True # Dropbox success
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"file-id": True} # GDrive success
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Brand code should be recycled
|
||||
mock_brand_service.recycle_brand_code.assert_called_once()
|
||||
assert data["dropbox"].get("recycled_brand_code") is True
|
||||
|
||||
def test_brand_code_not_recycled_when_gdrive_cleanup_partial(self, client):
|
||||
"""Brand code is NOT recycled when GDrive delete only partially succeeded.
|
||||
|
||||
If GDrive still has files with this brand code, recycling would allow a new
|
||||
job to get the same brand code, creating a duplicate in the public share.
|
||||
"""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True # Dropbox success
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"file-id-mp4": True,
|
||||
"file-id-cdg": False, # CDG file still on GDrive
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Brand code should NOT be recycled because GDrive still has a file
|
||||
mock_brand_service.recycle_brand_code.assert_not_called()
|
||||
# recycled_brand_code key should be absent (recycling never attempted)
|
||||
assert "recycled_brand_code" not in data.get("dropbox", {})
|
||||
|
||||
def test_brand_code_not_recycled_when_gdrive_not_configured(self, client):
|
||||
"""Brand code is NOT recycled when GDrive is not configured.
|
||||
|
||||
Without GDrive credentials, we cannot confirm that GDrive was cleaned.
|
||||
A previous upload may have succeeded (e.g., different credentials rotation).
|
||||
"""
|
||||
job = _make_job(gdrive_files={"cdg": "file-id"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = False # GDrive not configured
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
# Brand code NOT recycled — GDrive might still have files
|
||||
mock_brand_service.recycle_brand_code.assert_not_called()
|
||||
|
||||
def test_brand_code_recycled_when_gdrive_finds_nothing_to_delete(self, client):
|
||||
"""Brand code IS recycled when GDrive search finds nothing (already clean)."""
|
||||
job = _make_job(gdrive_files={}) # Empty — no tracked IDs
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = [] # GDrive already clean
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# GDrive was confirmed clean (nothing found), so brand code IS recycled
|
||||
mock_brand_service.recycle_brand_code.assert_called_once()
|
||||
assert data["dropbox"].get("recycled_brand_code") is True
|
||||
@@ -0,0 +1,262 @@
|
||||
"""
|
||||
Tests for credit enforcement in job creation and failure flows.
|
||||
|
||||
Verifies that:
|
||||
- Job creation requires credits (unless admin)
|
||||
- Credits are deducted on job creation
|
||||
- Credits are refunded on job failure
|
||||
- New users get 2 welcome credits
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
from datetime import datetime
|
||||
|
||||
# Mock Firestore before importing modules that use it
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.models.job import Job, JobCreate, JobStatus
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_firestore_service():
|
||||
"""Mock FirestoreService."""
|
||||
with patch('backend.services.job_manager.FirestoreService') as mock:
|
||||
service = Mock()
|
||||
mock.return_value = service
|
||||
yield service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage_service():
|
||||
"""Mock StorageService."""
|
||||
with patch('backend.services.job_manager.StorageService') as mock:
|
||||
service = Mock()
|
||||
mock.return_value = service
|
||||
yield service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(mock_firestore_service, mock_storage_service):
|
||||
"""Create JobManager with mocked dependencies."""
|
||||
return JobManager()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_service():
|
||||
"""Mock UserService via get_user_service (patched at source module)."""
|
||||
service = Mock()
|
||||
with patch('backend.services.user_service.get_user_service', return_value=service):
|
||||
yield service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_rate_limit_service():
|
||||
"""Mock rate limit service to always allow."""
|
||||
service = Mock()
|
||||
service.check_user_job_limit.return_value = (True, 5, "OK")
|
||||
service.record_job_creation.return_value = None
|
||||
with patch('backend.services.rate_limit_service.get_rate_limit_service', return_value=service):
|
||||
yield service
|
||||
|
||||
|
||||
class TestCreditCheckOnJobCreation:
|
||||
"""Test credit checks during job creation."""
|
||||
|
||||
def test_job_creation_succeeds_with_credits(
|
||||
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
|
||||
):
|
||||
"""Job creation succeeds when user has credits, and credit is deducted."""
|
||||
mock_user_service.has_credits.return_value = True
|
||||
mock_user_service.deduct_credit.return_value = (True, 4, "Credit deducted. 4 remaining")
|
||||
|
||||
job = job_manager.create_job(
|
||||
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="user@test.com"),
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
assert job.status == JobStatus.PENDING
|
||||
mock_user_service.has_credits.assert_called_once_with("user@test.com")
|
||||
mock_user_service.deduct_credit.assert_called_once()
|
||||
# Verify deduct_credit was called with user email, job_id, and reason
|
||||
call_args = mock_user_service.deduct_credit.call_args
|
||||
assert call_args[0][0] == "user@test.com"
|
||||
|
||||
def test_job_creation_fails_without_credits(
|
||||
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
|
||||
):
|
||||
"""Job creation raises InsufficientCreditsError when user has no credits."""
|
||||
mock_user_service.has_credits.return_value = False
|
||||
mock_user_service.check_credits.return_value = 0
|
||||
|
||||
with pytest.raises(InsufficientCreditsError) as exc_info:
|
||||
job_manager.create_job(
|
||||
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="broke@test.com"),
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
assert exc_info.value.credits_available == 0
|
||||
assert exc_info.value.credits_required == 1
|
||||
# Verify Firestore create_job was NOT called (fail-fast before job creation)
|
||||
mock_firestore_service.create_job.assert_not_called()
|
||||
|
||||
def test_admin_bypasses_credit_check(
|
||||
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
|
||||
):
|
||||
"""Admin users bypass credit check entirely."""
|
||||
job = job_manager.create_job(
|
||||
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="admin@nomadkaraoke.com"),
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
assert job.status == JobStatus.PENDING
|
||||
mock_user_service.has_credits.assert_not_called()
|
||||
mock_user_service.deduct_credit.assert_not_called()
|
||||
|
||||
def test_job_without_user_email_skips_credit_check(
|
||||
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
|
||||
):
|
||||
"""Jobs without user_email (e.g., API token auth) skip credit check."""
|
||||
job = job_manager.create_job(
|
||||
JobCreate(artist="Test", title="Song", theme_id="nomad"),
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
assert job.status == JobStatus.PENDING
|
||||
mock_user_service.has_credits.assert_not_called()
|
||||
|
||||
def test_deduction_failure_deletes_job_and_raises(
|
||||
self, job_manager, mock_firestore_service, mock_user_service, mock_rate_limit_service
|
||||
):
|
||||
"""If credit deduction fails after job creation, the job is deleted."""
|
||||
mock_user_service.has_credits.return_value = True
|
||||
mock_user_service.deduct_credit.return_value = (False, 0, "Insufficient credits")
|
||||
|
||||
with pytest.raises(InsufficientCreditsError):
|
||||
job_manager.create_job(
|
||||
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="user@test.com"),
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
# Job was created then deleted
|
||||
mock_firestore_service.create_job.assert_called_once()
|
||||
mock_firestore_service.delete_job.assert_called_once()
|
||||
|
||||
|
||||
class TestCreditRefundOnJobFailure:
|
||||
"""Test credit refund when jobs fail."""
|
||||
|
||||
def test_credit_refunded_on_job_failure(
|
||||
self, job_manager, mock_firestore_service, mock_user_service
|
||||
):
|
||||
"""Credit is refunded when a non-admin job fails."""
|
||||
mock_job = Mock(spec=Job)
|
||||
mock_job.user_email = "user@test.com"
|
||||
mock_firestore_service.get_job.return_value = mock_job
|
||||
mock_user_service.refund_credit.return_value = (True, 1, "Refunded")
|
||||
|
||||
with patch('backend.services.auth_service.is_admin_email', return_value=False):
|
||||
result = job_manager.fail_job("job123", "Processing error")
|
||||
|
||||
assert result is True
|
||||
mock_user_service.refund_credit.assert_called_once_with(
|
||||
"user@test.com", "job123", reason="job_failed"
|
||||
)
|
||||
|
||||
def test_credit_refund_skipped_for_admin_jobs(
|
||||
self, job_manager, mock_firestore_service, mock_user_service
|
||||
):
|
||||
"""Credit refund is skipped for admin-owned jobs."""
|
||||
mock_job = Mock(spec=Job)
|
||||
mock_job.user_email = "admin@nomadkaraoke.com"
|
||||
mock_firestore_service.get_job.return_value = mock_job
|
||||
|
||||
with patch('backend.services.auth_service.is_admin_email', return_value=True):
|
||||
result = job_manager.fail_job("job123", "Processing error")
|
||||
|
||||
assert result is True
|
||||
mock_user_service.refund_credit.assert_not_called()
|
||||
|
||||
def test_refund_failure_does_not_fail_job_marking(
|
||||
self, job_manager, mock_firestore_service, mock_user_service
|
||||
):
|
||||
"""If refund fails, the job is still marked as failed."""
|
||||
mock_job = Mock(spec=Job)
|
||||
mock_job.user_email = "user@test.com"
|
||||
mock_firestore_service.get_job.return_value = mock_job
|
||||
mock_user_service.refund_credit.side_effect = Exception("Firestore error")
|
||||
|
||||
with patch('backend.services.auth_service.is_admin_email', return_value=False):
|
||||
result = job_manager.fail_job("job123", "Processing error")
|
||||
|
||||
assert result is True # Job still marked as failed
|
||||
|
||||
def test_no_refund_when_job_has_no_user_email(
|
||||
self, job_manager, mock_firestore_service, mock_user_service
|
||||
):
|
||||
"""No refund attempted when job has no user_email."""
|
||||
mock_job = Mock(spec=Job)
|
||||
mock_job.user_email = None
|
||||
mock_firestore_service.get_job.return_value = mock_job
|
||||
|
||||
result = job_manager.fail_job("job123", "Processing error")
|
||||
|
||||
assert result is True
|
||||
mock_user_service.refund_credit.assert_not_called()
|
||||
|
||||
|
||||
class TestCreditAndRateLimitOrdering:
|
||||
"""Test interaction between rate limit and credit checks."""
|
||||
|
||||
def test_rate_limited_user_not_charged_credit(
|
||||
self, job_manager, mock_firestore_service, mock_user_service
|
||||
):
|
||||
"""User who is rate limited should NOT have a credit deducted."""
|
||||
mock_rate_limit_service = Mock()
|
||||
mock_rate_limit_service.check_user_job_limit.return_value = (False, 0, "Rate limit exceeded")
|
||||
mock_rate_limit_service.get_user_job_count_today.return_value = 5
|
||||
|
||||
with patch('backend.services.rate_limit_service.get_rate_limit_service', return_value=mock_rate_limit_service):
|
||||
from backend.exceptions import RateLimitExceededError
|
||||
with pytest.raises(RateLimitExceededError):
|
||||
job_manager.create_job(
|
||||
JobCreate(artist="Test", title="Song", theme_id="nomad", user_email="user@test.com"),
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
# Credit check should never be called because rate limit fails first
|
||||
mock_user_service.has_credits.assert_not_called()
|
||||
mock_user_service.deduct_credit.assert_not_called()
|
||||
|
||||
|
||||
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."""
|
||||
from backend.services.user_service import UserService
|
||||
assert UserService.NEW_USER_FREE_CREDITS == 2
|
||||
|
||||
|
||||
class TestInsufficientCreditsError:
|
||||
"""Test the InsufficientCreditsError exception."""
|
||||
|
||||
def test_exception_attributes(self):
|
||||
"""Verify exception stores all attributes."""
|
||||
err = InsufficientCreditsError(
|
||||
message="No credits",
|
||||
credits_available=0,
|
||||
credits_required=1,
|
||||
)
|
||||
assert err.message == "No credits"
|
||||
assert err.credits_available == 0
|
||||
assert err.credits_required == 1
|
||||
assert str(err) == "No credits"
|
||||
|
||||
def test_exception_defaults(self):
|
||||
"""Verify default values."""
|
||||
err = InsufficientCreditsError(message="Out of credits")
|
||||
assert err.credits_available == 0
|
||||
assert err.credits_required == 1
|
||||
File diff suppressed because it is too large.
Load diff
@@ -777,21 +777,22 @@ class TestVideoWorkerDistribution:
|
||||
async def test_handle_native_distribution_dropbox_not_configured(self):
|
||||
"""Test Dropbox upload skipped when service not configured."""
|
||||
from backend.workers.video_worker import _handle_native_distribution
|
||||
|
||||
|
||||
mock_job = MagicMock()
|
||||
mock_job.dropbox_path = "/test/path"
|
||||
mock_job.brand_prefix = "TEST"
|
||||
mock_job.gdrive_folder_id = None
|
||||
mock_job.is_private = False
|
||||
mock_job.artist = "Test"
|
||||
mock_job.title = "Song"
|
||||
mock_job.state_data = {}
|
||||
|
||||
|
||||
mock_job_log = MagicMock()
|
||||
mock_job_manager = MagicMock()
|
||||
|
||||
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = False
|
||||
|
||||
|
||||
with patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
await _handle_native_distribution(
|
||||
job_id="test-123",
|
||||
@@ -801,7 +802,7 @@ class TestVideoWorkerDistribution:
|
||||
temp_dir="/tmp/test",
|
||||
result={},
|
||||
)
|
||||
|
||||
|
||||
# Should log warning about not configured
|
||||
mock_job_log.warning.assert_called()
|
||||
|
||||
@@ -809,21 +810,22 @@ class TestVideoWorkerDistribution:
|
||||
async def test_handle_native_distribution_gdrive_not_configured(self):
|
||||
"""Test Google Drive upload skipped when service not configured."""
|
||||
from backend.workers.video_worker import _handle_native_distribution
|
||||
|
||||
|
||||
mock_job = MagicMock()
|
||||
mock_job.dropbox_path = None
|
||||
mock_job.brand_prefix = None
|
||||
mock_job.gdrive_folder_id = "test_folder_id"
|
||||
mock_job.is_private = False
|
||||
mock_job.artist = "Test"
|
||||
mock_job.title = "Song"
|
||||
mock_job.state_data = {}
|
||||
|
||||
|
||||
mock_job_log = MagicMock()
|
||||
mock_job_manager = MagicMock()
|
||||
|
||||
|
||||
mock_gdrive = MagicMock()
|
||||
mock_gdrive.is_configured = False
|
||||
|
||||
|
||||
with patch('backend.services.gdrive_service.get_gdrive_service', return_value=mock_gdrive):
|
||||
await _handle_native_distribution(
|
||||
job_id="test-123",
|
||||
@@ -833,7 +835,7 @@ class TestVideoWorkerDistribution:
|
||||
temp_dir="/tmp/test",
|
||||
result={},
|
||||
)
|
||||
|
||||
|
||||
# Should log warning about not configured
|
||||
mock_job_log.warning.assert_called()
|
||||
|
||||
@@ -841,18 +843,19 @@ class TestVideoWorkerDistribution:
|
||||
async def test_handle_native_distribution_handles_import_error(self):
|
||||
"""Test that import errors for services are handled gracefully."""
|
||||
from backend.workers.video_worker import _handle_native_distribution
|
||||
|
||||
|
||||
mock_job = MagicMock()
|
||||
mock_job.dropbox_path = "/test/path"
|
||||
mock_job.brand_prefix = "TEST"
|
||||
mock_job.gdrive_folder_id = None
|
||||
mock_job.is_private = False
|
||||
mock_job.artist = "Test"
|
||||
mock_job.title = "Song"
|
||||
mock_job.state_data = {}
|
||||
|
||||
|
||||
mock_job_log = MagicMock()
|
||||
mock_job_manager = MagicMock()
|
||||
|
||||
|
||||
# Simulate import error
|
||||
with patch('backend.services.dropbox_service.get_dropbox_service', side_effect=ImportError("No module")):
|
||||
await _handle_native_distribution(
|
||||
@@ -863,6 +866,6 @@ class TestVideoWorkerDistribution:
|
||||
temp_dir="/tmp/test",
|
||||
result={},
|
||||
)
|
||||
|
||||
|
||||
# Should log warning about import error
|
||||
mock_job_log.warning.assert_called()
|
||||
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
Tests for the GCE encoding service (encoding_service.py).
|
||||
|
||||
Tests resilience features: idempotent submission handling, cached/in_progress
|
||||
responses, and 409 fallback behavior.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
|
||||
from backend.services.encoding_service import EncodingService
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def encoding_service():
|
||||
"""Create an EncodingService with mocked credentials."""
|
||||
service = EncodingService()
|
||||
service._url = "http://fake-worker:8080"
|
||||
service._api_key = "test-key"
|
||||
service._initialized = True
|
||||
return service
|
||||
|
||||
|
||||
class TestSubmitEncodingJob:
|
||||
"""Tests for submit_encoding_job() resilience."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submit_returns_accepted(self, encoding_service):
|
||||
"""Normal submission returns accepted response."""
|
||||
mock_resp = {"status": 200, "json": {"status": "accepted", "job_id": "j1"}, "text": None}
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
assert result["status"] == "accepted"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submit_returns_cached(self, encoding_service):
|
||||
"""When worker returns cached (job already complete), pass through."""
|
||||
mock_resp = {"status": 200, "json": {"status": "cached", "job_id": "j1", "output_files": ["a.mp4"]}, "text": None}
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
assert result["status"] == "cached"
|
||||
assert result["output_files"] == ["a.mp4"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submit_returns_in_progress(self, encoding_service):
|
||||
"""When worker returns in_progress, pass through."""
|
||||
mock_resp = {"status": 200, "json": {"status": "in_progress", "job_id": "j1"}, "text": None}
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
assert result["status"] == "in_progress"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_returns_cached_if_complete(self, encoding_service):
|
||||
"""On 409, fall back to get_job_status(); return cached if complete."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
mock_status = {"status": "complete", "output_files": ["a.mp4", "b.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, return_value=mock_status):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
assert result["status"] == "cached"
|
||||
assert result["output_files"] == ["a.mp4", "b.mp4"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_returns_in_progress_if_running(self, encoding_service):
|
||||
"""On 409, fall back to get_job_status(); return in_progress if running."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
mock_status = {"status": "running", "progress": 42}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, return_value=mock_status):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
assert result["status"] == "in_progress"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_returns_in_progress_if_pending(self, encoding_service):
|
||||
"""On 409, fall back to get_job_status(); return in_progress if pending."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
mock_status = {"status": "pending", "progress": 0}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, return_value=mock_status):
|
||||
result = await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
assert result["status"] == "in_progress"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_raises_if_failed(self, encoding_service):
|
||||
"""On 409, fall back to get_job_status(); raise if status is failed."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
mock_status = {"status": "failed", "error": "ffmpeg crash"}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, return_value=mock_status):
|
||||
with pytest.raises(RuntimeError, match="already exists with status: failed"):
|
||||
await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_409_fallback_raises_if_status_check_404(self, encoding_service):
|
||||
"""On 409, if status check returns 404 (worker restarted), raise conflict error."""
|
||||
mock_resp = {"status": 409, "json": None, "text": "Job j1 already exists"}
|
||||
|
||||
with patch.object(encoding_service, "_request_with_retry", new_callable=AsyncMock, return_value=mock_resp), \
|
||||
patch.object(encoding_service, "get_job_status", new_callable=AsyncMock, side_effect=RuntimeError("Encoding job j1 not found")):
|
||||
with pytest.raises(RuntimeError, match="conflict: 409 but job not found"):
|
||||
await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
|
||||
|
||||
|
||||
class TestEncodeVideos:
|
||||
"""Tests for encode_videos() handling of submit result status."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cached_submit_returns_immediately(self, encoding_service):
|
||||
"""When submit returns cached, return immediately without polling."""
|
||||
cached_result = {"status": "cached", "job_id": "j1", "output_files": ["a.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "submit_encoding_job", new_callable=AsyncMock, return_value=cached_result) as mock_submit, \
|
||||
patch.object(encoding_service, "wait_for_completion", new_callable=AsyncMock) as mock_wait:
|
||||
result = await encoding_service.encode_videos("j1", "gs://in", "gs://out")
|
||||
|
||||
assert result["status"] == "complete"
|
||||
assert result["output_files"] == ["a.mp4"]
|
||||
mock_submit.assert_called_once()
|
||||
mock_wait.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_in_progress_submit_falls_through_to_wait(self, encoding_service):
|
||||
"""When submit returns in_progress, fall through to wait_for_completion."""
|
||||
in_progress_result = {"status": "in_progress", "job_id": "j1"}
|
||||
completed_result = {"status": "complete", "output_files": ["a.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "submit_encoding_job", new_callable=AsyncMock, return_value=in_progress_result), \
|
||||
patch.object(encoding_service, "wait_for_completion", new_callable=AsyncMock, return_value=completed_result) as mock_wait:
|
||||
result = await encoding_service.encode_videos("j1", "gs://in", "gs://out")
|
||||
|
||||
assert result["status"] == "complete"
|
||||
mock_wait.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_accepted_submit_falls_through_to_wait(self, encoding_service):
|
||||
"""Normal accepted submission falls through to wait_for_completion."""
|
||||
accepted_result = {"status": "accepted", "job_id": "j1"}
|
||||
completed_result = {"status": "complete", "output_files": ["a.mp4"]}
|
||||
|
||||
with patch.object(encoding_service, "submit_encoding_job", new_callable=AsyncMock, return_value=accepted_result), \
|
||||
patch.object(encoding_service, "wait_for_completion", new_callable=AsyncMock, return_value=completed_result) as mock_wait:
|
||||
result = await encoding_service.encode_videos("j1", "gs://in", "gs://out")
|
||||
|
||||
assert result["status"] == "complete"
|
||||
mock_wait.assert_called_once()
|
||||
@@ -19,6 +19,7 @@ import httpx
|
||||
from backend.services.flacfetch_client import (
|
||||
FlacfetchClient,
|
||||
FlacfetchServiceError,
|
||||
_format_httpx_error,
|
||||
get_flacfetch_client,
|
||||
reset_flacfetch_client,
|
||||
)
|
||||
@@ -630,3 +631,420 @@ class TestGetFlacfetchClient:
|
||||
assert client1 is not client2
|
||||
assert client2.base_url == "http://other:8080"
|
||||
|
||||
|
||||
class TestFlacfetchRetryLogic:
|
||||
"""Test retry logic for flacfetch download methods."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_retries_on_request_error(self):
|
||||
"""Test download_by_id retries on network errors (RequestError)."""
|
||||
# Mock config with retry settings
|
||||
mock_settings = Mock()
|
||||
mock_settings.flacfetch_retry_max_attempts = 3
|
||||
mock_settings.flacfetch_retry_min_wait = 0.01 # Fast retries for testing
|
||||
mock_settings.flacfetch_retry_max_wait = 0.02
|
||||
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=mock_settings):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
# Fail twice with network error, then succeed
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"download_id": "test123"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
|
||||
mock_client.post.side_effect = [
|
||||
httpx.RequestError("Connection timeout"),
|
||||
httpx.RequestError("Connection refused"),
|
||||
mock_response, # Success on third attempt
|
||||
]
|
||||
|
||||
result = await client.download_by_id("YouTube", "abc123")
|
||||
|
||||
assert result == "test123"
|
||||
assert mock_client.post.call_count == 3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_no_retry_on_4xx(self):
|
||||
"""Test download_by_id does NOT retry on 4xx client errors."""
|
||||
mock_settings = Mock()
|
||||
mock_settings.flacfetch_retry_max_attempts = 3
|
||||
mock_settings.flacfetch_retry_min_wait = 0.01
|
||||
mock_settings.flacfetch_retry_max_wait = 0.02
|
||||
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=mock_settings):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
# 404 error
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 404
|
||||
mock_response.text = "Not found"
|
||||
|
||||
def raise_status_error():
|
||||
raise httpx.HTTPStatusError(
|
||||
"Not found",
|
||||
request=Mock(),
|
||||
response=mock_response
|
||||
)
|
||||
|
||||
mock_response.raise_for_status.side_effect = raise_status_error
|
||||
mock_client.post.return_value = mock_response
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="404"):
|
||||
await client.download_by_id("YouTube", "abc123")
|
||||
|
||||
# Should only attempt once (no retries for 4xx)
|
||||
assert mock_client.post.call_count == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_retries_on_5xx(self):
|
||||
"""Test download_by_id retries on 5xx server errors."""
|
||||
mock_settings = Mock()
|
||||
mock_settings.flacfetch_retry_max_attempts = 3
|
||||
mock_settings.flacfetch_retry_min_wait = 0.01
|
||||
mock_settings.flacfetch_retry_max_wait = 0.02
|
||||
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=mock_settings):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
# 503 error twice, then success
|
||||
mock_503_response = Mock()
|
||||
mock_503_response.status_code = 503
|
||||
mock_503_response.text = "Service Unavailable"
|
||||
|
||||
def raise_503():
|
||||
raise httpx.HTTPStatusError(
|
||||
"Service Unavailable",
|
||||
request=Mock(),
|
||||
response=mock_503_response
|
||||
)
|
||||
|
||||
mock_success_response = Mock()
|
||||
mock_success_response.json.return_value = {"download_id": "test456"}
|
||||
mock_success_response.raise_for_status = Mock()
|
||||
|
||||
mock_503_response_1 = Mock()
|
||||
mock_503_response_1.status_code = 503
|
||||
mock_503_response_1.text = "Service Unavailable"
|
||||
mock_503_response_1.raise_for_status.side_effect = raise_503
|
||||
|
||||
mock_503_response_2 = Mock()
|
||||
mock_503_response_2.status_code = 503
|
||||
mock_503_response_2.text = "Service Unavailable"
|
||||
mock_503_response_2.raise_for_status.side_effect = raise_503
|
||||
|
||||
mock_client.post.side_effect = [
|
||||
mock_503_response_1,
|
||||
mock_503_response_2,
|
||||
mock_success_response,
|
||||
]
|
||||
|
||||
result = await client.download_by_id("YouTube", "abc123")
|
||||
|
||||
assert result == "test456"
|
||||
assert mock_client.post.call_count == 3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_fails_after_max_retries(self):
|
||||
"""Test download_by_id fails with clear message after all retries exhausted."""
|
||||
mock_settings = Mock()
|
||||
mock_settings.flacfetch_retry_max_attempts = 3
|
||||
mock_settings.flacfetch_retry_min_wait = 0.01
|
||||
mock_settings.flacfetch_retry_max_wait = 0.02
|
||||
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=mock_settings):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
# All attempts fail
|
||||
mock_client.post.side_effect = httpx.RequestError("Connection timeout")
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="request failed"):
|
||||
await client.download_by_id("YouTube", "abc123")
|
||||
|
||||
# Should have attempted max times
|
||||
assert mock_client.post.call_count == 3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_retries_same_as_download_by_id(self):
|
||||
"""Test download() method has same retry behavior as download_by_id()."""
|
||||
mock_settings = Mock()
|
||||
mock_settings.flacfetch_retry_max_attempts = 3
|
||||
mock_settings.flacfetch_retry_min_wait = 0.01
|
||||
mock_settings.flacfetch_retry_max_wait = 0.02
|
||||
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=mock_settings):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
# Fail twice, then succeed
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"download_id": "test789"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
|
||||
mock_client.post.side_effect = [
|
||||
httpx.RequestError("Network error"),
|
||||
httpx.RequestError("Network error"),
|
||||
mock_response,
|
||||
]
|
||||
|
||||
result = await client.download(
|
||||
search_id="search123",
|
||||
result_index=0,
|
||||
)
|
||||
|
||||
assert result == "test789"
|
||||
assert mock_client.post.call_count == 3
|
||||
|
||||
|
||||
class TestFormatHttpxError:
|
||||
"""Test _format_httpx_error helper for descriptive error messages."""
|
||||
|
||||
def test_formats_error_with_message(self):
|
||||
"""Test formatting when str(error) has content."""
|
||||
error = httpx.ConnectError("Connection refused")
|
||||
result = _format_httpx_error(error)
|
||||
assert result == "ConnectError: Connection refused"
|
||||
|
||||
def test_formats_error_with_empty_message(self):
|
||||
"""Test formatting when str(error) is empty -- the exact case from job c6b1b00f."""
|
||||
request = httpx.Request("GET", "http://10.128.0.41:8080/download/dl_abc/status")
|
||||
error = httpx.ConnectError("", request=request)
|
||||
result = _format_httpx_error(error)
|
||||
# Should include class name and URL context, NOT be empty
|
||||
assert "ConnectError" in result
|
||||
assert "GET" in result
|
||||
assert "10.128.0.41" in result
|
||||
|
||||
def test_formats_error_with_empty_message_no_request(self):
|
||||
"""Test formatting when both str and request are unavailable."""
|
||||
# Use base RequestError which doesn't require request in constructor
|
||||
error = httpx.RequestError("")
|
||||
result = _format_httpx_error(error)
|
||||
# Should at minimum return the class name
|
||||
assert result == "RequestError"
|
||||
|
||||
def test_formats_timeout_error(self):
|
||||
"""Test formatting of timeout errors."""
|
||||
error = httpx.ReadTimeout("timed out")
|
||||
result = _format_httpx_error(error)
|
||||
assert result == "ReadTimeout: timed out"
|
||||
|
||||
def test_formats_non_httpx_error(self):
|
||||
"""Test formatting of a generic exception."""
|
||||
error = ValueError("bad value")
|
||||
result = _format_httpx_error(error)
|
||||
assert result == "ValueError: bad value"
|
||||
|
||||
|
||||
class TestWaitForDownloadRetryTolerance:
|
||||
"""Test that wait_for_download tolerates transient poll failures."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tolerates_single_poll_failure(self):
|
||||
"""Test that a single transient error doesn't fail the download."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
call_count = 0
|
||||
async def mock_get_status(download_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count == 2:
|
||||
raise httpx.ConnectError("transient failure")
|
||||
if call_count >= 3:
|
||||
return {"status": "complete", "gcs_path": "gs://bucket/test.flac"}
|
||||
return {"status": "downloading", "progress": 50.0}
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
result = await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01
|
||||
)
|
||||
assert result["status"] == "complete"
|
||||
assert call_count == 3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tolerates_two_consecutive_failures(self):
|
||||
"""Test that two consecutive errors don't fail with default threshold of 3."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
mock_request = httpx.Request("GET", "http://localhost:8080/download/dl_test/status")
|
||||
|
||||
call_count = 0
|
||||
async def mock_get_status(download_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count in (2, 3):
|
||||
raise httpx.ConnectError("", request=mock_request)
|
||||
if call_count >= 4:
|
||||
return {"status": "complete", "gcs_path": "gs://bucket/test.flac"}
|
||||
return {"status": "downloading", "progress": 25.0}
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
result = await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01
|
||||
)
|
||||
assert result["status"] == "complete"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fails_after_max_consecutive_errors(self):
|
||||
"""Test that 3 consecutive errors (default) fails with descriptive message."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
call_count = 0
|
||||
async def mock_get_status(download_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count == 1:
|
||||
return {"status": "downloading", "progress": 10.0}
|
||||
# All subsequent polls fail
|
||||
raise httpx.ConnectError("connection reset")
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
with pytest.raises(FlacfetchServiceError) as exc_info:
|
||||
await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01
|
||||
)
|
||||
|
||||
error_msg = str(exc_info.value)
|
||||
assert "3 consecutive" in error_msg
|
||||
assert "ConnectError" in error_msg
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resets_error_count_on_success(self):
|
||||
"""Test that a successful poll resets the consecutive error counter."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
mock_request = httpx.Request("GET", "http://localhost:8080/download/dl_test/status")
|
||||
|
||||
call_count = 0
|
||||
async def mock_get_status(download_id):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
# Fail twice, succeed, fail twice, succeed, complete
|
||||
if call_count in (1, 2):
|
||||
raise httpx.ConnectError("", request=mock_request)
|
||||
if call_count == 3:
|
||||
return {"status": "downloading", "progress": 25.0}
|
||||
if call_count in (4, 5):
|
||||
raise httpx.ConnectError("", request=mock_request)
|
||||
if call_count == 6:
|
||||
return {"status": "downloading", "progress": 75.0}
|
||||
return {"status": "complete", "gcs_path": "gs://bucket/test.flac"}
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
result = await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01
|
||||
)
|
||||
assert result["status"] == "complete"
|
||||
assert call_count == 7 # 2 fail + 1 ok + 2 fail + 1 ok + 1 complete
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_max_consecutive_errors(self):
|
||||
"""Test configuring a different consecutive error threshold."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
async def mock_get_status(download_id):
|
||||
raise httpx.ReadError("read failed")
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
with pytest.raises(FlacfetchServiceError) as exc_info:
|
||||
await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01,
|
||||
max_consecutive_errors=5,
|
||||
)
|
||||
|
||||
assert "5 consecutive" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_error_message_includes_error_type_for_empty_str(self):
|
||||
"""Test the exact scenario from job c6b1b00f: empty httpx error string."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
mock_request = httpx.Request("GET", "http://10.128.0.41:8080/download/dl_e93031543e96/status")
|
||||
|
||||
async def mock_get_status(download_id):
|
||||
# Simulate the exact error from job c6b1b00f -- empty string
|
||||
raise httpx.ConnectError("", request=mock_request)
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
with pytest.raises(FlacfetchServiceError) as exc_info:
|
||||
await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01,
|
||||
)
|
||||
|
||||
error_msg = str(exc_info.value)
|
||||
# Must contain useful info, NOT just "Status request failed: "
|
||||
assert "ConnectError" in error_msg
|
||||
assert "consecutive" in error_msg
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_application_errors_still_fail_immediately(self):
|
||||
"""Test that FlacfetchServiceError (download not found, etc.) still fails immediately."""
|
||||
client = FlacfetchClient(
|
||||
base_url="http://localhost:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
async def mock_get_status(download_id):
|
||||
raise FlacfetchServiceError("Download not found: dl_test")
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="Download not found"):
|
||||
await client.wait_for_download(
|
||||
"dl_test", timeout=10, poll_interval=0.01,
|
||||
)
|
||||
|
||||
@@ -9,7 +9,9 @@ to avoid dependency issues in CI/CD environments.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import re
|
||||
from pathlib import Path
|
||||
from packaging.version import Version
|
||||
|
||||
|
||||
# Copy the find_file function here to test it in isolation
|
||||
@@ -227,3 +229,230 @@ class TestInstrumentalSelectionRegression:
|
||||
assert result is not None
|
||||
name = result.name.lower()
|
||||
assert "clean" in name, f"Expected clean instrumental but found: {result.name}"
|
||||
|
||||
|
||||
class TestWheelFilenameFiltering:
|
||||
"""Test wheel filename filtering to prevent installation of invalid wheels.
|
||||
|
||||
Bug: The ensure_latest_wheel() function downloads all wheels including
|
||||
karaoke_gen-current.whl, which is not a valid PEP 427 wheel filename
|
||||
(missing version and platform tags). When pip tries to install it,
|
||||
it fails with: "Invalid wheel filename (wrong number of parts)"
|
||||
|
||||
Fix: Filter out wheels containing '-current' before selecting which to install.
|
||||
"""
|
||||
|
||||
def filter_wheels(self, wheels):
|
||||
"""Replicate the filtering logic from ensure_latest_wheel()."""
|
||||
return [w for w in wheels if '-current' not in w]
|
||||
|
||||
def test_filters_out_current_wheel(self):
|
||||
"""Test that karaoke_gen-current.whl is filtered out."""
|
||||
wheels = [
|
||||
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-current.whl",
|
||||
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
|
||||
]
|
||||
|
||||
filtered = self.filter_wheels(wheels)
|
||||
|
||||
assert len(filtered) == 2
|
||||
assert "/tmp/karaoke_gen-current.whl" not in filtered
|
||||
assert "/tmp/karaoke_gen-0.116.0-py3-none-any.whl" in filtered
|
||||
assert "/tmp/karaoke_gen-0.115.0-py3-none-any.whl" in filtered
|
||||
|
||||
def test_returns_empty_when_only_current_wheel(self):
|
||||
"""Test that filtering returns empty list when only current wheel exists."""
|
||||
wheels = ["/tmp/karaoke_gen-current.whl"]
|
||||
|
||||
filtered = self.filter_wheels(wheels)
|
||||
|
||||
assert filtered == []
|
||||
|
||||
def test_selects_latest_version_after_filtering(self):
|
||||
"""Test that the latest version is selected after filtering out current.
|
||||
|
||||
Note: This test verifies filtering but uses simple sorting.
|
||||
See TestWheelVersionSorting for comprehensive semantic version sorting tests.
|
||||
"""
|
||||
wheels = [
|
||||
"/tmp/karaoke_gen-0.114.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-current.whl",
|
||||
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
|
||||
]
|
||||
|
||||
filtered = self.filter_wheels(wheels)
|
||||
|
||||
# Verify current wheel was filtered out
|
||||
assert len(filtered) == 3
|
||||
assert all("-current" not in w for w in filtered)
|
||||
|
||||
def test_no_filtering_when_no_current_wheel(self):
|
||||
"""Test that valid wheels pass through when no current wheel exists."""
|
||||
wheels = [
|
||||
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
|
||||
]
|
||||
|
||||
filtered = self.filter_wheels(wheels)
|
||||
|
||||
assert len(filtered) == 2
|
||||
assert filtered == wheels
|
||||
|
||||
def test_filters_current_in_different_paths(self):
|
||||
"""Test that current wheel is filtered regardless of path."""
|
||||
wheels = [
|
||||
"/different/path/karaoke_gen-current.whl",
|
||||
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
|
||||
]
|
||||
|
||||
filtered = self.filter_wheels(wheels)
|
||||
|
||||
assert len(filtered) == 1
|
||||
assert "/tmp/karaoke_gen-0.116.0-py3-none-any.whl" in filtered
|
||||
|
||||
|
||||
class TestWheelVersionSorting:
|
||||
"""Test semantic version sorting for wheel selection.
|
||||
|
||||
Bug: The ensure_latest_wheel() function uses sorted(wheels)[-1] which does
|
||||
alphabetical sorting, not semantic version sorting. This causes version 0.99.9
|
||||
to be selected over 0.116.1 because string comparison puts '9' > '1'.
|
||||
|
||||
Fix: Extract version from filename using regex and sort by packaging.version.Version
|
||||
"""
|
||||
|
||||
def extract_version(self, wheel_path):
|
||||
"""Replicate the version extraction logic from ensure_latest_wheel()."""
|
||||
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
|
||||
if match:
|
||||
return Version(match.group(1))
|
||||
return Version("0.0.0") # Fallback for unparseable filenames
|
||||
|
||||
def select_latest_wheel(self, wheels):
|
||||
"""Replicate the full selection logic from ensure_latest_wheel()."""
|
||||
# Filter out -current wheels
|
||||
filtered = [w for w in wheels if '-current' not in w]
|
||||
if not filtered:
|
||||
return None
|
||||
# Sort by semantic version
|
||||
filtered.sort(key=self.extract_version, reverse=True)
|
||||
return filtered[0]
|
||||
|
||||
def test_semantic_version_sorting_regression(self):
|
||||
"""Test the exact bug: 0.99.9 should NOT be selected over 0.116.1"""
|
||||
wheels = [
|
||||
"/tmp/karaoke_gen-0.99.9-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
|
||||
]
|
||||
|
||||
latest = self.select_latest_wheel(wheels)
|
||||
|
||||
# Semantic version: 0.116.1 > 0.99.9
|
||||
assert "0.116.1" in latest
|
||||
assert "0.99.9" not in latest
|
||||
|
||||
def test_alphabetical_would_fail(self):
|
||||
"""Demonstrate that alphabetical sorting gives wrong result."""
|
||||
wheels = [
|
||||
"/tmp/karaoke_gen-0.99.9-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
|
||||
]
|
||||
|
||||
# This is the OLD buggy behavior (alphabetical)
|
||||
alphabetical_latest = sorted(wheels)[-1]
|
||||
|
||||
# Alphabetical puts 0.99.9 last (WRONG!)
|
||||
assert "0.99.9" in alphabetical_latest
|
||||
|
||||
def test_version_extraction(self):
|
||||
"""Test that version is correctly extracted from wheel filename."""
|
||||
test_cases = [
|
||||
("/tmp/karaoke_gen-0.116.1-py3-none-any.whl", "0.116.1"),
|
||||
("/tmp/karaoke_gen-0.99.9-py3-none-any.whl", "0.99.9"),
|
||||
("/tmp/karaoke_gen-1.0.0-py3-none-any.whl", "1.0.0"),
|
||||
("/tmp/karaoke_gen-0.1.2-py3-none-any.whl", "0.1.2"),
|
||||
]
|
||||
|
||||
for wheel_path, expected_version in test_cases:
|
||||
version = self.extract_version(wheel_path)
|
||||
assert str(version) == expected_version
|
||||
|
||||
def test_version_extraction_fallback(self):
|
||||
"""Test that unparseable filenames get fallback version."""
|
||||
invalid_wheels = [
|
||||
"/tmp/karaoke_gen-current.whl",
|
||||
"/tmp/karaoke_gen-latest.whl",
|
||||
"/tmp/invalid-filename.whl",
|
||||
]
|
||||
|
||||
for wheel in invalid_wheels:
|
||||
version = self.extract_version(wheel)
|
||||
assert version == Version("0.0.0")
|
||||
|
||||
def test_complex_version_sorting(self):
|
||||
"""Test sorting with multiple versions including patch, minor, major."""
|
||||
wheels = [
|
||||
"/tmp/karaoke_gen-0.99.9-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-1.0.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.1.0-py3-none-any.whl",
|
||||
]
|
||||
|
||||
latest = self.select_latest_wheel(wheels)
|
||||
|
||||
# 1.0.0 is the highest version
|
||||
assert "1.0.0" in latest
|
||||
|
||||
def test_version_sorting_with_current_wheel(self):
|
||||
"""Test that current wheel is filtered before version sorting."""
|
||||
wheels = [
|
||||
"/tmp/karaoke_gen-0.99.9-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-current.whl",
|
||||
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
|
||||
]
|
||||
|
||||
latest = self.select_latest_wheel(wheels)
|
||||
|
||||
# Current is filtered out, 0.116.1 is selected
|
||||
assert "0.116.1" in latest
|
||||
assert "current" not in latest
|
||||
|
||||
def test_patch_version_comparison(self):
|
||||
"""Test that patch versions are compared correctly."""
|
||||
wheels = [
|
||||
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.116.1-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.116.2-py3-none-any.whl",
|
||||
]
|
||||
|
||||
latest = self.select_latest_wheel(wheels)
|
||||
|
||||
assert "0.116.2" in latest
|
||||
|
||||
def test_minor_version_comparison(self):
|
||||
"""Test that minor versions are compared correctly."""
|
||||
wheels = [
|
||||
"/tmp/karaoke_gen-0.115.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.116.0-py3-none-any.whl",
|
||||
"/tmp/karaoke_gen-0.200.0-py3-none-any.whl",
|
||||
]
|
||||
|
||||
latest = self.select_latest_wheel(wheels)
|
||||
|
||||
assert "0.200.0" in latest
|
||||
|
||||
def test_empty_wheels_list(self):
|
||||
"""Test that empty list returns None."""
|
||||
wheels = []
|
||||
latest = self.select_latest_wheel(wheels)
|
||||
assert latest is None
|
||||
|
||||
def test_only_current_wheel_returns_none(self):
|
||||
"""Test that list with only current wheel returns None."""
|
||||
wheels = ["/tmp/karaoke_gen-current.whl"]
|
||||
latest = self.select_latest_wheel(wheels)
|
||||
assert latest is None
|
||||
@@ -9,6 +9,7 @@ These tests mock the Google API client and Secret Manager to verify:
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
|
||||
@@ -501,24 +502,451 @@ class TestUploadToPublicShare:
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
class TestRetryBehavior:
|
||||
"""Test retry behavior for transient connection errors."""
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_retries_on_broken_pipe(self, mock_get_settings):
|
||||
"""Test that BrokenPipeError triggers retry and succeeds on second attempt."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# First call raises BrokenPipeError, second succeeds
|
||||
mock_list_result.execute.side_effect = [
|
||||
BrokenPipeError("[Errno 32] Broken pipe"),
|
||||
{"files": [{"id": "folder-123", "name": "MP4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to clear but re-set the mock (avoid real OAuth)
|
||||
def mock_reset():
|
||||
service._service = mock_drive
|
||||
|
||||
service._reset_service = mock_reset
|
||||
|
||||
folder_id = service.get_or_create_folder("parent-123", "MP4")
|
||||
assert folder_id == "folder-123"
|
||||
assert mock_list_result.execute.call_count == 2
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_gives_up_after_3_attempts(self, mock_get_settings):
|
||||
"""Test that 3 consecutive failures raises the exception."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = BrokenPipeError("[Errno 32] Broken pipe")
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to re-set the mock (avoid real OAuth)
|
||||
service._reset_service = lambda: setattr(service, '_service', mock_drive)
|
||||
|
||||
with pytest.raises(BrokenPipeError):
|
||||
service.get_or_create_folder("parent-123", "MP4")
|
||||
|
||||
assert mock_list_result.execute.call_count == 3
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_service_reset_on_retry(self, mock_get_settings):
|
||||
"""Test that _service is reset to None between retry attempts."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
BrokenPipeError("[Errno 32] Broken pipe"),
|
||||
{"files": [{"id": "folder-123", "name": "MP4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to track calls but still do the reset
|
||||
original_reset = service._reset_service
|
||||
reset_calls = []
|
||||
|
||||
def tracked_reset():
|
||||
reset_calls.append(True)
|
||||
original_reset()
|
||||
# Re-set mock service so the retry works
|
||||
service._service = mock_drive
|
||||
|
||||
service._reset_service = tracked_reset
|
||||
|
||||
folder_id = service.get_or_create_folder("parent-123", "MP4")
|
||||
assert folder_id == "folder-123"
|
||||
assert len(reset_calls) == 1 # Reset called once between attempt 1 and 2
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_retries_on_ssl_error(self, mock_get_settings):
|
||||
"""Test that SSLError triggers retry."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
ssl.SSLError("SSL: UNEXPECTED_EOF_WHILE_READING"),
|
||||
{"files": [{"id": "folder-123", "name": "MP4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
# Patch _reset_service to re-set the mock (avoid real OAuth)
|
||||
service._reset_service = lambda: setattr(service, '_service', mock_drive)
|
||||
|
||||
folder_id = service.get_or_create_folder("parent-123", "MP4")
|
||||
assert folder_id == "folder-123"
|
||||
assert mock_list_result.execute.call_count == 2
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_no_retry_on_non_transient_error(self, mock_get_settings):
|
||||
"""Test that non-transient errors are not retried."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
service = GoogleDriveService()
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = ValueError("bad value")
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
service.get_or_create_folder("parent-123", "MP4")
|
||||
|
||||
assert mock_list_result.execute.call_count == 1
|
||||
|
||||
|
||||
class TestDeleteFile:
|
||||
"""Test delete_file and delete_files methods."""
|
||||
|
||||
def _make_service(self, mock_get_settings):
|
||||
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
mock_settings = Mock()
|
||||
mock_get_settings.return_value = mock_settings
|
||||
service = GoogleDriveService()
|
||||
service._loaded = True
|
||||
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
|
||||
return service
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_file_success(self, mock_get_settings):
|
||||
"""Successful delete returns True."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_delete = Mock()
|
||||
mock_delete.execute.return_value = None
|
||||
mock_files_api.delete.return_value = mock_delete
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.delete_file("file-id-123")
|
||||
|
||||
assert result is True
|
||||
mock_files_api.delete.assert_called_once_with(fileId="file-id-123")
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_file_returns_true_on_404(self, mock_get_settings):
|
||||
"""404 (already deleted) returns True — idempotent cleanup."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_delete = Mock()
|
||||
not_found = Exception("File not found")
|
||||
not_found.resp = Mock()
|
||||
not_found.resp.status = 404
|
||||
mock_delete.execute.side_effect = not_found
|
||||
mock_files_api.delete.return_value = mock_delete
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.delete_file("already-gone-id")
|
||||
|
||||
assert result is True
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_file_returns_false_on_error(self, mock_get_settings):
|
||||
"""Non-404 errors return False."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_delete = Mock()
|
||||
mock_delete.execute.side_effect = Exception("Permission denied")
|
||||
mock_files_api.delete.return_value = mock_delete
|
||||
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.delete_file("restricted-file")
|
||||
|
||||
assert result is False
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_files_calls_delete_file_for_each_id(self, mock_get_settings):
|
||||
"""delete_files returns a per-ID success dict."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
# Stub delete_file: first ID succeeds, second fails
|
||||
results_by_id = {"id-1": True, "id-2": False}
|
||||
service.delete_file = lambda fid: results_by_id[fid]
|
||||
|
||||
result = service.delete_files(["id-1", "id-2"])
|
||||
|
||||
assert result == {"id-1": True, "id-2": False}
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_delete_files_empty_list(self, mock_get_settings):
|
||||
"""delete_files with empty list returns empty dict."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
result = service.delete_files([])
|
||||
assert result == {}
|
||||
|
||||
|
||||
class TestFindFilesByBrandCode:
|
||||
"""Test find_files_by_brand_code method — used as fallback in cleanup-distribution."""
|
||||
|
||||
def _make_service(self, mock_get_settings):
|
||||
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
|
||||
from backend.services.gdrive_service import GoogleDriveService
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = json.dumps({
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
})
|
||||
mock_get_settings.return_value = mock_settings
|
||||
service = GoogleDriveService()
|
||||
service._loaded = True
|
||||
service._credentials_data = {
|
||||
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
|
||||
}
|
||||
return service
|
||||
|
||||
def _attach_mock_drive(self, service, list_side_effects):
|
||||
"""Attach a mock Drive client whose files().list().execute() returns given values."""
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = list_side_effects
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
return mock_files_api
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_finds_files_in_all_subfolders(self, mock_get_settings):
|
||||
"""Test finds matching files across CDG/, MP4/, MP4-720p/ subfolders."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# Responses: for each subfolder: (1) find subfolder, (2) search for files
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]}, # CDG subfolder found
|
||||
{"files": [{"id": "cdg-file-1", "name": "NOMAD-1271 - piri - dog.zip"}]},
|
||||
{"files": [{"id": "mp4-folder"}]}, # MP4 subfolder found
|
||||
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
|
||||
{"files": [{"id": "mp4720-folder"}]}, # MP4-720p subfolder found
|
||||
{"files": [{"id": "mp4720-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert len(result) == 3
|
||||
assert "cdg-file-1" in result
|
||||
assert "mp4-file-1" in result
|
||||
assert "mp4720-file-1" in result
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_returns_empty_when_subfolder_not_found(self, mock_get_settings):
|
||||
"""Test returns empty list when public share subfolders don't exist."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
# All subfolder lookups return empty
|
||||
mock_list_result.execute.return_value = {"files": []}
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == []
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_filters_by_exact_brand_code_prefix(self, mock_get_settings):
|
||||
"""Test only returns files whose name starts with '{brand_code} - '."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]},
|
||||
{
|
||||
"files": [
|
||||
{"id": "match-id", "name": "NOMAD-1271 - piri - dog.zip"},
|
||||
# This one contains NOMAD-1271 but doesn't START with it — should be excluded
|
||||
{"id": "no-match-id", "name": "BONUS-NOMAD-1271 - other.zip"},
|
||||
]
|
||||
},
|
||||
{"files": []}, # MP4 subfolder not found
|
||||
{"files": []}, # MP4-720p subfolder not found
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == ["match-id"]
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_returns_empty_when_no_files_match_brand_code(self, mock_get_settings):
|
||||
"""Test returns empty list when subfolder exists but has no matching files."""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]},
|
||||
{"files": [{"id": "other-id", "name": "NOMAD-1300 - someone else.zip"}]},
|
||||
{"files": []}, # MP4 not found
|
||||
{"files": []}, # MP4-720p not found
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
assert result == []
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_raises_after_all_subfolders_when_any_error(self, mock_get_settings):
|
||||
"""When any subfolder search errors, raises RuntimeError after processing all subfolders.
|
||||
|
||||
This prevents the cleanup endpoint from treating an incomplete search result
|
||||
as "GDrive is clean" and incorrectly recycling the brand code.
|
||||
"""
|
||||
service = self._make_service(mock_get_settings)
|
||||
|
||||
mock_files_api = Mock()
|
||||
mock_list_result = Mock()
|
||||
mock_list_result.execute.side_effect = [
|
||||
{"files": [{"id": "cdg-folder"}]},
|
||||
Exception("API error"), # CDG file search fails
|
||||
{"files": [{"id": "mp4-folder"}]},
|
||||
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
|
||||
{"files": [{"id": "mp4720-folder"}]},
|
||||
{"files": []},
|
||||
]
|
||||
mock_files_api.list.return_value = mock_list_result
|
||||
mock_drive = Mock()
|
||||
mock_drive.files.return_value = mock_files_api
|
||||
service._service = mock_drive
|
||||
|
||||
# Should raise after processing all subfolders — an incomplete search must not
|
||||
# be silently treated as "nothing found" by the caller
|
||||
with pytest.raises(RuntimeError, match="search incomplete"):
|
||||
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
|
||||
|
||||
|
||||
class TestGetGdriveService:
|
||||
"""Test get_gdrive_service singleton."""
|
||||
|
||||
|
||||
@patch("backend.services.gdrive_service.get_settings")
|
||||
def test_get_gdrive_service_singleton(self, mock_get_settings):
|
||||
"""Test get_gdrive_service returns singleton instance."""
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
import backend.services.gdrive_service as gdrive_module
|
||||
|
||||
|
||||
# Reset singleton
|
||||
gdrive_module._gdrive_service = None
|
||||
|
||||
|
||||
mock_settings = Mock()
|
||||
mock_settings.get_secret.return_value = None
|
||||
mock_get_settings.return_value = mock_settings
|
||||
|
||||
|
||||
service1 = get_gdrive_service()
|
||||
service2 = get_gdrive_service()
|
||||
|
||||
|
||||
assert service1 is service2
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
Tests for delayed GDrive validation trigger.
|
||||
|
||||
The post-job GDrive validation was firing immediately after upload, before E2E
|
||||
test cleanup could run. This caused false "all clear" reports when the validator
|
||||
checked sequence gaps while test files still existed in GDrive.
|
||||
|
||||
Fix: Use Cloud Tasks to delay the validation by 5 minutes.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, AsyncMock, patch
|
||||
|
||||
|
||||
class TestGdriveValidationEndpoint:
|
||||
"""Tests for POST /api/internal/trigger-gdrive-validation."""
|
||||
|
||||
@pytest.fixture
|
||||
def client_and_mocks(self):
|
||||
"""Create TestClient with mocked dependencies."""
|
||||
import os
|
||||
os.environ.setdefault('ADMIN_TOKENS', 'test-admin-token')
|
||||
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
|
||||
with patch('backend.api.routes.internal.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
yield TestClient(app)
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers(self):
|
||||
return {"Authorization": "Bearer test-admin-token"}
|
||||
|
||||
def test_endpoint_returns_200(self, client_and_mocks, auth_headers):
|
||||
"""Test gdrive validation endpoint returns 200 with auth."""
|
||||
with patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
return_value={"status": "ok", "total_files": 1276}
|
||||
):
|
||||
response = client_and_mocks.post(
|
||||
"/api/internal/trigger-gdrive-validation",
|
||||
headers=auth_headers,
|
||||
json={},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "ok"
|
||||
|
||||
def test_endpoint_returns_skipped_when_url_not_set(self, client_and_mocks, auth_headers):
|
||||
"""Test endpoint returns skipped when GDRIVE_VALIDATOR_URL is not configured."""
|
||||
with patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
return_value=None
|
||||
):
|
||||
response = client_and_mocks.post(
|
||||
"/api/internal/trigger-gdrive-validation",
|
||||
headers=auth_headers,
|
||||
json={},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "skipped"
|
||||
|
||||
def test_endpoint_handles_issues_found(self, client_and_mocks, auth_headers):
|
||||
"""Test endpoint properly relays issues_found status."""
|
||||
with patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
return_value={"status": "issues_found", "issues": ["NOMAD-1276 missing"]}
|
||||
):
|
||||
response = client_and_mocks.post(
|
||||
"/api/internal/trigger-gdrive-validation",
|
||||
headers=auth_headers,
|
||||
json={},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "issues_found"
|
||||
|
||||
def test_endpoint_handles_exception(self, client_and_mocks, auth_headers):
|
||||
"""Test endpoint returns error status on exception."""
|
||||
with patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
side_effect=Exception("Connection refused")
|
||||
):
|
||||
response = client_and_mocks.post(
|
||||
"/api/internal/trigger-gdrive-validation",
|
||||
headers=auth_headers,
|
||||
json={},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "error"
|
||||
assert "Connection refused" in data["message"]
|
||||
|
||||
|
||||
class TestScheduleGdriveValidation:
|
||||
"""Tests for WorkerService.schedule_gdrive_validation()."""
|
||||
|
||||
def test_skips_when_cloud_tasks_disabled(self):
|
||||
"""Test validation scheduling is skipped in dev mode (no Cloud Tasks)."""
|
||||
import asyncio
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.enable_cloud_tasks = False
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
|
||||
from backend.services.worker_service import WorkerService
|
||||
service = WorkerService()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
result = loop.run_until_complete(service.schedule_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Should return True (success) even though it didn't schedule
|
||||
assert result is True
|
||||
|
||||
def test_schedules_with_correct_url(self):
|
||||
"""Test that validation is scheduled targeting the right endpoint."""
|
||||
import asyncio
|
||||
|
||||
mock_tasks_client = MagicMock()
|
||||
mock_response = MagicMock()
|
||||
mock_response.name = "projects/test/queues/gdrive-validation-queue/tasks/abc123"
|
||||
mock_tasks_client.create_task.return_value = mock_response
|
||||
mock_tasks_client.queue_path.return_value = "projects/test/locations/us-central1/queues/gdrive-validation-queue"
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.cloud_run_url = "https://api.nomadkaraoke.com"
|
||||
|
||||
from backend.services.worker_service import WorkerService
|
||||
service = WorkerService()
|
||||
# Override the lazy property by setting the private attribute
|
||||
service._tasks_client = mock_tasks_client
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
result = loop.run_until_complete(service.schedule_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
assert result is True
|
||||
mock_tasks_client.create_task.assert_called_once()
|
||||
|
||||
# Verify the task targets the right endpoint
|
||||
create_call = mock_tasks_client.create_task.call_args
|
||||
task_payload = create_call.kwargs.get('task', {})
|
||||
url = task_payload.get('http_request', {}).get('url', '')
|
||||
assert 'trigger-gdrive-validation' in url
|
||||
|
||||
def test_returns_false_on_error(self):
|
||||
"""Test that scheduling failure returns False (non-fatal)."""
|
||||
import asyncio
|
||||
|
||||
mock_tasks_client = MagicMock()
|
||||
mock_tasks_client.create_task.side_effect = Exception("Queue not found")
|
||||
mock_tasks_client.queue_path.return_value = "projects/test/queues/gdrive-validation-queue"
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.cloud_run_url = "https://api.nomadkaraoke.com"
|
||||
|
||||
from backend.services.worker_service import WorkerService
|
||||
service = WorkerService()
|
||||
service._tasks_client = mock_tasks_client
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
result = loop.run_until_complete(service.schedule_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestOrchestratorUsesDelayedValidation:
|
||||
"""Test that the orchestrator uses delayed validation instead of immediate."""
|
||||
|
||||
def test_orchestrator_schedules_delayed_validation(self):
|
||||
"""Test _trigger_gdrive_validation uses schedule_gdrive_validation."""
|
||||
import asyncio
|
||||
|
||||
mock_worker_service = MagicMock()
|
||||
mock_worker_service.schedule_gdrive_validation = AsyncMock(return_value=True)
|
||||
|
||||
with patch(
|
||||
'backend.services.worker_service.get_worker_service',
|
||||
return_value=mock_worker_service
|
||||
):
|
||||
from backend.workers.video_worker_orchestrator import VideoWorkerOrchestrator
|
||||
|
||||
# Create a minimal orchestrator instance
|
||||
mock_config = MagicMock()
|
||||
mock_job_log = MagicMock()
|
||||
orchestrator = VideoWorkerOrchestrator.__new__(VideoWorkerOrchestrator)
|
||||
orchestrator.config = mock_config
|
||||
orchestrator.job_log = mock_job_log
|
||||
orchestrator.result = MagicMock()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(orchestrator._trigger_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_worker_service.schedule_gdrive_validation.assert_called_once()
|
||||
mock_job_log.info.assert_called_once()
|
||||
assert "5 min" in mock_job_log.info.call_args[0][0]
|
||||
|
||||
def test_orchestrator_falls_back_to_immediate_on_failure(self):
|
||||
"""Test _trigger_gdrive_validation falls back to immediate call if scheduling fails."""
|
||||
import asyncio
|
||||
|
||||
mock_worker_service = MagicMock()
|
||||
mock_worker_service.schedule_gdrive_validation = AsyncMock(return_value=False)
|
||||
|
||||
mock_validator = MagicMock(return_value={"status": "ok"})
|
||||
|
||||
with patch(
|
||||
'backend.services.worker_service.get_worker_service',
|
||||
return_value=mock_worker_service
|
||||
), patch(
|
||||
'backend.services.gdrive_validator_client.trigger_gdrive_validation',
|
||||
mock_validator
|
||||
):
|
||||
from backend.workers.video_worker_orchestrator import VideoWorkerOrchestrator
|
||||
|
||||
mock_config = MagicMock()
|
||||
mock_job_log = MagicMock()
|
||||
orchestrator = VideoWorkerOrchestrator.__new__(VideoWorkerOrchestrator)
|
||||
orchestrator.config = mock_config
|
||||
orchestrator.job_log = mock_job_log
|
||||
orchestrator.result = MagicMock()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(orchestrator._trigger_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Should have called the fallback immediate trigger
|
||||
mock_validator.assert_called_once()
|
||||
# Should have logged a warning about the fallback
|
||||
mock_job_log.warning.assert_called_once()
|
||||
|
||||
def test_orchestrator_handles_exception_gracefully(self):
|
||||
"""Test _trigger_gdrive_validation never crashes the pipeline."""
|
||||
import asyncio
|
||||
|
||||
with patch(
|
||||
'backend.services.worker_service.get_worker_service',
|
||||
side_effect=Exception("Service unavailable")
|
||||
):
|
||||
from backend.workers.video_worker_orchestrator import VideoWorkerOrchestrator
|
||||
|
||||
mock_config = MagicMock()
|
||||
mock_job_log = MagicMock()
|
||||
orchestrator = VideoWorkerOrchestrator.__new__(VideoWorkerOrchestrator)
|
||||
orchestrator.config = mock_config
|
||||
orchestrator.job_log = mock_job_log
|
||||
orchestrator.result = MagicMock()
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
# Should not raise - non-fatal
|
||||
loop.run_until_complete(orchestrator._trigger_gdrive_validation())
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
mock_job_log.warning.assert_called_once()
|
||||
|
||||
|
||||
class TestGdriveValidationConstants:
|
||||
"""Test that the delay constant is correctly set."""
|
||||
|
||||
def test_delay_is_five_minutes(self):
|
||||
"""Verify GDRIVE_VALIDATION_DELAY_SECONDS is 300 (5 minutes)."""
|
||||
from backend.services.worker_service import GDRIVE_VALIDATION_DELAY_SECONDS
|
||||
assert GDRIVE_VALIDATION_DELAY_SECONDS == 300
|
||||
|
||||
def test_queue_is_configured(self):
|
||||
"""Verify gdrive-validation queue is in WORKER_QUEUES."""
|
||||
from backend.services.worker_service import WORKER_QUEUES
|
||||
assert "gdrive-validation" in WORKER_QUEUES
|
||||
assert WORKER_QUEUES["gdrive-validation"] == "gdrive-validation-queue"
|
||||
|
||||
def test_dispatch_deadline_is_configured(self):
|
||||
"""Verify gdrive-validation dispatch deadline is set."""
|
||||
from backend.services.worker_service import WORKER_DISPATCH_DEADLINES
|
||||
assert "gdrive-validation" in WORKER_DISPATCH_DEADLINES
|
||||
assert WORKER_DISPATCH_DEADLINES["gdrive-validation"] == 120
|
||||
@@ -196,7 +196,7 @@ class TestUserEmailExtraction:
|
||||
mock_jm.create_job.return_value = mock_job
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_cred.return_value.check_youtube_credentials.return_value = Mock(status=Mock(value="valid"))
|
||||
mock_search.return_value.search.return_value = []
|
||||
mock_search.return_value.search_async = AsyncMock(return_value=[])
|
||||
|
||||
await search_audio(
|
||||
request=mock_request,
|
||||
@@ -381,7 +381,7 @@ class TestAudioSearchCacheIndependence:
|
||||
|
||||
def test_download_code_uses_youtube_download_service(self):
|
||||
"""
|
||||
Verify that _download_and_start_processing uses YouTubeDownloadService.
|
||||
Verify that _download_audio_and_trigger_workers uses YouTubeDownloadService.
|
||||
|
||||
After the consolidation refactor (2025-01), all YouTube downloads go through
|
||||
YouTubeDownloadService instead of using download_from_url directly. This
|
||||
@@ -390,14 +390,14 @@ class TestAudioSearchCacheIndependence:
|
||||
from backend.api.routes import audio_search
|
||||
import inspect
|
||||
|
||||
# Get the source of _download_and_start_processing
|
||||
source = inspect.getsource(audio_search._download_and_start_processing)
|
||||
# Get the source of _download_audio_and_trigger_workers
|
||||
source = inspect.getsource(audio_search._download_audio_and_trigger_workers)
|
||||
|
||||
# Verify YouTubeDownloadService is used for YouTube
|
||||
assert "source_name == 'YouTube'" in source, \
|
||||
"_download_and_start_processing must check for YouTube source"
|
||||
"_download_audio_and_trigger_workers must check for YouTube source"
|
||||
assert 'youtube_service' in source or 'get_youtube_download_service' in source, \
|
||||
"_download_and_start_processing must use YouTubeDownloadService for YouTube"
|
||||
"_download_audio_and_trigger_workers must use YouTubeDownloadService for YouTube"
|
||||
|
||||
def test_youtube_download_service_import_exists(self):
|
||||
"""
|
||||
|
||||
@@ -4,7 +4,7 @@ Tests for the job health service.
|
||||
Tests consistency checks and worker validation functions.
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timedelta, timezone, UTC
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.job_health_service import (
|
||||
@@ -135,6 +135,43 @@ class TestCheckJobConsistency:
|
||||
issues = check_job_consistency(job)
|
||||
assert issues == []
|
||||
|
||||
def test_encoding_recently_started_not_flagged(self):
|
||||
"""Encoding job started 10 minutes ago should not be flagged."""
|
||||
job = create_test_job(status=JobStatus.ENCODING)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=10)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("encoding_stuck" in i for i in issues)
|
||||
|
||||
def test_encoding_stuck_55_min_flagged(self):
|
||||
"""Encoding job stuck for 55 minutes should be flagged."""
|
||||
job = create_test_job(status=JobStatus.ENCODING)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=55)
|
||||
issues = check_job_consistency(job)
|
||||
assert any("encoding_stuck" in i for i in issues)
|
||||
stuck_issue = [i for i in issues if "encoding_stuck" in i][0]
|
||||
assert "55 min" in stuck_issue
|
||||
|
||||
def test_encoding_at_49_min_not_flagged(self):
|
||||
"""Encoding job at 49 minutes should not be flagged (must exceed 50)."""
|
||||
job = create_test_job(status=JobStatus.ENCODING)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=49)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("encoding_stuck" in i for i in issues)
|
||||
|
||||
def test_non_encoding_job_not_affected(self):
|
||||
"""Non-encoding job should not trigger encoding_stuck check."""
|
||||
job = create_test_job(status=JobStatus.GENERATING_VIDEO)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=120)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("encoding_stuck" in i for i in issues)
|
||||
|
||||
def test_encoding_stuck_with_naive_datetime(self):
|
||||
"""Encoding-stuck check handles naive datetime (no tzinfo)."""
|
||||
job = create_test_job(status=JobStatus.ENCODING)
|
||||
job.updated_at = datetime.utcnow() - timedelta(minutes=60)
|
||||
issues = check_job_consistency(job)
|
||||
assert any("encoding_stuck" in i for i in issues)
|
||||
|
||||
|
||||
class TestCheckJobConsistencyDetailed:
|
||||
"""Tests for check_job_consistency_detailed function."""
|
||||
|
||||
@@ -428,7 +428,7 @@ class TestMadeForYouFieldMapping:
|
||||
brand_prefix="NOMAD",
|
||||
)
|
||||
|
||||
job = job_manager.create_job(job_create)
|
||||
job = job_manager.create_job(job_create, is_admin=True)
|
||||
|
||||
# Verify all made-for-you fields
|
||||
assert job.made_for_you is True
|
||||
|
||||
@@ -214,6 +214,91 @@ class TestDeleteJob:
|
||||
assert response.status_code in [200, 404]
|
||||
|
||||
|
||||
class TestDeleteJobBrandCodeRecycling:
|
||||
"""Tests for brand code recycling in DELETE /api/jobs/{job_id}."""
|
||||
|
||||
def test_brand_code_recycled_before_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Test that brand code is recycled before the job is deleted."""
|
||||
mock_job_manager = MagicMock()
|
||||
job_with_brand = Job(
|
||||
job_id="test-bc-123",
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={"brand_code": "NOMAD-0042"},
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job_with_brand
|
||||
mock_job_manager.delete_job.return_value = True
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', return_value=("NOMAD", 42)) as mock_parse, \
|
||||
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
|
||||
mock_svc = MagicMock()
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-123", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_parse.assert_called_once_with("NOMAD-0042")
|
||||
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
|
||||
def test_recycling_failure_does_not_prevent_deletion(self, mock_worker_service, mock_theme_service, auth_headers):
|
||||
"""Test that job deletion proceeds even if brand code recycling fails."""
|
||||
mock_job_manager = MagicMock()
|
||||
job_with_brand = Job(
|
||||
job_id="test-bc-456",
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={"brand_code": "NOMAD-0099"},
|
||||
outputs_deleted_at=datetime.now(UTC),
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job_with_brand
|
||||
mock_job_manager.delete_job.return_value = True
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.services.job_manager.JobManager', lambda *a, **k: mock_job_manager), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')), \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code', side_effect=ValueError("Bad format")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/test-bc-456", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Job should still be deleted despite recycling failure
|
||||
mock_job_manager.delete_job.assert_called_once()
|
||||
|
||||
def test_no_brand_code_skips_recycling(self, client, mock_job_manager, auth_headers):
|
||||
"""Test that deletion without brand code doesn't attempt recycling."""
|
||||
with patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
|
||||
response = client.delete("/api/jobs/test123", headers=auth_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_get_svc.assert_not_called()
|
||||
|
||||
|
||||
class TestCancelJob:
|
||||
"""Tests for POST /api/jobs/{job_id}/cancel."""
|
||||
|
||||
@@ -274,10 +359,129 @@ class TestSelectInstrumental:
|
||||
|
||||
class TestStartReview:
|
||||
"""Tests for POST /api/jobs/{job_id}/start-review."""
|
||||
|
||||
|
||||
def test_start_review_endpoint_exists(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test start review endpoint exists."""
|
||||
response = client.post("/api/jobs/test123/start-review", headers=auth_headers)
|
||||
# Should not be 404 or 405
|
||||
assert response.status_code not in [404, 405]
|
||||
|
||||
|
||||
class TestSubmitEditLog:
|
||||
"""Tests for POST /api/jobs/{job_id}/edit-log."""
|
||||
|
||||
def test_submit_edit_log_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test submitting a valid edit log returns 200."""
|
||||
edit_log = {
|
||||
"session_id": "sess-abc",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "hash123",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": [
|
||||
{
|
||||
"id": "e1",
|
||||
"timestamp": "2026-03-01T00:01:00.000Z",
|
||||
"operation": "word_change",
|
||||
"segment_id": "s1",
|
||||
"segment_index": 0,
|
||||
"word_ids_before": ["w1"],
|
||||
"word_ids_after": ["w1"],
|
||||
"text_before": "helo",
|
||||
"text_after": "hello",
|
||||
"feedback": {"reason": "misheard_word", "timestamp": "2026-03-01T00:01:05.000Z"}
|
||||
}
|
||||
]
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
response = client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["entries_count"] == 1
|
||||
assert data["feedback_count"] == 1
|
||||
|
||||
def test_submit_edit_log_stores_to_gcs(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test edit log is stored to GCS with correct path."""
|
||||
edit_log = {
|
||||
"session_id": "sess-xyz",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "hash123",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": []
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
mock_storage.upload_json.assert_called_once_with(
|
||||
"jobs/test123/lyrics/edit_log_sess-xyz.json",
|
||||
edit_log
|
||||
)
|
||||
|
||||
def test_submit_edit_log_updates_firestore(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test edit log updates Firestore state_data."""
|
||||
edit_log = {
|
||||
"session_id": "sess-123",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "h",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": []
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
mock_job_manager.update_state_data.assert_any_call(
|
||||
"test123", "last_edit_log_path", "jobs/test123/lyrics/edit_log_sess-123.json"
|
||||
)
|
||||
mock_job_manager.update_state_data.assert_any_call(
|
||||
"test123", "last_edit_log_session", "sess-123"
|
||||
)
|
||||
|
||||
def test_submit_edit_log_nonexistent_job_returns_404(self, mock_worker_service, auth_headers):
|
||||
"""Test submitting to nonexistent job returns 404."""
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_jm
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_jm), \
|
||||
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
|
||||
patch('backend.services.job_manager.JobManager', mock_jm_factory), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
from backend.main import app
|
||||
test_client = TestClient(app)
|
||||
response = test_client.post(
|
||||
"/api/jobs/nonexistent/edit-log",
|
||||
json={"session_id": "s", "entries": []},
|
||||
headers=auth_headers
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_submit_edit_log_counts_feedback_correctly(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test feedback count excludes no_response entries."""
|
||||
edit_log = {
|
||||
"session_id": "sess-1",
|
||||
"job_id": "test123",
|
||||
"audio_hash": "h",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": [
|
||||
{"id": "e1", "feedback": {"reason": "misheard_word"}},
|
||||
{"id": "e2", "feedback": {"reason": "no_response"}},
|
||||
{"id": "e3", "feedback": None},
|
||||
{"id": "e4", "feedback": {"reason": "wrong_lyrics"}},
|
||||
]
|
||||
}
|
||||
with patch('backend.api.routes.jobs.StorageService') as mock_storage_cls:
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
response = client.post("/api/jobs/test123/edit-log", json=edit_log, headers=auth_headers)
|
||||
data = response.json()
|
||||
assert data["entries_count"] == 4
|
||||
assert data["feedback_count"] == 2 # misheard_word + wrong_lyrics
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""
|
||||
Tests for the karaokenerds service — HTML parsing, community detection, YouTube URL cleanup.
|
||||
|
||||
Ported from kjbox/kj-controller/tests/unit/test_karaoke_nerds.py.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from backend.services.karaokenerds_service import (
|
||||
parse_results,
|
||||
_clean_youtube_url,
|
||||
_parse_single_track,
|
||||
)
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
|
||||
# --- YouTube URL cleanup ---
|
||||
|
||||
|
||||
def test_clean_youtube_url_strips_list_param():
|
||||
url = "https://www.youtube.com/watch?v=abc123&list=PLtest123&index=1"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123&index=1"
|
||||
|
||||
|
||||
def test_clean_youtube_url_no_list_param():
|
||||
url = "https://www.youtube.com/watch?v=abc123"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123"
|
||||
|
||||
|
||||
def test_clean_youtube_url_list_at_end():
|
||||
url = "https://www.youtube.com/watch?v=abc123&list=PLtest"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123"
|
||||
|
||||
|
||||
# --- Single track parsing ---
|
||||
|
||||
|
||||
TRACK_HTML_COMMUNITY = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">Karaoke Version</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=mrZRURcb1cM&list=PLtest" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">
|
||||
<span class="badge badge-primary badge-pill">
|
||||
KV<img class="check" src="/Content/Images/check.svg" title="Global Karaoke Community">
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
TRACK_HTML_NO_COMMUNITY = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">Sunfly</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=xyz789" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">
|
||||
<span class="badge badge-primary badge-pill">SF</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
TRACK_HTML_NO_YOUTUBE = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/AB/">Some Brand</a>
|
||||
<div class="ml-auto">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/AB/">
|
||||
<span class="badge badge-primary badge-pill">AB</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
|
||||
def test_parse_single_track_community():
|
||||
soup = BeautifulSoup(TRACK_HTML_COMMUNITY, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is not None
|
||||
assert track["brand_name"] == "Karaoke Version"
|
||||
assert track["brand_code"] == "KV"
|
||||
assert track["is_community"] is True
|
||||
assert "youtube.com" in track["youtube_url"]
|
||||
# List param should be stripped
|
||||
assert "&list=" not in track["youtube_url"]
|
||||
|
||||
|
||||
def test_parse_single_track_no_community():
|
||||
soup = BeautifulSoup(TRACK_HTML_NO_COMMUNITY, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is not None
|
||||
assert track["brand_name"] == "Sunfly"
|
||||
assert track["brand_code"] == "SF"
|
||||
assert track["is_community"] is False
|
||||
assert "youtube.com" in track["youtube_url"]
|
||||
|
||||
|
||||
def test_parse_single_track_no_youtube_returns_none():
|
||||
soup = BeautifulSoup(TRACK_HTML_NO_YOUTUBE, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is None
|
||||
|
||||
|
||||
# --- Full results parsing ---
|
||||
|
||||
|
||||
FULL_RESULTS_HTML = """
|
||||
<table>
|
||||
<tbody>
|
||||
<tr class="group">
|
||||
<td><a href="/Song/Dreams/Fleetwood-Mac/">Dreams</a></td>
|
||||
<td><a href="/Artist/Fleetwood-Mac/">Fleetwood Mac</a></td>
|
||||
<td><a class="details-link">2 Brands >></a></td>
|
||||
</tr>
|
||||
<tr class="details">
|
||||
<td colspan="30">
|
||||
<ul class="list-group">
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">Karaoke Version</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=community1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">
|
||||
<span class="badge badge-primary badge-pill">
|
||||
KV<img class="check" src="/Content/Images/check.svg" title="Global Karaoke Community">
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">Sunfly</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=noncommunity1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">
|
||||
<span class="badge badge-primary badge-pill">SF</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="group">
|
||||
<td><a href="/Song/The-Chain/Fleetwood-Mac/">The Chain</a></td>
|
||||
<td><a href="/Artist/Fleetwood-Mac/">Fleetwood Mac</a></td>
|
||||
<td><a class="details-link">1 Brand >></a></td>
|
||||
</tr>
|
||||
<tr class="details">
|
||||
<td colspan="30">
|
||||
<ul class="list-group">
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/The-Chain/Fleetwood-Mac/KFN/">Karafun</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=chain1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/The-Chain/Fleetwood-Mac/KFN/">
|
||||
<span class="badge badge-primary badge-pill">KFN</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
"""
|
||||
|
||||
|
||||
def test_parse_results_full():
|
||||
songs = parse_results(FULL_RESULTS_HTML)
|
||||
assert len(songs) == 2
|
||||
|
||||
# First song: Dreams
|
||||
assert songs[0]["title"] == "Dreams"
|
||||
assert songs[0]["artist"] == "Fleetwood Mac"
|
||||
assert len(songs[0]["tracks"]) == 2
|
||||
|
||||
# First track is community
|
||||
assert songs[0]["tracks"][0]["is_community"] is True
|
||||
assert songs[0]["tracks"][0]["brand_code"] == "KV"
|
||||
|
||||
# Second track is not community
|
||||
assert songs[0]["tracks"][1]["is_community"] is False
|
||||
assert songs[0]["tracks"][1]["brand_code"] == "SF"
|
||||
|
||||
# Second song: The Chain
|
||||
assert songs[1]["title"] == "The Chain"
|
||||
assert songs[1]["artist"] == "Fleetwood Mac"
|
||||
assert len(songs[1]["tracks"]) == 1
|
||||
assert songs[1]["tracks"][0]["is_community"] is False
|
||||
|
||||
|
||||
def test_parse_results_empty_html():
|
||||
assert parse_results("") == []
|
||||
assert parse_results("<html></html>") == []
|
||||
assert parse_results("<table></table>") == []
|
||||
|
||||
|
||||
def test_parse_results_no_table():
|
||||
assert parse_results("<div>No results</div>") == []
|
||||
@@ -75,6 +75,32 @@ class TestMain:
|
||||
assert 'karaoke' in app.title.lower() or app.title
|
||||
|
||||
|
||||
class TestExceptionHandlers:
|
||||
"""Tests for global exception handlers in main.py."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_insufficient_credits_handler_returns_402_response(self):
|
||||
"""Test that the insufficient credits handler returns HTTP 402 with correct body."""
|
||||
from backend.main import insufficient_credits_exception_handler
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
|
||||
exc = InsufficientCreditsError(
|
||||
message="No credits remaining",
|
||||
credits_available=0,
|
||||
credits_required=1,
|
||||
)
|
||||
|
||||
response = await insufficient_credits_exception_handler(request=None, exc=exc)
|
||||
|
||||
assert response.status_code == 402
|
||||
import json
|
||||
body = json.loads(response.body)
|
||||
assert body["detail"] == "No credits remaining"
|
||||
assert body["credits_available"] == 0
|
||||
assert body["credits_required"] == 1
|
||||
assert body["buy_url"] == "/#pricing"
|
||||
|
||||
|
||||
class TestDependencies:
|
||||
"""Tests for dependencies.py."""
|
||||
|
||||
|
||||
@@ -243,6 +243,59 @@ class TestPackagingServiceCDGPackage:
|
||||
title="Test Title",
|
||||
artist="Test Artist",
|
||||
cdg_styles=styles,
|
||||
lrc_has_countdown_padding=False,
|
||||
countdown_padding_seconds=3.0,
|
||||
)
|
||||
assert os.path.isfile(zip_path)
|
||||
|
||||
@patch("karaoke_gen.lyrics_transcriber.output.cdg.CDGGenerator")
|
||||
def test_create_cdg_package_with_countdown_padding(self, mock_cdg_generator_class):
|
||||
"""Test CDG package creation with countdown padding parameters."""
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
lrc_file = os.path.join(tmpdir, "test.lrc")
|
||||
audio_file = os.path.join(tmpdir, "test.flac")
|
||||
zip_path = os.path.join(tmpdir, "output.zip")
|
||||
generated_zip = os.path.join(tmpdir, "generated.zip")
|
||||
|
||||
with open(lrc_file, "w") as f:
|
||||
f.write("[00:00.00]Test lyrics")
|
||||
with open(audio_file, "w") as f:
|
||||
f.write("fake audio")
|
||||
|
||||
# Create the zip file that would be generated
|
||||
with zipfile.ZipFile(generated_zip, "w") as zf:
|
||||
zf.writestr("test.mp3", "fake mp3")
|
||||
zf.writestr("test.cdg", "fake cdg")
|
||||
|
||||
mock_generator = MagicMock()
|
||||
mock_generator.generate_cdg_from_lrc.return_value = (
|
||||
"test.cdg", "test.mp3", generated_zip
|
||||
)
|
||||
mock_cdg_generator_class.return_value = mock_generator
|
||||
|
||||
styles = {"font_size": 24}
|
||||
service = PackagingService(cdg_styles=styles)
|
||||
|
||||
# Call with countdown padding enabled
|
||||
result = service.create_cdg_package(
|
||||
lrc_file=lrc_file,
|
||||
audio_file=audio_file,
|
||||
output_zip_path=zip_path,
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
lrc_has_countdown_padding=True,
|
||||
countdown_padding_seconds=3.5,
|
||||
)
|
||||
|
||||
# Verify countdown params are passed to generator
|
||||
mock_generator.generate_cdg_from_lrc.assert_called_once_with(
|
||||
lrc_file=lrc_file,
|
||||
audio_file=audio_file,
|
||||
title="Test Title",
|
||||
artist="Test Artist",
|
||||
cdg_styles=styles,
|
||||
lrc_has_countdown_padding=True,
|
||||
countdown_padding_seconds=3.5,
|
||||
)
|
||||
assert os.path.isfile(zip_path)
|
||||
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
"""
|
||||
Tests for private (non-published) tracks feature.
|
||||
|
||||
Tests cover:
|
||||
- Job model is_private field
|
||||
- Distribution settings overrides for private jobs
|
||||
- Email template YouTube section removal
|
||||
- Admin toggle with auto-delete behavior
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.models.job import Job, JobCreate
|
||||
from backend.services.job_defaults_service import (
|
||||
get_effective_distribution_for_job,
|
||||
EffectiveDistributionSettings,
|
||||
)
|
||||
from backend.services.template_service import TemplateService
|
||||
|
||||
|
||||
class TestJobModelIsPrivate:
|
||||
"""Tests for is_private field on Job and JobCreate models."""
|
||||
|
||||
def test_job_defaults_to_not_private(self):
|
||||
"""Job.is_private defaults to False."""
|
||||
now = datetime.utcnow().isoformat()
|
||||
job = Job(job_id="test-123", status="pending", created_at=now, updated_at=now)
|
||||
assert job.is_private is False
|
||||
|
||||
def test_job_can_be_created_as_private(self):
|
||||
"""Job can be explicitly set as private."""
|
||||
now = datetime.utcnow().isoformat()
|
||||
job = Job(job_id="test-123", status="pending", is_private=True, created_at=now, updated_at=now)
|
||||
assert job.is_private is True
|
||||
|
||||
def test_job_create_defaults_to_not_private(self):
|
||||
"""JobCreate.is_private defaults to False."""
|
||||
job_create = JobCreate(artist="Test", title="Song")
|
||||
assert job_create.is_private is False
|
||||
|
||||
def test_job_create_can_be_private(self):
|
||||
"""JobCreate can be explicitly set as private."""
|
||||
job_create = JobCreate(artist="Test", title="Song", is_private=True)
|
||||
assert job_create.is_private is True
|
||||
|
||||
def test_create_job_persists_is_private(self):
|
||||
"""JobManager.create_job should persist is_private from JobCreate to Job."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
manager = JobManager()
|
||||
manager.firestore = Mock()
|
||||
manager.firestore.create_job = Mock()
|
||||
|
||||
job_create = JobCreate(
|
||||
artist="Test",
|
||||
title="Song",
|
||||
is_private=True,
|
||||
theme_id="nomad",
|
||||
)
|
||||
|
||||
job = manager.create_job(job_create, is_admin=True)
|
||||
|
||||
assert job.is_private is True
|
||||
manager.firestore.create_job.assert_called_once()
|
||||
saved_job = manager.firestore.create_job.call_args[0][0]
|
||||
assert saved_job.is_private is True
|
||||
|
||||
def test_create_job_defaults_is_private_false(self):
|
||||
"""JobManager.create_job should default is_private to False."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
manager = JobManager()
|
||||
manager.firestore = Mock()
|
||||
manager.firestore.create_job = Mock()
|
||||
|
||||
job_create = JobCreate(
|
||||
artist="Test",
|
||||
title="Song",
|
||||
theme_id="nomad",
|
||||
)
|
||||
|
||||
job = manager.create_job(job_create, is_admin=True)
|
||||
|
||||
assert job.is_private is False
|
||||
|
||||
|
||||
class TestGetEffectiveDistributionForJob:
|
||||
"""Tests for get_effective_distribution_for_job() helper."""
|
||||
|
||||
@patch('backend.services.job_defaults_service.get_settings')
|
||||
def test_private_job_uses_private_dropbox_path(self, mock_settings):
|
||||
"""Private job should use the private Dropbox path."""
|
||||
mock_settings.return_value = SimpleNamespace(
|
||||
default_private_dropbox_path="/Tracks-NonPublished",
|
||||
default_private_brand_prefix="NOMADNP",
|
||||
)
|
||||
job = SimpleNamespace(
|
||||
is_private=True,
|
||||
dropbox_path="/Tracks-Organized",
|
||||
brand_prefix="NOMAD",
|
||||
enable_youtube_upload=True,
|
||||
gdrive_folder_id="some-folder-id",
|
||||
discord_webhook_url="https://discord.com/hook",
|
||||
youtube_description_template="template",
|
||||
)
|
||||
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
assert dist.dropbox_path == "/Tracks-NonPublished"
|
||||
assert dist.brand_prefix == "NOMADNP"
|
||||
|
||||
@patch('backend.services.job_defaults_service.get_settings')
|
||||
def test_private_job_disables_youtube(self, mock_settings):
|
||||
"""Private job should have YouTube upload disabled."""
|
||||
mock_settings.return_value = SimpleNamespace(
|
||||
default_private_dropbox_path="/Tracks-NonPublished",
|
||||
default_private_brand_prefix="NOMADNP",
|
||||
)
|
||||
job = SimpleNamespace(
|
||||
is_private=True,
|
||||
enable_youtube_upload=True,
|
||||
discord_webhook_url=None,
|
||||
)
|
||||
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
assert dist.enable_youtube_upload is False
|
||||
assert dist.youtube_description is None
|
||||
|
||||
@patch('backend.services.job_defaults_service.get_settings')
|
||||
def test_private_job_disables_gdrive(self, mock_settings):
|
||||
"""Private job should have Google Drive folder ID set to None."""
|
||||
mock_settings.return_value = SimpleNamespace(
|
||||
default_private_dropbox_path="/Tracks-NonPublished",
|
||||
default_private_brand_prefix="NOMADNP",
|
||||
)
|
||||
job = SimpleNamespace(
|
||||
is_private=True,
|
||||
gdrive_folder_id="some-folder-id",
|
||||
discord_webhook_url=None,
|
||||
)
|
||||
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
assert dist.gdrive_folder_id is None
|
||||
|
||||
@patch('backend.services.job_defaults_service.get_settings')
|
||||
def test_private_job_preserves_discord(self, mock_settings):
|
||||
"""Private job should still have Discord webhook preserved."""
|
||||
mock_settings.return_value = SimpleNamespace(
|
||||
default_private_dropbox_path="/Tracks-NonPublished",
|
||||
default_private_brand_prefix="NOMADNP",
|
||||
)
|
||||
job = SimpleNamespace(
|
||||
is_private=True,
|
||||
discord_webhook_url="https://discord.com/webhook/123",
|
||||
)
|
||||
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
assert dist.discord_webhook_url == "https://discord.com/webhook/123"
|
||||
|
||||
def test_non_private_job_uses_job_settings(self):
|
||||
"""Non-private job should use its own distribution settings."""
|
||||
job = SimpleNamespace(
|
||||
is_private=False,
|
||||
dropbox_path="/Tracks-Organized",
|
||||
brand_prefix="NOMAD",
|
||||
enable_youtube_upload=True,
|
||||
gdrive_folder_id="folder-id",
|
||||
discord_webhook_url="https://discord.com/hook",
|
||||
youtube_description_template="description",
|
||||
)
|
||||
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
assert dist.dropbox_path == "/Tracks-Organized"
|
||||
assert dist.brand_prefix == "NOMAD"
|
||||
assert dist.enable_youtube_upload is True
|
||||
assert dist.gdrive_folder_id == "folder-id"
|
||||
assert dist.discord_webhook_url == "https://discord.com/hook"
|
||||
assert dist.youtube_description == "description"
|
||||
|
||||
def test_job_without_is_private_treated_as_non_private(self):
|
||||
"""Job object without is_private attribute should be treated as non-private."""
|
||||
job = SimpleNamespace(
|
||||
dropbox_path="/Tracks-Organized",
|
||||
brand_prefix="NOMAD",
|
||||
enable_youtube_upload=False,
|
||||
gdrive_folder_id=None,
|
||||
discord_webhook_url=None,
|
||||
youtube_description_template=None,
|
||||
)
|
||||
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
assert dist.dropbox_path == "/Tracks-Organized"
|
||||
assert dist.brand_prefix == "NOMAD"
|
||||
assert dist.enable_youtube_upload is False
|
||||
|
||||
|
||||
class TestTemplateServicePrivate:
|
||||
"""Tests for email template rendering with is_private flag."""
|
||||
|
||||
def test_private_job_removes_youtube_section(self):
|
||||
"""Private job completion email should not contain YouTube section."""
|
||||
service = TemplateService()
|
||||
service._storage_client = Mock()
|
||||
service._bucket = Mock()
|
||||
# Force use of default template
|
||||
service._bucket.blob.return_value.exists.return_value = False
|
||||
|
||||
result = service.render_job_completion(
|
||||
name="Test User",
|
||||
youtube_url=None,
|
||||
dropbox_url="https://dropbox.com/link",
|
||||
artist="Artist",
|
||||
title="Song",
|
||||
job_id="job-123",
|
||||
is_private=True,
|
||||
)
|
||||
|
||||
assert "YouTube" not in result
|
||||
assert "youtube_url" not in result
|
||||
assert "https://dropbox.com/link" in result
|
||||
|
||||
def test_non_private_job_includes_youtube_section(self):
|
||||
"""Non-private job completion email should include YouTube section."""
|
||||
service = TemplateService()
|
||||
service._storage_client = Mock()
|
||||
service._bucket = Mock()
|
||||
service._bucket.blob.return_value.exists.return_value = False
|
||||
|
||||
result = service.render_job_completion(
|
||||
name="Test User",
|
||||
youtube_url="https://youtube.com/watch?v=123",
|
||||
dropbox_url="https://dropbox.com/link",
|
||||
artist="Artist",
|
||||
title="Song",
|
||||
job_id="job-123",
|
||||
is_private=False,
|
||||
)
|
||||
|
||||
assert "https://youtube.com/watch?v=123" in result
|
||||
assert "YouTube" in result
|
||||
|
||||
def test_private_job_still_has_dropbox_link(self):
|
||||
"""Private job email should still contain the Dropbox link."""
|
||||
service = TemplateService()
|
||||
service._storage_client = Mock()
|
||||
service._bucket = Mock()
|
||||
service._bucket.blob.return_value.exists.return_value = False
|
||||
|
||||
result = service.render_job_completion(
|
||||
name="Test User",
|
||||
dropbox_url="https://dropbox.com/sh/abc123",
|
||||
artist="Artist",
|
||||
title="Song",
|
||||
job_id="job-123",
|
||||
is_private=True,
|
||||
)
|
||||
|
||||
assert "https://dropbox.com/sh/abc123" in result
|
||||
assert "dropbox" in result.lower()
|
||||
|
||||
def test_private_job_still_has_greeting(self):
|
||||
"""Private job email should still contain the greeting."""
|
||||
service = TemplateService()
|
||||
service._storage_client = Mock()
|
||||
service._bucket = Mock()
|
||||
service._bucket.blob.return_value.exists.return_value = False
|
||||
|
||||
result = service.render_job_completion(
|
||||
name="Jane",
|
||||
dropbox_url="https://dropbox.com/link",
|
||||
is_private=True,
|
||||
)
|
||||
|
||||
assert "Hi Jane" in result
|
||||
|
||||
|
||||
class TestNotificationServicePrivate:
|
||||
"""Tests for notification service passing is_private to template."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_completion_email_passes_is_private(self):
|
||||
"""send_job_completion_email should pass is_private to template renderer."""
|
||||
from backend.services.job_notification_service import JobNotificationService
|
||||
|
||||
service = JobNotificationService()
|
||||
service.email_service = Mock()
|
||||
service.email_service.send_job_completion.return_value = True
|
||||
service.template_service = Mock()
|
||||
service.template_service.render_job_completion.return_value = "Test message"
|
||||
|
||||
with patch('backend.services.job_notification_service.ENABLE_AUTO_EMAILS', True):
|
||||
await service.send_job_completion_email(
|
||||
job_id="job-123",
|
||||
user_email="user@example.com",
|
||||
is_private=True,
|
||||
)
|
||||
|
||||
# Verify is_private=True was passed to template renderer
|
||||
call_kwargs = service.template_service.render_job_completion.call_args
|
||||
assert call_kwargs[1].get('is_private') is True or \
|
||||
(call_kwargs[0] and True in call_kwargs[0]) # positional or keyword
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_completion_email_defaults_is_private_false(self):
|
||||
"""send_job_completion_email should default is_private to False."""
|
||||
from backend.services.job_notification_service import JobNotificationService
|
||||
|
||||
service = JobNotificationService()
|
||||
service.email_service = Mock()
|
||||
service.email_service.send_job_completion.return_value = True
|
||||
service.template_service = Mock()
|
||||
service.template_service.render_job_completion.return_value = "Test message"
|
||||
|
||||
with patch('backend.services.job_notification_service.ENABLE_AUTO_EMAILS', True):
|
||||
await service.send_job_completion_email(
|
||||
job_id="job-123",
|
||||
user_email="user@example.com",
|
||||
)
|
||||
|
||||
call_kwargs = service.template_service.render_job_completion.call_args
|
||||
assert call_kwargs[1].get('is_private') is False
|
||||
|
||||
def test_get_completion_message_passes_is_private(self):
|
||||
"""get_completion_message should pass is_private to template renderer."""
|
||||
from backend.services.job_notification_service import JobNotificationService
|
||||
|
||||
service = JobNotificationService()
|
||||
service.template_service = Mock()
|
||||
service.template_service.render_job_completion.return_value = "Test message"
|
||||
|
||||
service.get_completion_message(job_id="job-123", is_private=True)
|
||||
|
||||
call_kwargs = service.template_service.render_job_completion.call_args
|
||||
assert call_kwargs[1].get('is_private') is True
|
||||
|
||||
|
||||
class TestRequestModelIsPrivate:
|
||||
"""Tests for is_private on API request models."""
|
||||
|
||||
def test_url_submission_request_has_is_private(self):
|
||||
"""URLSubmissionRequest should accept is_private field."""
|
||||
from backend.models.requests import URLSubmissionRequest
|
||||
req = URLSubmissionRequest(url="https://youtube.com/watch?v=123", is_private=True)
|
||||
assert req.is_private is True
|
||||
|
||||
def test_url_submission_request_is_private_defaults_none(self):
|
||||
"""URLSubmissionRequest.is_private should default to None."""
|
||||
from backend.models.requests import URLSubmissionRequest
|
||||
req = URLSubmissionRequest(url="https://youtube.com/watch?v=123")
|
||||
assert req.is_private is None
|
||||
|
||||
|
||||
class TestAdminPrivateToggle:
|
||||
"""Tests for admin API handling of is_private toggle."""
|
||||
|
||||
def test_is_private_in_editable_fields(self):
|
||||
"""is_private should be in the EDITABLE_JOB_FIELDS set."""
|
||||
from backend.api.routes.admin import EDITABLE_JOB_FIELDS
|
||||
assert "is_private" in EDITABLE_JOB_FIELDS
|
||||
|
||||
def test_job_update_request_has_is_private(self):
|
||||
"""JobUpdateRequest model should accept is_private field."""
|
||||
from backend.api.routes.admin import JobUpdateRequest
|
||||
req = JobUpdateRequest(is_private=True)
|
||||
assert req.is_private is True
|
||||
|
||||
def test_job_update_request_is_private_optional(self):
|
||||
"""JobUpdateRequest.is_private should be optional."""
|
||||
from backend.api.routes.admin import JobUpdateRequest
|
||||
req = JobUpdateRequest()
|
||||
assert req.is_private is None
|
||||
|
||||
|
||||
class TestOrchestratorConfigPrivate:
|
||||
"""Tests for orchestrator config with private jobs."""
|
||||
|
||||
@patch('backend.services.job_defaults_service.get_settings')
|
||||
def test_private_job_config_disables_youtube_and_gdrive(self, mock_settings):
|
||||
"""Private job should produce config with no YouTube and no GDrive."""
|
||||
mock_settings.return_value = SimpleNamespace(
|
||||
default_private_dropbox_path="/Tracks-NonPublished",
|
||||
default_private_brand_prefix="NOMADNP",
|
||||
)
|
||||
from backend.workers.video_worker_orchestrator import create_orchestrator_config_from_job
|
||||
|
||||
job = MagicMock()
|
||||
job.job_id = "test-private"
|
||||
job.artist = "Artist"
|
||||
job.title = "Title"
|
||||
job.state_data = {"instrumental_selection": "clean"}
|
||||
job.enable_cdg = False
|
||||
job.enable_txt = False
|
||||
job.enable_youtube_upload = True # Would normally enable YouTube
|
||||
job.is_private = True # But private overrides it
|
||||
job.brand_prefix = "NOMAD"
|
||||
job.discord_webhook_url = None
|
||||
job.youtube_description_template = "desc"
|
||||
job.dropbox_path = "/Tracks-Organized"
|
||||
job.gdrive_folder_id = "folder-123"
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
temp_dir="/tmp/test",
|
||||
youtube_credentials={"token": "test"},
|
||||
)
|
||||
|
||||
assert config.enable_youtube_upload is False
|
||||
assert config.gdrive_folder_id is None
|
||||
assert config.brand_prefix == "NOMADNP"
|
||||
assert config.youtube_description_template is None
|
||||
@@ -176,56 +176,71 @@ class TestRateLimitService:
|
||||
# YouTube Upload Rate Limiting Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_check_youtube_limit_under_limit(self, rate_limit_service, mock_db, mock_settings):
|
||||
"""Test YouTube upload under limit is allowed."""
|
||||
def test_check_youtube_limit_delegates_to_quota_service(self, rate_limit_service, mock_db, mock_settings):
|
||||
"""Test YouTube upload check delegates to YouTubeQuotaService."""
|
||||
mock_quota_service = Mock()
|
||||
mock_quota_service.check_quota_available.return_value = (True, 9500, "9500 quota units remaining")
|
||||
|
||||
with patch('backend.services.rate_limit_service.settings', mock_settings), \
|
||||
patch('backend.services.youtube_quota_service.get_youtube_quota_service', return_value=mock_quota_service):
|
||||
allowed, remaining, message = rate_limit_service.check_youtube_upload_limit()
|
||||
|
||||
assert allowed is True
|
||||
assert remaining == 9500
|
||||
mock_quota_service.check_quota_available.assert_called_once()
|
||||
|
||||
def test_check_youtube_limit_quota_exceeded(self, rate_limit_service, mock_db, mock_settings):
|
||||
"""Test YouTube upload check when quota is exceeded."""
|
||||
mock_quota_service = Mock()
|
||||
mock_quota_service.check_quota_available.return_value = (False, 0, "YouTube API quota exhausted")
|
||||
|
||||
with patch('backend.services.rate_limit_service.settings', mock_settings), \
|
||||
patch('backend.services.youtube_quota_service.get_youtube_quota_service', return_value=mock_quota_service):
|
||||
allowed, remaining, message = rate_limit_service.check_youtube_upload_limit()
|
||||
|
||||
assert allowed is False
|
||||
assert remaining == 0
|
||||
assert "quota" in message.lower()
|
||||
|
||||
def test_check_youtube_limit_fallback_on_quota_service_error(self, rate_limit_service, mock_db, mock_settings):
|
||||
"""Test YouTube upload falls back to legacy when quota service unavailable."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"count": 3}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.rate_limit_service.settings', mock_settings):
|
||||
with patch('backend.services.rate_limit_service.settings', mock_settings), \
|
||||
patch('backend.services.youtube_quota_service.get_youtube_quota_service', side_effect=Exception("Service unavailable")):
|
||||
allowed, remaining, message = rate_limit_service.check_youtube_upload_limit()
|
||||
|
||||
assert allowed is True
|
||||
assert remaining == 7 # 10 - 3
|
||||
|
||||
def test_check_youtube_limit_at_limit(self, rate_limit_service, mock_db, mock_settings):
|
||||
"""Test YouTube upload at limit is blocked."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"count": 10}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.rate_limit_service.settings', mock_settings):
|
||||
allowed, remaining, message = rate_limit_service.check_youtube_upload_limit()
|
||||
|
||||
assert allowed is False
|
||||
assert remaining == 0
|
||||
assert "Daily YouTube upload limit reached" in message
|
||||
|
||||
def test_check_youtube_limit_no_uploads_yet(self, rate_limit_service, mock_db, mock_settings):
|
||||
"""Test YouTube upload with no uploads today is allowed."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.rate_limit_service.settings', mock_settings):
|
||||
allowed, remaining, message = rate_limit_service.check_youtube_upload_limit()
|
||||
|
||||
assert allowed is True
|
||||
assert remaining == 10
|
||||
|
||||
def test_check_youtube_limit_zero_configured(self, rate_limit_service, mock_db, mock_settings):
|
||||
"""Test that zero limit means unlimited YouTube uploads."""
|
||||
def test_check_youtube_limit_fallback_zero_configured(self, rate_limit_service, mock_db, mock_settings):
|
||||
"""Test that zero limit means unlimited when falling back to legacy."""
|
||||
mock_settings.rate_limit_youtube_uploads_per_day = 0
|
||||
|
||||
with patch('backend.services.rate_limit_service.settings', mock_settings):
|
||||
with patch('backend.services.rate_limit_service.settings', mock_settings), \
|
||||
patch('backend.services.youtube_quota_service.get_youtube_quota_service', side_effect=Exception("Service unavailable")):
|
||||
allowed, remaining, message = rate_limit_service.check_youtube_upload_limit()
|
||||
|
||||
assert allowed is True
|
||||
assert remaining == -1
|
||||
assert "No YouTube upload limit" in message
|
||||
|
||||
def test_check_youtube_limit_denies_on_runtime_error(self, rate_limit_service, mock_db, mock_settings):
|
||||
"""Test YouTube upload denied when quota service check_quota_available raises."""
|
||||
mock_quota_service = Mock()
|
||||
mock_quota_service.check_quota_available.side_effect = Exception("Firestore timeout")
|
||||
|
||||
with patch('backend.services.rate_limit_service.settings', mock_settings), \
|
||||
patch('backend.services.youtube_quota_service.get_youtube_quota_service', return_value=mock_quota_service):
|
||||
allowed, remaining, message = rate_limit_service.check_youtube_upload_limit()
|
||||
|
||||
assert allowed is False
|
||||
assert remaining == 0
|
||||
assert "Quota service error" in message
|
||||
|
||||
# =========================================================================
|
||||
# Beta Enrollment IP Rate Limiting Tests
|
||||
# =========================================================================
|
||||
|
||||
@@ -59,6 +59,8 @@ class TestGetRateLimitStats:
|
||||
"""Test successful stats retrieval."""
|
||||
with patch('backend.api.routes.rate_limits.get_rate_limit_service') as mock_get_rls, \
|
||||
patch('backend.api.routes.rate_limits.get_email_validation_service') as mock_get_evs, \
|
||||
patch('backend.services.youtube_quota_service.get_youtube_quota_service') as mock_get_qs, \
|
||||
patch('backend.services.youtube_upload_queue_service.get_youtube_upload_queue_service') as mock_get_uqs, \
|
||||
patch('backend.api.routes.rate_limits.settings', mock_settings):
|
||||
|
||||
# Setup rate limit service mock
|
||||
@@ -77,6 +79,30 @@ class TestGetRateLimitStats:
|
||||
}
|
||||
mock_get_evs.return_value = mock_evs
|
||||
|
||||
# Setup quota service mock
|
||||
mock_quota = Mock()
|
||||
mock_quota.get_quota_stats.return_value = {
|
||||
"units_consumed": 900,
|
||||
"units_remaining": 8600,
|
||||
"units_limit": 10000,
|
||||
"effective_limit": 9500,
|
||||
"upload_cost": 300,
|
||||
"estimated_uploads_remaining": 28,
|
||||
"seconds_until_reset": 43200,
|
||||
}
|
||||
mock_get_qs.return_value = mock_quota
|
||||
|
||||
# Setup queue service mock
|
||||
mock_queue = Mock()
|
||||
mock_queue.get_queue_stats.return_value = {
|
||||
"queued": 0,
|
||||
"processing": 0,
|
||||
"failed": 0,
|
||||
"completed": 0,
|
||||
"total": 0,
|
||||
}
|
||||
mock_get_uqs.return_value = mock_queue
|
||||
|
||||
response = client.get(
|
||||
"/api/admin/rate-limits/stats",
|
||||
headers={"Authorization": "Bearer admin-token"}
|
||||
@@ -90,6 +116,10 @@ class TestGetRateLimitStats:
|
||||
assert data["youtube_uploads_remaining"] == 7
|
||||
assert data["disposable_domains_count"] == 100
|
||||
assert data["total_overrides"] == 1
|
||||
# New quota fields
|
||||
assert data["youtube_quota_units_consumed"] == 900
|
||||
assert data["youtube_quota_units_remaining"] == 8600
|
||||
assert data["youtube_quota_daily_limit"] == 10000
|
||||
|
||||
|
||||
class TestGetUserRateLimitStatus:
|
||||
@@ -390,3 +420,96 @@ class TestUserOverrideEndpoints:
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestYouTubeQueueEndpoints:
|
||||
"""Tests for YouTube upload queue management endpoints."""
|
||||
|
||||
def test_get_youtube_queue(self, client):
|
||||
"""Test getting YouTube queue entries."""
|
||||
with patch('backend.services.youtube_upload_queue_service.get_youtube_upload_queue_service') as mock_get_qs:
|
||||
|
||||
mock_qs = Mock()
|
||||
mock_qs.get_all_queue_entries.return_value = [
|
||||
{
|
||||
"job_id": "job-123",
|
||||
"status": "queued",
|
||||
"reason": "quota_exceeded",
|
||||
"user_email": "user@example.com",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song",
|
||||
"brand_code": "NOMAD-100",
|
||||
"queued_at": "2026-03-03T10:00:00",
|
||||
"attempts": 0,
|
||||
"max_attempts": 5,
|
||||
"last_error": None,
|
||||
"youtube_url": None,
|
||||
"notification_sent": False,
|
||||
}
|
||||
]
|
||||
mock_qs.get_queue_stats.return_value = {
|
||||
"queued": 1,
|
||||
"processing": 0,
|
||||
"failed": 0,
|
||||
"completed": 5,
|
||||
"total": 6,
|
||||
}
|
||||
mock_get_qs.return_value = mock_qs
|
||||
|
||||
response = client.get(
|
||||
"/api/admin/rate-limits/youtube-queue",
|
||||
headers={"Authorization": "Bearer admin-token"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["entries"]) == 1
|
||||
assert data["entries"][0]["job_id"] == "job-123"
|
||||
assert data["entries"][0]["status"] == "queued"
|
||||
assert data["stats"]["queued"] == 1
|
||||
assert data["stats"]["total"] == 6
|
||||
|
||||
def test_retry_youtube_upload_success(self, client):
|
||||
"""Test retrying a failed YouTube upload."""
|
||||
with patch('backend.services.youtube_upload_queue_service.get_youtube_upload_queue_service') as mock_get_qs:
|
||||
|
||||
mock_qs = Mock()
|
||||
mock_qs.retry_upload.return_value = True
|
||||
mock_get_qs.return_value = mock_qs
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/rate-limits/youtube-queue/job-123/retry",
|
||||
headers={"Authorization": "Bearer admin-token"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["success"] is True
|
||||
mock_qs.retry_upload.assert_called_once_with("job-123")
|
||||
|
||||
def test_retry_youtube_upload_not_found(self, client):
|
||||
"""Test retrying a non-existent or non-retryable upload."""
|
||||
with patch('backend.services.youtube_upload_queue_service.get_youtube_upload_queue_service') as mock_get_qs:
|
||||
|
||||
mock_qs = Mock()
|
||||
mock_qs.retry_upload.return_value = False
|
||||
mock_get_qs.return_value = mock_qs
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/rate-limits/youtube-queue/nonexistent/retry",
|
||||
headers={"Authorization": "Bearer admin-token"}
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_trigger_queue_processing(self, client):
|
||||
"""Test manually triggering queue processing."""
|
||||
response = client.post(
|
||||
"/api/admin/rate-limits/youtube-queue/process",
|
||||
headers={"Authorization": "Bearer admin-token"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["success"] is True
|
||||
assert "background" in data["message"].lower()
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
Unit tests for the annotations endpoint in review.py.
|
||||
|
||||
Tests the actual storage logic (not the stub version).
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage():
|
||||
"""Create a mock StorageService that tracks calls."""
|
||||
storage = MagicMock()
|
||||
storage.upload_json = MagicMock()
|
||||
# Default: no existing annotations
|
||||
storage.download_json = MagicMock(side_effect=Exception("Not found"))
|
||||
return storage
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_storage):
|
||||
"""Create TestClient with mocked dependencies for review routes."""
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = 'googleapis.com'
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = MagicMock(
|
||||
job_id="test-job",
|
||||
status="in_review",
|
||||
review_token="test-review-token"
|
||||
)
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_jm
|
||||
|
||||
# Override review auth to bypass complex auth chain
|
||||
async def fake_review_auth():
|
||||
return ("test-job", "full")
|
||||
|
||||
with patch('backend.api.routes.jobs.job_manager', mock_jm), \
|
||||
patch('backend.services.job_manager.JobManager', mock_jm_factory), \
|
||||
patch('backend.services.firestore_service.firestore'), \
|
||||
patch('backend.services.storage_service.storage'), \
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
|
||||
# Override review auth dependency (must use the same function object used by routes)
|
||||
app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
|
||||
# Patch StorageService inside the review module
|
||||
with patch('backend.api.routes.review.StorageService', return_value=mock_storage):
|
||||
yield TestClient(app)
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
class TestSubmitAnnotations:
|
||||
"""Tests for POST /api/review/{job_id}/v1/annotations."""
|
||||
|
||||
def test_submit_single_annotation(self, client, mock_storage):
|
||||
"""Test submitting a single annotation stores to GCS."""
|
||||
annotation = {"annotation_type": "SOUND_ALIKE", "original_text": "helo", "corrected_text": "hello"}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=annotation)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["saved_count"] == 1
|
||||
|
||||
def test_submit_batch_annotations(self, client, mock_storage):
|
||||
"""Test submitting a batch of annotations."""
|
||||
payload = {
|
||||
"annotations": [
|
||||
{"annotation_type": "SOUND_ALIKE", "original_text": "a"},
|
||||
{"annotation_type": "EXTRA_WORDS", "original_text": "b"},
|
||||
]
|
||||
}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=payload)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["saved_count"] == 2
|
||||
assert data["total_count"] == 2
|
||||
|
||||
def test_annotations_stored_to_correct_gcs_path(self, client, mock_storage):
|
||||
"""Test annotations are stored at jobs/{job_id}/lyrics/annotations.json."""
|
||||
client.post(
|
||||
"/api/review/test-job/v1/annotations",
|
||||
json={"annotation_type": "MANUAL_EDIT"}
|
||||
)
|
||||
mock_storage.upload_json.assert_called_once()
|
||||
gcs_path = mock_storage.upload_json.call_args[0][0]
|
||||
assert gcs_path == "jobs/test-job/lyrics/annotations.json"
|
||||
|
||||
def test_annotations_merged_with_existing(self, client, mock_storage):
|
||||
"""Test new annotations are merged with existing ones."""
|
||||
# Set up existing annotations
|
||||
mock_storage.download_json.side_effect = None
|
||||
mock_storage.download_json.return_value = {
|
||||
"annotations": [{"annotation_type": "SOUND_ALIKE", "original_text": "existing"}]
|
||||
}
|
||||
|
||||
payload = {"annotations": [{"annotation_type": "EXTRA_WORDS", "original_text": "new"}]}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=payload)
|
||||
|
||||
data = response.json()
|
||||
assert data["saved_count"] == 1
|
||||
assert data["total_count"] == 2 # 1 existing + 1 new
|
||||
|
||||
# Verify merged data was uploaded
|
||||
uploaded_data = mock_storage.upload_json.call_args[0][1]
|
||||
assert len(uploaded_data["annotations"]) == 2
|
||||
|
||||
def test_annotations_fresh_when_no_existing(self, client, mock_storage):
|
||||
"""Test annotations start fresh when no existing file."""
|
||||
payload = {"annotations": [{"annotation_type": "NO_ERROR"}]}
|
||||
response = client.post("/api/review/test-job/v1/annotations", json=payload)
|
||||
assert response.json()["total_count"] == 1
|
||||
@@ -374,6 +374,169 @@ class TestCompleteReviewWithInstrumentalSelection:
|
||||
assert selection in ['clean', 'with_backing', 'custom']
|
||||
|
||||
|
||||
class TestSummaryEndpoint:
|
||||
"""Tests for the fields=summary query parameter on list_jobs.
|
||||
|
||||
When fields=summary, the endpoint uses Firestore field projection and
|
||||
returns pruned dicts instead of full Job models. This dramatically
|
||||
reduces payload size for the dashboard polling use case.
|
||||
"""
|
||||
|
||||
def test_prune_state_data_keeps_allowed_keys(self):
|
||||
"""Verify _prune_state_data keeps only dashboard-required keys."""
|
||||
from backend.api.routes.jobs import _prune_state_data
|
||||
|
||||
data = {
|
||||
'state_data': {
|
||||
'brand_code': 'NKP',
|
||||
'youtube_url': 'https://youtu.be/abc',
|
||||
'audio_progress': {'stage': 'separating'},
|
||||
'lyrics_progress': {'stage': 'transcribing'},
|
||||
'audio_complete': True,
|
||||
'lyrics_complete': True,
|
||||
'backing_vocals_analysis': {'recommended_selection': 'clean'},
|
||||
'dropbox_link': 'https://dropbox.com/s/...',
|
||||
# These should be stripped
|
||||
'corrected_lyrics': {'lines': [1, 2, 3]},
|
||||
'render_progress': {'stage': 'done'},
|
||||
'blocking_state_entered_at': '2026-01-01',
|
||||
}
|
||||
}
|
||||
|
||||
result = _prune_state_data(data)
|
||||
sd = result['state_data']
|
||||
assert 'brand_code' in sd
|
||||
assert 'youtube_url' in sd
|
||||
assert 'audio_progress' in sd
|
||||
assert 'lyrics_progress' in sd
|
||||
assert 'audio_complete' in sd
|
||||
assert 'lyrics_complete' in sd
|
||||
assert 'backing_vocals_analysis' in sd
|
||||
assert 'dropbox_link' in sd
|
||||
# Stripped keys
|
||||
assert 'corrected_lyrics' not in sd
|
||||
assert 'render_progress' not in sd
|
||||
assert 'blocking_state_entered_at' not in sd
|
||||
|
||||
def test_prune_state_data_handles_missing(self):
|
||||
"""Verify _prune_state_data is safe when state_data is absent."""
|
||||
from backend.api.routes.jobs import _prune_state_data
|
||||
|
||||
assert _prune_state_data({}) == {}
|
||||
assert _prune_state_data({'state_data': None}) == {'state_data': None}
|
||||
|
||||
def test_prune_file_urls_keeps_allowed_keys(self):
|
||||
"""Verify _prune_file_urls keeps only dashboard-required keys."""
|
||||
from backend.api.routes.jobs import _prune_file_urls
|
||||
|
||||
data = {
|
||||
'file_urls': {
|
||||
'finals': {'lossless_4k_mp4': 'gs://bucket/finals/4k.mp4'},
|
||||
'videos': {'with_vocals': 'gs://bucket/videos/wv.mkv'},
|
||||
'packages': {'cdg_zip': 'gs://bucket/packages/cdg.zip'},
|
||||
# These should be stripped
|
||||
'stems': {'clean': 'gs://bucket/stems/clean.flac'},
|
||||
'lyrics': {'corrections': 'gs://bucket/lyrics/c.json'},
|
||||
'screens': {'title': 'gs://bucket/screens/title.mov'},
|
||||
}
|
||||
}
|
||||
|
||||
result = _prune_file_urls(data)
|
||||
fu = result['file_urls']
|
||||
assert 'finals' in fu
|
||||
assert 'videos' in fu
|
||||
assert 'packages' in fu
|
||||
assert 'stems' not in fu
|
||||
assert 'lyrics' not in fu
|
||||
assert 'screens' not in fu
|
||||
|
||||
def test_prune_file_urls_handles_missing(self):
|
||||
"""Verify _prune_file_urls is safe when file_urls is absent."""
|
||||
from backend.api.routes.jobs import _prune_file_urls
|
||||
|
||||
assert _prune_file_urls({}) == {}
|
||||
assert _prune_file_urls({'file_urls': None}) == {'file_urls': None}
|
||||
|
||||
def test_summary_returns_only_expected_fields(self):
|
||||
"""Verify a pruned summary dict only contains dashboard fields."""
|
||||
from backend.api.routes.jobs import _prune_state_data, _prune_file_urls
|
||||
|
||||
raw = {
|
||||
'job_id': 'abc123',
|
||||
'status': 'pending',
|
||||
'progress': 0,
|
||||
'created_at': '2026-01-01T00:00:00',
|
||||
'artist': 'Test',
|
||||
'title': 'Song',
|
||||
'error_message': None,
|
||||
'non_interactive': False,
|
||||
'outputs_deleted_at': None,
|
||||
'user_email': 'test@example.com',
|
||||
'state_data': {
|
||||
'brand_code': 'NKP',
|
||||
'corrected_lyrics': 'should be removed',
|
||||
},
|
||||
'file_urls': {
|
||||
'finals': {'lossless_4k_mp4': 'gs://...'},
|
||||
'stems': {'clean': 'gs://...'},
|
||||
},
|
||||
}
|
||||
|
||||
result = _prune_file_urls(_prune_state_data(raw))
|
||||
|
||||
# state_data should only have brand_code
|
||||
assert list(result['state_data'].keys()) == ['brand_code']
|
||||
# file_urls should only have finals
|
||||
assert list(result['file_urls'].keys()) == ['finals']
|
||||
|
||||
def test_hide_completed_statuses(self):
|
||||
"""Verify _HIDE_COMPLETED_STATUSES only hides successful completions (not failed/cancelled)."""
|
||||
from backend.api.routes.jobs import _HIDE_COMPLETED_STATUSES
|
||||
|
||||
assert 'complete' in _HIDE_COMPLETED_STATUSES
|
||||
assert 'prep_complete' in _HIDE_COMPLETED_STATUSES
|
||||
# Failed/cancelled should NOT be hidden - users need to see these
|
||||
assert 'failed' not in _HIDE_COMPLETED_STATUSES
|
||||
assert 'cancelled' not in _HIDE_COMPLETED_STATUSES
|
||||
# Active statuses should NOT be in the list
|
||||
assert 'pending' not in _HIDE_COMPLETED_STATUSES
|
||||
assert 'downloading' not in _HIDE_COMPLETED_STATUSES
|
||||
|
||||
def test_exclude_test_works_with_summary_dicts(self):
|
||||
"""Verify test email filtering works on raw dicts (not Job models)."""
|
||||
from backend.utils.test_data import is_test_email
|
||||
|
||||
# Summary mode returns dicts, so exclude_test filters using dict access
|
||||
job_dicts = [
|
||||
{'job_id': '1', 'user_email': 'real@example.com'},
|
||||
{'job_id': '2', 'user_email': 'test@inbox.testmail.app'},
|
||||
{'job_id': '3', 'user_email': None},
|
||||
]
|
||||
|
||||
filtered = [j for j in job_dicts if not is_test_email(j.get('user_email') or "")]
|
||||
assert len(filtered) == 2
|
||||
assert filtered[0]['job_id'] == '1'
|
||||
assert filtered[1]['job_id'] == '3'
|
||||
|
||||
def test_full_response_unchanged_without_fields_param(self):
|
||||
"""Verify the endpoint returns full Job models when fields is not set.
|
||||
|
||||
This is a backward-compatibility test: the admin jobs page (adminApi.listAllJobs)
|
||||
does NOT send fields=summary, so it must continue receiving full Job objects.
|
||||
"""
|
||||
# When fields is None, the route falls through to the full Job path.
|
||||
# We verify this by checking that the route accepts fields=None gracefully.
|
||||
# (The actual HTTP test would require a TestClient, so here we verify
|
||||
# the route function signature accepts None.)
|
||||
import inspect
|
||||
from backend.api.routes.jobs import list_jobs
|
||||
|
||||
sig = inspect.signature(list_jobs)
|
||||
fields_param = sig.parameters.get('fields')
|
||||
assert fields_param is not None
|
||||
assert fields_param.default is None # Default should be None (full mode)
|
||||
|
||||
|
||||
class TestScreensWorkerBackingVocalsAnalysis:
|
||||
"""Tests documenting that backing vocals analysis now runs in screens_worker.
|
||||
|
||||
|
||||
@@ -613,3 +613,40 @@ class TestCorrectionFlowIntegration:
|
||||
# The corrections_updated key should be added
|
||||
assert "corrections_updated" not in file_urls_before["lyrics"]
|
||||
assert "corrections_updated" in file_urls_after["lyrics"]
|
||||
|
||||
|
||||
class TestInstrumentalSelectionValidation:
|
||||
"""Tests for instrumental_selection validation in complete_review."""
|
||||
|
||||
def test_custom_allowed_with_custom_instrumental_stem(self):
|
||||
"""'custom' should be valid when custom_instrumental stem exists (mute-region editing)."""
|
||||
from unittest.mock import Mock, patch, AsyncMock
|
||||
|
||||
valid_selections = ["clean", "with_backing"]
|
||||
# Simulate the validation logic from review.py
|
||||
stems = {"custom_instrumental": "jobs/test/stems/custom_instrumental.flac"}
|
||||
existing_instrumental_gcs_path = None
|
||||
if existing_instrumental_gcs_path or stems.get("custom_instrumental"):
|
||||
valid_selections.append("custom")
|
||||
|
||||
assert "custom" in valid_selections
|
||||
|
||||
def test_custom_allowed_with_uploaded_instrumental(self):
|
||||
"""'custom' should be valid when existing_instrumental_gcs_path is set."""
|
||||
valid_selections = ["clean", "with_backing"]
|
||||
stems = {}
|
||||
existing_instrumental_gcs_path = "uploads/test/audio/instrumental.flac"
|
||||
if existing_instrumental_gcs_path or stems.get("custom_instrumental"):
|
||||
valid_selections.append("custom")
|
||||
|
||||
assert "custom" in valid_selections
|
||||
|
||||
def test_custom_rejected_without_custom_stem_or_upload(self):
|
||||
"""'custom' should NOT be valid when neither custom stem nor upload exists."""
|
||||
valid_selections = ["clean", "with_backing"]
|
||||
stems = {"instrumental_clean": "jobs/test/stems/clean.flac"}
|
||||
existing_instrumental_gcs_path = None
|
||||
if existing_instrumental_gcs_path or stems.get("custom_instrumental"):
|
||||
valid_selections.append("custom")
|
||||
|
||||
assert "custom" not in valid_selections
|
||||
@@ -0,0 +1,230 @@
|
||||
"""
|
||||
Tests for audio select endpoint overrides (guided flow Step 3).
|
||||
|
||||
When the guided flow reaches Step 3 (Customize), the user can change:
|
||||
- is_private: Whether the job should use private distribution
|
||||
- display_artist: Override the display artist name
|
||||
- display_title: Override the display title
|
||||
|
||||
These overrides are sent with the select request and applied to the job
|
||||
BEFORE the pipeline starts, since the job was created in Step 2 before
|
||||
these fields were available.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, AsyncMock
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
|
||||
class TestAudioSelectRequestOverrides:
|
||||
"""Tests for AudioSelectRequest model with optional overrides."""
|
||||
|
||||
def test_model_accepts_overrides(self):
|
||||
"""Test AudioSelectRequest accepts is_private, display_artist, display_title."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
req = AudioSelectRequest(
|
||||
selection_index=0,
|
||||
is_private=True,
|
||||
display_artist="Custom Artist",
|
||||
display_title="Custom Title",
|
||||
)
|
||||
assert req.selection_index == 0
|
||||
assert req.is_private is True
|
||||
assert req.display_artist == "Custom Artist"
|
||||
assert req.display_title == "Custom Title"
|
||||
|
||||
def test_model_defaults_overrides_to_none(self):
|
||||
"""Test AudioSelectRequest defaults override fields to None."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
req = AudioSelectRequest(selection_index=0)
|
||||
assert req.is_private is None
|
||||
assert req.display_artist is None
|
||||
assert req.display_title is None
|
||||
|
||||
def test_model_accepts_is_private_false(self):
|
||||
"""Test AudioSelectRequest distinguishes is_private=False from None."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
req = AudioSelectRequest(selection_index=0, is_private=False)
|
||||
assert req.is_private is False
|
||||
|
||||
|
||||
class TestSelectEndpointAppliesOverrides:
|
||||
"""Tests that the select_audio_source endpoint applies overrides to the job."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(self):
|
||||
"""Mock the job manager singleton."""
|
||||
with patch('backend.api.routes.audio_search.job_manager') as mock:
|
||||
yield mock
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage_service(self):
|
||||
"""Mock the storage service singleton."""
|
||||
with patch('backend.api.routes.audio_search.storage_service') as mock:
|
||||
yield mock
|
||||
|
||||
def test_overrides_applied_before_selection(self, mock_job_manager, mock_storage_service):
|
||||
"""Test is_private and display overrides are applied to job before pipeline starts."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
# Setup mock job in AWAITING_AUDIO_SELECTION state
|
||||
mock_job = Mock()
|
||||
mock_job.status = JobStatus.AWAITING_AUDIO_SELECTION
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test Song',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'abc123',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
body = AudioSelectRequest(
|
||||
selection_index=0,
|
||||
is_private=True,
|
||||
display_artist="DJ Test",
|
||||
display_title="The Remix",
|
||||
)
|
||||
|
||||
# We test the override logic directly by checking update_job calls
|
||||
# The first update_job call should be the overrides (before _validate_and_prepare_selection)
|
||||
import asyncio
|
||||
from unittest.mock import call
|
||||
from fastapi import BackgroundTasks
|
||||
|
||||
# Mock BackgroundTasks and auth
|
||||
bg_tasks = Mock(spec=BackgroundTasks)
|
||||
auth_result = Mock()
|
||||
|
||||
# Mock the audio search service
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'):
|
||||
from backend.api.routes.audio_search import select_audio_source
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
select_audio_source(
|
||||
job_id="test-job",
|
||||
background_tasks=bg_tasks,
|
||||
body=body,
|
||||
auth_result=auth_result,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# The overrides should be applied via update_job
|
||||
update_calls = mock_job_manager.update_job.call_args_list
|
||||
# First call should be the overrides
|
||||
override_call = update_calls[0]
|
||||
assert override_call.args[0] == "test-job"
|
||||
override_data = override_call.args[1]
|
||||
assert override_data["is_private"] is True
|
||||
assert override_data["display_artist"] == "DJ Test"
|
||||
assert override_data["display_title"] == "The Remix"
|
||||
|
||||
def test_no_overrides_skips_update(self, mock_job_manager, mock_storage_service):
|
||||
"""Test that when no overrides are provided, update_job is NOT called for overrides."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.status = JobStatus.AWAITING_AUDIO_SELECTION
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test Song',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'abc123',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
body = AudioSelectRequest(selection_index=0)
|
||||
|
||||
import asyncio
|
||||
from fastapi import BackgroundTasks
|
||||
|
||||
bg_tasks = Mock(spec=BackgroundTasks)
|
||||
auth_result = Mock()
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'):
|
||||
from backend.api.routes.audio_search import select_audio_source
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
select_audio_source(
|
||||
job_id="test-job",
|
||||
background_tasks=bg_tasks,
|
||||
body=body,
|
||||
auth_result=auth_result,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# update_job will be called by _validate_and_prepare_selection for download params
|
||||
# but NOT for overrides. The override call would have is_private/display_artist/display_title
|
||||
for call_args in mock_job_manager.update_job.call_args_list:
|
||||
update_data = call_args.args[1]
|
||||
assert "is_private" not in update_data
|
||||
assert "display_artist" not in update_data
|
||||
assert "display_title" not in update_data
|
||||
|
||||
def test_partial_overrides_only_applies_provided(self, mock_job_manager, mock_storage_service):
|
||||
"""Test that only provided override fields are sent to update_job."""
|
||||
from backend.api.routes.audio_search import AudioSelectRequest
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.status = JobStatus.AWAITING_AUDIO_SELECTION
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test Song',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
'source_id': 'abc123',
|
||||
'target_file': 'test.flac',
|
||||
'url': '',
|
||||
}]
|
||||
}
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
# Only is_private, no display overrides
|
||||
body = AudioSelectRequest(selection_index=0, is_private=True)
|
||||
|
||||
import asyncio
|
||||
from fastapi import BackgroundTasks
|
||||
|
||||
bg_tasks = Mock(spec=BackgroundTasks)
|
||||
auth_result = Mock()
|
||||
|
||||
with patch('backend.api.routes.audio_search.get_audio_search_service'):
|
||||
from backend.api.routes.audio_search import select_audio_source
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
select_audio_source(
|
||||
job_id="test-job",
|
||||
background_tasks=bg_tasks,
|
||||
body=body,
|
||||
auth_result=auth_result,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Find the override call (first update_job call)
|
||||
override_call = mock_job_manager.update_job.call_args_list[0]
|
||||
override_data = override_call.args[1]
|
||||
assert override_data == {"is_private": True}
|
||||
assert "display_artist" not in override_data
|
||||
assert "display_title" not in override_data
|
||||
@@ -184,7 +184,12 @@ class TestWorkerService:
|
||||
mock_run_v2.RunJobRequest.Overrides = MagicMock()
|
||||
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
|
||||
|
||||
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}):
|
||||
# Patch both sys.modules and the parent package attribute to ensure
|
||||
# 'from google.cloud import run_v2' resolves to our mock regardless
|
||||
# of whether the real package is installed (namespace package resolution)
|
||||
import google.cloud
|
||||
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
|
||||
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
|
||||
service = WorkerService()
|
||||
result = await service.trigger_audio_worker("test123")
|
||||
|
||||
@@ -222,7 +227,12 @@ class TestWorkerService:
|
||||
mock_run_v2.RunJobRequest.Overrides = MagicMock()
|
||||
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
|
||||
|
||||
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}):
|
||||
# Patch both sys.modules and the parent package attribute to ensure
|
||||
# 'from google.cloud import run_v2' resolves to our mock regardless
|
||||
# of whether the real package is installed (namespace package resolution)
|
||||
import google.cloud
|
||||
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
|
||||
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
|
||||
service = WorkerService()
|
||||
result = await service.trigger_lyrics_worker("test123")
|
||||
|
||||
|
||||
@@ -0,0 +1,959 @@
|
||||
"""
|
||||
Unit tests for the standalone search + create-from-search guided flow.
|
||||
|
||||
Covers:
|
||||
- FirestoreService search session CRUD (including consume_search_session)
|
||||
- POST /api/audio-search/search-standalone (no job created)
|
||||
- POST /api/jobs/create-from-search (session validation, ownership, tenant, job creation)
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, timedelta, UTC
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_mock_creds():
|
||||
creds = MagicMock()
|
||||
creds.universe_domain = "googleapis.com"
|
||||
return creds
|
||||
|
||||
|
||||
def _make_mock_job_manager(job=None):
|
||||
mgr = MagicMock()
|
||||
if job is None:
|
||||
job = Job(
|
||||
job_id="test-job-123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
)
|
||||
mgr.create_job.return_value = job
|
||||
mgr.get_job.return_value = job
|
||||
mgr.update_job.return_value = None
|
||||
mgr.update_state_data.return_value = None
|
||||
return mgr
|
||||
|
||||
|
||||
def _make_search_session(user_email="test@example.com", expired=False, tenant_id=None):
|
||||
now = datetime.utcnow()
|
||||
ttl = now - timedelta(hours=1) if expired else now + timedelta(minutes=30)
|
||||
return {
|
||||
"session_id": "sess-abc-123",
|
||||
"user_email": user_email,
|
||||
"tenant_id": tenant_id,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"results": [
|
||||
{
|
||||
"index": 0,
|
||||
"title": "Waterloo",
|
||||
"artist": "ABBA",
|
||||
"provider": "YouTube",
|
||||
"url": "https://youtube.com/watch?v=abc",
|
||||
}
|
||||
],
|
||||
"remote_search_id": None,
|
||||
"created_at": now.isoformat(),
|
||||
"ttl_expiry": ttl,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# State machine — PENDING → DOWNLOADING_AUDIO transition
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestStateTransitionPendingToDownloadingAudio:
|
||||
"""Verify PENDING → DOWNLOADING_AUDIO is a valid state transition (create-from-search path)."""
|
||||
|
||||
def test_pending_allows_downloading_audio_transition(self):
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
assert JobStatus.DOWNLOADING_AUDIO in STATE_TRANSITIONS[JobStatus.PENDING]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# FirestoreService session CRUD
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestFirestoreServiceSearchSessionCRUD:
|
||||
"""Unit tests for search session CRUD methods on FirestoreService."""
|
||||
|
||||
def test_create_search_session_stores_document(self):
|
||||
"""create_search_session should write to Firestore and return session_id."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
session_data = {
|
||||
"session_id": "sess-xyz",
|
||||
"user_email": "user@example.com",
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"results": [],
|
||||
}
|
||||
returned_id = svc.create_search_session(session_data)
|
||||
|
||||
mock_db.collection.assert_called_once_with("search_sessions")
|
||||
mock_collection.document.assert_called_once_with("sess-xyz")
|
||||
mock_doc.set.assert_called_once_with(session_data)
|
||||
assert returned_id == "sess-xyz"
|
||||
|
||||
def test_get_search_session_returns_dict_when_exists(self):
|
||||
"""get_search_session should return doc dict when document exists."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
session_dict = {"session_id": "sess-xyz", "user_email": "user@example.com"}
|
||||
mock_snapshot = MagicMock()
|
||||
mock_snapshot.exists = True
|
||||
mock_snapshot.to_dict.return_value = session_dict
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.get.return_value = mock_snapshot
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
result = svc.get_search_session("sess-xyz")
|
||||
|
||||
assert result == session_dict
|
||||
|
||||
def test_get_search_session_returns_none_when_missing(self):
|
||||
"""get_search_session should return None when document doesn't exist."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_snapshot = MagicMock()
|
||||
mock_snapshot.exists = False
|
||||
mock_doc = MagicMock()
|
||||
mock_doc.get.return_value = mock_snapshot
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
result = svc.get_search_session("nonexistent-session")
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_get_search_session_raises_on_firestore_error(self):
|
||||
"""get_search_session should raise (not return None) on Firestore errors."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.side_effect = Exception("Firestore unavailable")
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
with pytest.raises(Exception, match="Firestore unavailable"):
|
||||
svc.get_search_session("sess-xyz")
|
||||
|
||||
def test_consume_search_session_returns_session_and_deletes_atomically(self):
|
||||
"""consume_search_session should return session data and delete within transaction."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from google.cloud import firestore as fs
|
||||
|
||||
session_dict = {"session_id": "sess-xyz", "user_email": "user@example.com"}
|
||||
|
||||
mock_snapshot = MagicMock()
|
||||
mock_snapshot.exists = True
|
||||
mock_snapshot.to_dict.return_value = session_dict
|
||||
|
||||
mock_doc_ref = MagicMock()
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc_ref
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
# Simulate Firestore transaction: the @transactional function gets called
|
||||
# with a transaction object; we simulate by calling the inner function directly.
|
||||
captured_fn = {}
|
||||
|
||||
def fake_transactional(fn):
|
||||
captured_fn['fn'] = fn
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return fn(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
mock_transaction = MagicMock()
|
||||
mock_doc_ref.get.return_value = mock_snapshot
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
with patch.object(fs, 'transactional', fake_transactional):
|
||||
result = svc.consume_search_session("sess-xyz")
|
||||
|
||||
assert result == session_dict
|
||||
|
||||
def test_consume_search_session_returns_none_when_missing(self):
|
||||
"""consume_search_session returns None when document doesn't exist."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from google.cloud import firestore as fs
|
||||
|
||||
mock_snapshot = MagicMock()
|
||||
mock_snapshot.exists = False
|
||||
|
||||
mock_doc_ref = MagicMock()
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc_ref
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
def fake_transactional(fn):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return fn(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
mock_transaction = MagicMock()
|
||||
mock_doc_ref.get.return_value = mock_snapshot
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
with patch.object(fs, 'transactional', fake_transactional):
|
||||
result = svc.consume_search_session("nonexistent-session")
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_delete_search_session_calls_firestore_delete(self):
|
||||
"""delete_search_session should call Firestore delete."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_doc = MagicMock()
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.return_value = mock_doc
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
svc.delete_search_session("sess-xyz")
|
||||
|
||||
mock_doc.delete.assert_called_once()
|
||||
|
||||
def test_delete_search_session_silently_ignores_errors(self):
|
||||
"""delete_search_session should not raise on Firestore errors."""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
mock_collection = MagicMock()
|
||||
mock_collection.document.side_effect = Exception("Connection error")
|
||||
mock_db = MagicMock()
|
||||
mock_db.collection.return_value = mock_collection
|
||||
|
||||
svc = FirestoreService.__new__(FirestoreService)
|
||||
svc.db = mock_db
|
||||
|
||||
# Should not raise
|
||||
svc.delete_search_session("sess-xyz")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# POST /api/audio-search/search-standalone
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def standalone_client(mock_job_manager_standalone):
|
||||
"""TestClient for standalone search tests."""
|
||||
from backend.services.audio_search_service import AudioSearchResult
|
||||
|
||||
mock_search_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="YouTube",
|
||||
url="https://youtube.com/watch?v=abc",
|
||||
duration=180,
|
||||
quality="320kbps",
|
||||
source_id="abc",
|
||||
index=0,
|
||||
)
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
mock_audio_search.search_async = AsyncMock(return_value=[mock_search_result])
|
||||
mock_audio_search.last_remote_search_id = None
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.create_search_session.return_value = "sess-new-123"
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_standalone
|
||||
|
||||
with patch("backend.api.routes.audio_search.job_manager", mock_job_manager_standalone), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.api.routes.audio_search.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
client._mock_audio_search = mock_audio_search
|
||||
client._mock_firestore = mock_firestore
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager_standalone():
|
||||
return _make_mock_job_manager()
|
||||
|
||||
|
||||
class TestSearchAudioStandalone:
|
||||
"""Tests for POST /api/audio-search/search-standalone."""
|
||||
|
||||
def test_returns_200_and_session_id(self, standalone_client, auth_headers):
|
||||
"""Successful search returns 200 with search_session_id."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "search_session_id" in data
|
||||
assert data["results_count"] == 1
|
||||
|
||||
def test_returns_results_in_response(self, standalone_client, auth_headers):
|
||||
"""Response includes search result details."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
data = response.json()
|
||||
results = data["results"]
|
||||
assert len(results) == 1
|
||||
assert results[0]["title"] == "Waterloo"
|
||||
assert results[0]["provider"] == "YouTube"
|
||||
|
||||
def test_no_job_is_created(self, standalone_client, mock_job_manager_standalone, auth_headers):
|
||||
"""Standalone search must NOT create any job."""
|
||||
standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
mock_job_manager_standalone.create_job.assert_not_called()
|
||||
|
||||
def test_session_is_stored_in_firestore(self, standalone_client, auth_headers):
|
||||
"""Search session is stored in Firestore."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
standalone_client._mock_firestore.create_search_session.assert_called_once()
|
||||
|
||||
def test_no_results_returns_empty_list(self, mock_job_manager_standalone, auth_headers):
|
||||
"""No-results case returns empty results list, not an error."""
|
||||
from backend.services.audio_search_service import NoResultsError
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
mock_audio_search.search_async = AsyncMock(side_effect=NoResultsError("No results"))
|
||||
mock_audio_search.last_remote_search_id = None
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_standalone
|
||||
|
||||
with patch("backend.api.routes.audio_search.job_manager", mock_job_manager_standalone), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.api.routes.audio_search.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "Unknown Artist", "title": "Unknown Song"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["results"] == []
|
||||
assert data["results_count"] == 0
|
||||
|
||||
def test_missing_artist_returns_422(self, standalone_client, auth_headers):
|
||||
"""Missing required artist field returns 422 validation error."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_missing_title_returns_422(self, standalone_client, auth_headers):
|
||||
"""Missing required title field returns 422 validation error."""
|
||||
response = standalone_client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# POST /api/jobs/create-from-search
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def create_from_search_client(mock_job_manager_cfs):
|
||||
"""TestClient for create-from-search tests with a valid session in Firestore."""
|
||||
session = _make_search_session(user_email="test@example.com")
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
mock_firestore.consume_search_session.return_value = session
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.api.routes.audio_search._validate_and_prepare_selection"), \
|
||||
patch("backend.api.routes.audio_search._download_audio_and_trigger_workers"), \
|
||||
patch("backend.api.routes.audio_search.extract_request_metadata", return_value={}), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
client._mock_firestore = mock_firestore
|
||||
client._mock_jm = mock_job_manager_cfs
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager_cfs():
|
||||
return _make_mock_job_manager()
|
||||
|
||||
|
||||
class TestCreateJobFromSearch:
|
||||
"""Tests for POST /api/jobs/create-from-search."""
|
||||
|
||||
def test_returns_200_with_job_id(self, create_from_search_client, auth_headers):
|
||||
"""Successful call returns 200 with job_id."""
|
||||
response = create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "job_id" in data
|
||||
assert data["job_id"] == "test-job-123"
|
||||
|
||||
def test_job_is_created_via_job_manager(self, create_from_search_client, auth_headers):
|
||||
"""Job must be created through job_manager.create_job."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
create_from_search_client._mock_jm.create_job.assert_called_once()
|
||||
|
||||
def test_is_private_flag_passed_to_job(self, create_from_search_client, auth_headers):
|
||||
"""is_private flag is included in JobCreate passed to job_manager."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"is_private": True,
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
job_create = call_args[0][0] # First positional arg
|
||||
assert job_create.is_private is True
|
||||
|
||||
def test_display_overrides_applied_when_provided(self, create_from_search_client, auth_headers):
|
||||
"""display_artist and display_title overrides are applied."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"display_artist": "Abba (Display)",
|
||||
"display_title": "Waterloo (Karaoke)",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
job_create = call_args[0][0]
|
||||
assert job_create.artist == "Abba (Display)"
|
||||
assert job_create.title == "Waterloo (Karaoke)"
|
||||
|
||||
def test_session_consumed_atomically(self, create_from_search_client, auth_headers):
|
||||
"""Session is consumed (atomically read+deleted) via consume_search_session."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
# consume_search_session handles both read + delete atomically
|
||||
create_from_search_client._mock_firestore.consume_search_session.assert_called_once_with(
|
||||
"sess-abc-123"
|
||||
)
|
||||
# No separate delete_search_session call needed
|
||||
create_from_search_client._mock_firestore.delete_search_session.assert_not_called()
|
||||
|
||||
def test_missing_session_returns_404(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 404 when search session is not found (expired or invalid)."""
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = None # session not found
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "expired-session",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "Search expired" in response.json()["detail"]
|
||||
|
||||
def test_expired_ttl_returns_404(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 404 when session TTL has passed (belt-and-suspenders check)."""
|
||||
expired_session = _make_search_session(user_email="test@example.com", expired=True)
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = expired_session
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "Search expired" in response.json()["detail"]
|
||||
|
||||
def test_tenant_mismatch_returns_403(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 403 when session tenant_id doesn't match the request tenant."""
|
||||
# Session was created in tenant "tenant-a"
|
||||
session_with_tenant = _make_search_session(user_email="test@example.com", tenant_id="tenant-a")
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session_with_tenant
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
# Request arrives from the default (no-tenant) context — tenant_id=None in request.state
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 403
|
||||
|
||||
def test_invalid_selection_index_returns_400(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 400 when selection_index is out of bounds."""
|
||||
session = _make_search_session() # 1 result at index 0
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 99, # out of range
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "Invalid selection index" in response.json()["detail"]
|
||||
|
||||
def test_missing_required_fields_returns_422(self, create_from_search_client, auth_headers):
|
||||
"""Missing required fields return 422 validation error."""
|
||||
response = create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={"search_session_id": "sess-abc-123"}, # missing selection_index, artist, title
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_no_awaiting_selection_state(self, create_from_search_client, auth_headers):
|
||||
"""Job goes directly to downloading — AWAITING_AUDIO_SELECTION is never set."""
|
||||
create_from_search_client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
# The created job should NOT be in AWAITING_AUDIO_SELECTION
|
||||
# (we verify job_manager.create_job was called and the job status is not AWAITING)
|
||||
call_args = create_from_search_client._mock_jm.create_job.call_args
|
||||
assert call_args is not None # job was created
|
||||
# The initial status is PENDING — it's then moved to DOWNLOADING_AUDIO
|
||||
# by _validate_and_prepare_selection (which is mocked here)
|
||||
created_job = create_from_search_client._mock_jm.create_job.return_value
|
||||
assert created_job.status != JobStatus.AWAITING_AUDIO_SELECTION
|
||||
|
||||
def test_different_user_cannot_use_anothers_session(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Returns 403 when session belongs to a different user (ownership check)."""
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
# Session belongs to alice, but request comes from bob (non-admin)
|
||||
session = _make_search_session(user_email="alice@example.com")
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
async def bob_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.LIMITED,
|
||||
remaining_uses=5, message="OK", is_admin=False,
|
||||
user_email="bob@example.com",
|
||||
)
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
app.dependency_overrides[require_auth] = bob_auth
|
||||
try:
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
finally:
|
||||
# Restore the default admin mock
|
||||
# Restore the default admin auth (same as conftest autouse fixture)
|
||||
async def _restore_admin_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.ADMIN,
|
||||
remaining_uses=999, message="Test admin token",
|
||||
is_admin=True, user_email="test@example.com",
|
||||
)
|
||||
app.dependency_overrides[require_auth] = _restore_admin_auth
|
||||
|
||||
assert response.status_code == 403
|
||||
|
||||
def test_remote_search_id_stored_in_state_data(self, mock_job_manager_cfs, auth_headers):
|
||||
"""remote_search_id from session is copied to job state_data."""
|
||||
session = _make_search_session(user_email="test@example.com")
|
||||
session["remote_search_id"] = "torrent-search-42"
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
mock_firestore.consume_search_session.return_value = session
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.api.routes.audio_search._validate_and_prepare_selection"), \
|
||||
patch("backend.api.routes.audio_search._download_audio_and_trigger_workers"), \
|
||||
patch("backend.api.routes.audio_search.extract_request_metadata", return_value={}), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Check that update_job was called with state_data containing remote_search_id
|
||||
update_calls = mock_job_manager_cfs.update_job.call_args_list
|
||||
state_data_call = [c for c in update_calls if 'state_data' in c[0][1]]
|
||||
assert len(state_data_call) >= 1
|
||||
state_data = state_data_call[0][0][1]['state_data']
|
||||
assert state_data['remote_search_id'] == "torrent-search-42"
|
||||
|
||||
def test_concurrent_consume_second_request_returns_404(self, mock_job_manager_cfs, auth_headers):
|
||||
"""Second concurrent request to same session gets 404 (session already consumed)."""
|
||||
session = _make_search_session(user_email="test@example.com")
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_firestore.get_search_session.return_value = session
|
||||
# First consume succeeds, simulating that another request already consumed it
|
||||
mock_firestore.consume_search_session.return_value = None
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
|
||||
mock_theme_service = MagicMock()
|
||||
mock_theme_service.get_default_theme_id.return_value = None
|
||||
|
||||
mock_creds = _make_mock_creds()
|
||||
|
||||
def mock_jm_factory(*args, **kwargs):
|
||||
return mock_job_manager_cfs
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_job_manager_cfs), \
|
||||
patch("backend.api.routes.jobs.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
|
||||
patch("backend.api.routes.audio_search._validate_and_prepare_selection"), \
|
||||
patch("backend.api.routes.audio_search._download_audio_and_trigger_workers"), \
|
||||
patch("backend.api.routes.audio_search.extract_request_metadata", return_value={}), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.services.job_manager.JobManager", mock_jm_factory), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.post(
|
||||
"/api/jobs/create-from-search",
|
||||
json={
|
||||
"search_session_id": "sess-abc-123",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
},
|
||||
headers=auth_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "Search expired" in response.json()["detail"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# POST /api/audio-search/search-standalone — credit check
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSearchStandaloneCredits:
|
||||
"""Tests for credit checking on the standalone search endpoint."""
|
||||
|
||||
def test_insufficient_credits_returns_402(self, auth_headers):
|
||||
"""Non-admin user with no credits gets 402 on search."""
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
mock_audio_search = MagicMock()
|
||||
mock_user_service = MagicMock()
|
||||
mock_user_service.has_credits.return_value = False
|
||||
mock_user_service.check_credits.return_value = 0
|
||||
|
||||
mock_firestore = MagicMock()
|
||||
mock_creds = _make_mock_creds()
|
||||
mock_jm = _make_mock_job_manager()
|
||||
|
||||
async def regular_user_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.LIMITED,
|
||||
remaining_uses=0, message="OK", is_admin=False,
|
||||
user_email="user@example.com",
|
||||
)
|
||||
|
||||
with patch("backend.api.routes.audio_search.job_manager", mock_jm), \
|
||||
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=mock_audio_search), \
|
||||
patch("backend.api.routes.audio_search.FirestoreService", return_value=mock_firestore), \
|
||||
patch("backend.services.user_service.get_user_service", return_value=mock_user_service), \
|
||||
patch("backend.services.job_manager.JobManager", lambda *a, **k: mock_jm), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
app.dependency_overrides[require_auth] = regular_user_auth
|
||||
try:
|
||||
client = TestClient(app, raise_server_exceptions=False)
|
||||
response = client.post(
|
||||
"/api/audio-search/search-standalone",
|
||||
json={"artist": "ABBA", "title": "Waterloo"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
finally:
|
||||
# Restore the default admin auth (same as conftest autouse fixture)
|
||||
async def _restore_admin_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.ADMIN,
|
||||
remaining_uses=999, message="Test admin token",
|
||||
is_admin=True, user_email="test@example.com",
|
||||
)
|
||||
app.dependency_overrides[require_auth] = _restore_admin_auth
|
||||
|
||||
assert response.status_code == 402
|
||||
data = response.json()
|
||||
assert "credits" in data["detail"].lower()
|
||||
@@ -0,0 +1,310 @@
|
||||
"""
|
||||
Tests for whitelabel tenant separation (magic link redirect fix, frontend URL, verify response,
|
||||
tenant-scoped tokens).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from backend.models.tenant import TenantConfig, TenantAuth, TenantBranding
|
||||
from backend.models.user import VerifyMagicLinkResponse, UserPublic
|
||||
from backend.services.auth_service import AuthResult, AuthService, UserType
|
||||
|
||||
|
||||
class TestTenantConfigGetFrontendUrl:
|
||||
"""Tests for TenantConfig.get_frontend_url()."""
|
||||
|
||||
def test_returns_https_url_with_subdomain(self):
|
||||
config = TenantConfig(
|
||||
id="vocalstar",
|
||||
name="Vocal Star",
|
||||
subdomain="vocalstar.nomadkaraoke.com",
|
||||
)
|
||||
assert config.get_frontend_url() == "https://vocalstar.nomadkaraoke.com"
|
||||
|
||||
def test_different_tenant(self):
|
||||
config = TenantConfig(
|
||||
id="singa",
|
||||
name="Singa",
|
||||
subdomain="singa.nomadkaraoke.com",
|
||||
)
|
||||
assert config.get_frontend_url() == "https://singa.nomadkaraoke.com"
|
||||
|
||||
|
||||
class TestSendMagicLinkTenantParams:
|
||||
"""Tests for EmailService.send_magic_link() with tenant parameters."""
|
||||
|
||||
@pytest.fixture
|
||||
def email_service(self):
|
||||
"""Create an EmailService with a mock provider."""
|
||||
from backend.services.email_service import EmailService
|
||||
service = EmailService()
|
||||
service.provider = MagicMock()
|
||||
service.provider.send_email = MagicMock(return_value=True)
|
||||
return service
|
||||
|
||||
def test_default_uses_nomad_karaoke_branding(self, email_service):
|
||||
"""Without tenant params, email uses default Nomad Karaoke branding."""
|
||||
email_service.send_magic_link("user@test.com", "abc123")
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
subject = call_args[0][1]
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
|
||||
assert subject == "Sign in to Nomad Karaoke"
|
||||
assert "Nomad Karaoke" in html_content
|
||||
assert "Nomad Karaoke" in text_content
|
||||
# Default URL should be used
|
||||
assert f"{email_service.frontend_url}/auth/verify" in html_content
|
||||
|
||||
def test_tenant_url_used_in_magic_link(self, email_service):
|
||||
"""When tenant_frontend_url is provided, magic link points to tenant domain."""
|
||||
email_service.send_magic_link(
|
||||
"user@vocal-star.com",
|
||||
"abc123",
|
||||
tenant_frontend_url="https://vocalstar.nomadkaraoke.com",
|
||||
)
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
|
||||
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in html_content
|
||||
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in text_content
|
||||
# Should NOT contain default URL
|
||||
assert "gen.nomadkaraoke.com" not in html_content
|
||||
|
||||
def test_tenant_name_used_in_subject_and_body(self, email_service):
|
||||
"""When tenant_name is provided, email uses tenant brand name."""
|
||||
email_service.send_magic_link(
|
||||
"user@vocal-star.com",
|
||||
"abc123",
|
||||
tenant_name="Vocal Star",
|
||||
)
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
subject = call_args[0][1]
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
|
||||
assert subject == "Sign in to Vocal Star"
|
||||
assert "Vocal Star" in html_content
|
||||
assert "Vocal Star" in text_content
|
||||
|
||||
def test_tenant_name_html_escaped(self, email_service):
|
||||
"""Tenant name is HTML-escaped to prevent XSS."""
|
||||
email_service.send_magic_link(
|
||||
"user@test.com",
|
||||
"abc123",
|
||||
tenant_name='<script>alert("xss")</script>',
|
||||
)
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
html_content = call_args[0][2]
|
||||
|
||||
# Should be escaped in HTML
|
||||
assert "<script>" not in html_content
|
||||
assert "<script>" in html_content
|
||||
|
||||
def test_all_tenant_params_together(self, email_service):
|
||||
"""Test sending magic link with all tenant parameters."""
|
||||
result = email_service.send_magic_link(
|
||||
"user@vocal-star.com",
|
||||
"token123",
|
||||
sender_email="vocalstar@nomadkaraoke.com",
|
||||
tenant_frontend_url="https://vocalstar.nomadkaraoke.com",
|
||||
tenant_name="Vocal Star",
|
||||
)
|
||||
|
||||
assert result is True
|
||||
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
subject = call_args[0][1]
|
||||
html_content = call_args[0][2]
|
||||
|
||||
assert subject == "Sign in to Vocal Star"
|
||||
assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=token123" in html_content
|
||||
# Check sender email override was passed through
|
||||
assert call_args[1]["from_email_override"] == "vocalstar@nomadkaraoke.com"
|
||||
|
||||
|
||||
class TestVerifyMagicLinkResponseTenantSubdomain:
|
||||
"""Tests for tenant_subdomain field in VerifyMagicLinkResponse."""
|
||||
|
||||
def test_response_without_tenant(self):
|
||||
"""Verify response without tenant has null subdomain."""
|
||||
user = UserPublic(email="user@test.com", role="user", credits=2)
|
||||
response = VerifyMagicLinkResponse(
|
||||
status="success",
|
||||
session_token="sess_123",
|
||||
user=user,
|
||||
message="ok",
|
||||
)
|
||||
assert response.tenant_subdomain is None
|
||||
|
||||
def test_response_with_tenant_subdomain(self):
|
||||
"""Verify response includes tenant subdomain when provided."""
|
||||
user = UserPublic(email="user@vocal-star.com", role="user", credits=2)
|
||||
response = VerifyMagicLinkResponse(
|
||||
status="success",
|
||||
session_token="sess_123",
|
||||
user=user,
|
||||
message="ok",
|
||||
tenant_subdomain="vocalstar.nomadkaraoke.com",
|
||||
)
|
||||
assert response.tenant_subdomain == "vocalstar.nomadkaraoke.com"
|
||||
|
||||
def test_response_serialization_includes_tenant_subdomain(self):
|
||||
"""Verify response serializes tenant_subdomain correctly."""
|
||||
user = UserPublic(email="user@test.com", role="user", credits=2)
|
||||
response = VerifyMagicLinkResponse(
|
||||
status="success",
|
||||
session_token="sess_123",
|
||||
user=user,
|
||||
message="ok",
|
||||
tenant_subdomain="singa.nomadkaraoke.com",
|
||||
)
|
||||
data = response.model_dump()
|
||||
assert data["tenant_subdomain"] == "singa.nomadkaraoke.com"
|
||||
|
||||
|
||||
class TestTenantScopedTokens:
|
||||
"""Tests for tenant_id propagation from Firestore auth tokens to AuthResult."""
|
||||
|
||||
@pytest.fixture
|
||||
def auth_service(self):
|
||||
"""Create an AuthService with mocked Firestore."""
|
||||
service = AuthService()
|
||||
service.firestore = MagicMock()
|
||||
service.admin_tokens = set()
|
||||
return service
|
||||
|
||||
def test_token_without_tenant_id(self, auth_service):
|
||||
"""Auth token without tenant_id returns None tenant_id in result."""
|
||||
auth_service.firestore.get_token.return_value = {
|
||||
"type": "unlimited",
|
||||
"active": True,
|
||||
"user_email": "user@test.com",
|
||||
}
|
||||
result = auth_service.validate_token_full("test-token")
|
||||
assert result.is_valid is True
|
||||
assert result.tenant_id is None
|
||||
|
||||
def test_token_with_tenant_id(self, auth_service):
|
||||
"""Auth token with tenant_id propagates it to AuthResult."""
|
||||
auth_service.firestore.get_token.return_value = {
|
||||
"type": "unlimited",
|
||||
"active": True,
|
||||
"user_email": "admin@nomadkaraoke.com",
|
||||
"tenant_id": "vocalstar",
|
||||
}
|
||||
result = auth_service.validate_token_full("test-token")
|
||||
assert result.is_valid is True
|
||||
assert result.tenant_id == "vocalstar"
|
||||
assert result.is_admin is True
|
||||
|
||||
def test_limited_token_with_tenant_id(self, auth_service):
|
||||
"""Limited token with tenant_id propagates it."""
|
||||
auth_service.firestore.get_token.return_value = {
|
||||
"type": "limited",
|
||||
"active": True,
|
||||
"user_email": "user@test.com",
|
||||
"tenant_id": "singa",
|
||||
"max_uses": 10,
|
||||
"usage_count": 3,
|
||||
}
|
||||
result = auth_service.validate_token_full("test-token")
|
||||
assert result.is_valid is True
|
||||
assert result.tenant_id == "singa"
|
||||
assert result.remaining_uses == 7
|
||||
|
||||
def test_api_key_with_tenant_id(self, auth_service):
|
||||
"""API key token with tenant_id propagates it."""
|
||||
auth_service.firestore.get_token.return_value = {
|
||||
"type": "api_key",
|
||||
"active": True,
|
||||
"user_email": "api@vocal-star.com",
|
||||
"tenant_id": "vocalstar",
|
||||
"api_key_id": "ak_123",
|
||||
}
|
||||
result = auth_service.validate_token_full("test-token")
|
||||
assert result.is_valid is True
|
||||
assert result.tenant_id == "vocalstar"
|
||||
assert result.api_key_id == "ak_123"
|
||||
|
||||
def test_admin_env_token_has_no_tenant_id(self, auth_service):
|
||||
"""Admin tokens from env var should not have tenant scoping."""
|
||||
auth_service.admin_tokens = {"admin-secret-token"}
|
||||
result = auth_service.validate_token_full("admin-secret-token")
|
||||
assert result.is_valid is True
|
||||
assert result.is_admin is True
|
||||
assert result.tenant_id is None
|
||||
|
||||
|
||||
class TestRequireAuthTenantOverride:
|
||||
"""Tests for tenant_id override logic in require_auth dependency."""
|
||||
|
||||
def _make_request(self, initial_tenant_id="hostname-tenant"):
|
||||
"""Create a mock Request with request.state.tenant_id pre-set."""
|
||||
request = MagicMock()
|
||||
request.state.tenant_id = initial_tenant_id
|
||||
request.state.request_id = "req-123"
|
||||
request.headers.get.return_value = ""
|
||||
return request
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auth_result_with_tenant_id_overrides_request_state(self):
|
||||
"""When auth_result has tenant_id, it overrides the hostname-based tenant_id."""
|
||||
from backend.api.dependencies import require_auth
|
||||
|
||||
request = self._make_request(initial_tenant_id="hostname-tenant")
|
||||
|
||||
mock_auth_result = AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.UNLIMITED,
|
||||
remaining_uses=-1,
|
||||
message="ok",
|
||||
tenant_id="token-tenant",
|
||||
)
|
||||
mock_auth_service = MagicMock()
|
||||
mock_auth_service.validate_token_full.return_value = mock_auth_result
|
||||
|
||||
with patch("backend.api.dependencies.get_auth_service", return_value=mock_auth_service):
|
||||
result = await require_auth(
|
||||
request=request,
|
||||
auth_service=mock_auth_service,
|
||||
credentials=MagicMock(credentials="valid-token"),
|
||||
token=None,
|
||||
)
|
||||
|
||||
assert result.tenant_id == "token-tenant"
|
||||
assert request.state.tenant_id == "token-tenant"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auth_result_without_tenant_id_leaves_request_state_unchanged(self):
|
||||
"""When auth_result has no tenant_id, request.state.tenant_id is not changed."""
|
||||
from backend.api.dependencies import require_auth
|
||||
|
||||
request = self._make_request(initial_tenant_id="hostname-tenant")
|
||||
|
||||
mock_auth_result = AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.UNLIMITED,
|
||||
remaining_uses=-1,
|
||||
message="ok",
|
||||
tenant_id=None,
|
||||
)
|
||||
mock_auth_service = MagicMock()
|
||||
mock_auth_service.validate_token_full.return_value = mock_auth_result
|
||||
|
||||
with patch("backend.api.dependencies.get_auth_service", return_value=mock_auth_service):
|
||||
result = await require_auth(
|
||||
request=request,
|
||||
auth_service=mock_auth_service,
|
||||
credentials=MagicMock(credentials="valid-token"),
|
||||
token=None,
|
||||
)
|
||||
|
||||
assert result.tenant_id is None
|
||||
assert request.state.tenant_id == "hostname-tenant"
|
||||
@@ -250,8 +250,28 @@ class TestVideoWorkerOrchestratorPackaging:
|
||||
"""Test packaging stage."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_no_lrc(self):
|
||||
"""Test packaging stage with no LRC file."""
|
||||
async def test_run_packaging_no_lrc_cdg_disabled(self):
|
||||
"""Test packaging stage with no LRC file and CDG disabled skips silently."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=False,
|
||||
lrc_file_path=None,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Should not raise, just skip
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_no_lrc_cdg_enabled_raises(self):
|
||||
"""Test packaging stage raises when CDG enabled but no LRC file."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
@@ -264,10 +284,8 @@ class TestVideoWorkerOrchestratorPackaging:
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Should not raise, just skip
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
with pytest.raises(RuntimeError, match="LRC file not available"):
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_cdg(self):
|
||||
@@ -310,6 +328,266 @@ class TestVideoWorkerOrchestratorPackaging:
|
||||
mock_service.create_cdg_package.assert_called_once()
|
||||
assert orchestrator.result.final_karaoke_cdg_zip == f"{temp_dir}/cdg.zip"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_packaging_cdg_with_countdown_padding(self):
|
||||
"""Test CDG packaging passes countdown params when LRC has countdown padding.
|
||||
|
||||
This test prevents regression of the CDG sync bug where:
|
||||
- Video rendering adds 3s countdown and shifts LRC timestamps by +3s
|
||||
- CDG generation was using shifted timestamps but instrumental audio without padding
|
||||
- Result: CDG lyrics appeared 3 seconds late
|
||||
|
||||
The fix: When lrc_has_countdown_padding=True, the packaging service must pass
|
||||
this flag to CDGGenerator so it can strip the countdown and shift timestamps back.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
lrc_file = os.path.join(temp_dir, "test.lrc")
|
||||
audio_file = os.path.join(temp_dir, "test.flac")
|
||||
|
||||
# Create LRC with countdown-shifted timestamps (as video rendering produces)
|
||||
with open(lrc_file, "w") as f:
|
||||
f.write("[00:00.10]1:/3... 2... 1...\n") # Countdown at 0.1s
|
||||
f.write("[00:03.60]1:/First\n") # First word at 3.6s (shifted from 0.6s)
|
||||
with open(audio_file, "w") as f:
|
||||
f.write("dummy audio")
|
||||
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path=audio_file,
|
||||
lrc_file_path=lrc_file,
|
||||
output_dir=temp_dir,
|
||||
enable_cdg=True,
|
||||
cdg_styles={"background_color": "black"},
|
||||
lrc_has_countdown_padding=True, # Critical: flag must be set
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with patch.object(orchestrator, "_get_packaging_service") as mock_get:
|
||||
mock_service = MagicMock()
|
||||
mock_service.create_cdg_package.return_value = (
|
||||
f"{temp_dir}/cdg.zip",
|
||||
f"{temp_dir}/test.mp3",
|
||||
f"{temp_dir}/test.cdg",
|
||||
)
|
||||
mock_get.return_value = mock_service
|
||||
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
# CRITICAL ASSERTION: countdown padding params must be passed
|
||||
mock_service.create_cdg_package.assert_called_once()
|
||||
call_kwargs = mock_service.create_cdg_package.call_args[1]
|
||||
assert call_kwargs.get("lrc_has_countdown_padding") is True, \
|
||||
"lrc_has_countdown_padding must be passed to packaging service for CDG sync fix"
|
||||
assert call_kwargs.get("countdown_padding_seconds") == 3.0, \
|
||||
"countdown_padding_seconds must be passed for CDG timestamp adjustment"
|
||||
|
||||
|
||||
class TestPackagingValidation:
|
||||
"""Test CDG/TXT packaging validation checks.
|
||||
|
||||
These tests verify that the orchestrator fails fast when CDG/TXT
|
||||
generation is enabled but fails, rather than silently proceeding
|
||||
to expensive encoding. This prevents jobs from completing without
|
||||
their requested CDG/TXT packages.
|
||||
|
||||
Added after jobs 5b6aba25 and 5161b069 completed with enable_cdg=True
|
||||
but no CDG ZIP was produced due to a FileNotFoundError being silently caught.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cdg_validation_fails_when_enabled_but_not_produced(self):
|
||||
"""Test that orchestrator raises when CDG enabled but not produced."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Mock _run_packaging to NOT set result.final_karaoke_cdg_zip (simulates failure)
|
||||
async def mock_packaging():
|
||||
pass # CDG generation "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is False
|
||||
assert "CDG generation was enabled but failed" in result.error_message
|
||||
mock_encoding.assert_not_called() # Should not reach encoding
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_txt_validation_fails_when_enabled_but_not_produced(self):
|
||||
"""Test that orchestrator raises when TXT enabled but not produced."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_txt=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging():
|
||||
pass # TXT generation "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is False
|
||||
assert "TXT generation was enabled but failed" in result.error_message
|
||||
mock_encoding.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pipeline_succeeds_when_cdg_disabled(self):
|
||||
"""Test that pipeline succeeds normally when CDG is not enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=False,
|
||||
enable_txt=False,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_pkg, \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is True
|
||||
mock_pkg.assert_not_called() # Packaging skipped entirely
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cdg_validation_passes_when_cdg_produced(self):
|
||||
"""Test that validation passes when CDG is successfully produced."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging_success():
|
||||
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_success), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
|
||||
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_both_cdg_and_txt_validation_fail_together(self):
|
||||
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
enable_txt=True,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
async def mock_packaging():
|
||||
pass # Both CDG and TXT "failed" silently
|
||||
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
|
||||
|
||||
result = await orchestrator.run()
|
||||
|
||||
assert result.success is False
|
||||
# CDG validation is checked first
|
||||
assert "CDG generation was enabled but failed" in result.error_message
|
||||
mock_encoding.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lrc_missing_raises_when_cdg_enabled(self):
|
||||
"""Test that missing LRC file raises when CDG is enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=True,
|
||||
lrc_file_path="/nonexistent/path.lrc",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with pytest.raises(RuntimeError, match="LRC file not available"):
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lrc_missing_raises_when_txt_enabled(self):
|
||||
"""Test that missing LRC file raises when TXT is enabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_txt=True,
|
||||
lrc_file_path=None,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with pytest.raises(RuntimeError, match="LRC file not available"):
|
||||
await orchestrator._run_packaging()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lrc_missing_skips_when_cdg_disabled(self):
|
||||
"""Test that missing LRC file just skips packaging when CDG/TXT disabled."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
enable_cdg=False,
|
||||
enable_txt=False,
|
||||
lrc_file_path=None,
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Should not raise, just skip
|
||||
await orchestrator._run_packaging()
|
||||
assert orchestrator.result.final_karaoke_cdg_zip is None
|
||||
|
||||
|
||||
class TestVideoWorkerOrchestratorEncoding:
|
||||
"""Test encoding stage."""
|
||||
@@ -554,7 +832,7 @@ class TestVideoWorkerOrchestratorOrganization:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_organization_generate_brand_code(self):
|
||||
"""Test brand code generation from Dropbox."""
|
||||
"""Test brand code generation via atomic BrandCodeService."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
@@ -567,15 +845,15 @@ class TestVideoWorkerOrchestratorOrganization:
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service") as mock_get:
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.get_next_brand_code.return_value = "TEST-0001"
|
||||
mock_get.return_value = mock_dropbox
|
||||
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_get:
|
||||
mock_service = MagicMock()
|
||||
mock_service.allocate_brand_code.return_value = "TEST-0001"
|
||||
mock_get.return_value = mock_service
|
||||
|
||||
await orchestrator._run_organization()
|
||||
|
||||
assert orchestrator.result.brand_code == "TEST-0001"
|
||||
mock_service.allocate_brand_code.assert_called_once_with("TEST", "/Karaoke/Tracks")
|
||||
|
||||
|
||||
class TestVideoWorkerOrchestratorDistribution:
|
||||
@@ -715,8 +993,12 @@ class TestVideoWorkerOrchestratorFullPipeline:
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
|
||||
# Mock packaging to set CDG result (validation requires it when enable_cdg=True)
|
||||
async def mock_packaging_with_result():
|
||||
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
|
||||
|
||||
# Mock all stages
|
||||
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_packaging, \
|
||||
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_with_result) as mock_packaging, \
|
||||
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding, \
|
||||
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock) as mock_org, \
|
||||
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock) as mock_dist, \
|
||||
@@ -798,6 +1080,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
job.enable_cdg = True
|
||||
job.enable_txt = False
|
||||
job.enable_youtube_upload = True
|
||||
job.is_private = False
|
||||
job.brand_prefix = "NOMAD"
|
||||
job.discord_webhook_url = "https://discord.com/api/webhooks/123/abc"
|
||||
job.youtube_description_template = "Test description"
|
||||
@@ -831,6 +1114,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
job.enable_cdg = False
|
||||
job.enable_txt = False
|
||||
job.enable_youtube_upload = False
|
||||
job.is_private = False
|
||||
job.brand_prefix = None
|
||||
job.discord_webhook_url = None
|
||||
job.youtube_description_template = None
|
||||
@@ -869,6 +1153,7 @@ class TestCreateOrchestratorConfigFromJob:
|
||||
job.enable_cdg = False
|
||||
job.enable_txt = False
|
||||
job.enable_youtube_upload = False
|
||||
job.is_private = False
|
||||
job.brand_prefix = None
|
||||
job.discord_webhook_url = None
|
||||
job.youtube_description_template = None
|
||||
@@ -1227,3 +1512,64 @@ class TestOrchestratorCountdownPadding:
|
||||
assert captured_input is not None, "encode() should have been called"
|
||||
assert captured_input.options.get("countdown_padding_seconds") == 3.0, \
|
||||
"Orchestrator must pass countdown_padding_seconds in EncodingInput.options"
|
||||
|
||||
|
||||
class TestDistributionWarnings:
|
||||
"""Test distribution_warnings tracking in OrchestratorResult."""
|
||||
|
||||
def test_result_has_distribution_warnings_field(self):
|
||||
"""Test that OrchestratorResult has distribution_warnings as empty list by default."""
|
||||
result = OrchestratorResult(success=True)
|
||||
assert result.distribution_warnings == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gdrive_failure_populates_warnings(self):
|
||||
"""Test that Google Drive upload failure populates distribution_warnings."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
gdrive_folder_id="folder-123",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
orchestrator.result.brand_code = "NOMAD-0001"
|
||||
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_get:
|
||||
mock_gdrive = MagicMock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.upload_to_public_share.side_effect = Exception("Connection refused")
|
||||
mock_get.return_value = mock_gdrive
|
||||
|
||||
await orchestrator._upload_to_gdrive()
|
||||
|
||||
assert len(orchestrator.result.distribution_warnings) == 1
|
||||
assert "Google Drive upload failed" in orchestrator.result.distribution_warnings[0]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dropbox_failure_populates_warnings(self):
|
||||
"""Test that Dropbox upload failure populates distribution_warnings."""
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
title_video_path="/path/title.mov",
|
||||
karaoke_video_path="/path/karaoke.mov",
|
||||
instrumental_audio_path="/path/audio.flac",
|
||||
dropbox_path="/Public Share",
|
||||
)
|
||||
orchestrator = VideoWorkerOrchestrator(config)
|
||||
orchestrator.result.brand_code = "NOMAD-0001"
|
||||
|
||||
with patch("backend.services.dropbox_service.get_dropbox_service") as mock_get:
|
||||
mock_dropbox = MagicMock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.upload_folder.side_effect = Exception("Auth expired")
|
||||
mock_get.return_value = mock_dropbox
|
||||
|
||||
await orchestrator._upload_to_dropbox()
|
||||
|
||||
assert len(orchestrator.result.distribution_warnings) == 1
|
||||
assert "Dropbox upload failed" in orchestrator.result.distribution_warnings[0]
|
||||
@@ -0,0 +1,278 @@
|
||||
"""
|
||||
Unit tests for YouTube queue processor.
|
||||
|
||||
Tests the deferred upload processing logic including quota checks,
|
||||
queue claiming, video downloading, and error handling.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, AsyncMock, patch
|
||||
|
||||
# Mock Google Cloud before imports
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.storage', MagicMock())
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestProcessYouTubeUploadQueue:
|
||||
"""Test the main queue processing function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_quota_service(self):
|
||||
service = Mock()
|
||||
service.check_quota_available.return_value = (True, 9000, "9000 units remaining")
|
||||
service.record_operation = Mock()
|
||||
return service
|
||||
|
||||
@pytest.fixture
|
||||
def mock_queue_service(self):
|
||||
service = Mock()
|
||||
service.get_queued_uploads.return_value = []
|
||||
service.mark_processing.return_value = True
|
||||
service.mark_completed = Mock()
|
||||
service.mark_failed = Mock()
|
||||
return service
|
||||
|
||||
async def test_skips_when_no_quota(self, mock_quota_service, mock_queue_service):
|
||||
"""Should skip processing when no quota available."""
|
||||
mock_quota_service.check_quota_available.return_value = (False, 0, "Quota exhausted")
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.get_youtube_quota_service', return_value=mock_quota_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_youtube_upload_queue_service', return_value=mock_queue_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_settings'):
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue
|
||||
result = await process_youtube_upload_queue()
|
||||
|
||||
assert result["status"] == "skipped"
|
||||
assert result["reason"] == "no_quota"
|
||||
assert result["processed"] == 0
|
||||
|
||||
async def test_returns_empty_when_no_queued(self, mock_quota_service, mock_queue_service):
|
||||
"""Should return empty status when no uploads queued."""
|
||||
mock_queue_service.get_queued_uploads.return_value = []
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.get_youtube_quota_service', return_value=mock_quota_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_youtube_upload_queue_service', return_value=mock_queue_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_settings'):
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue
|
||||
result = await process_youtube_upload_queue()
|
||||
|
||||
assert result["status"] == "empty"
|
||||
assert result["processed"] == 0
|
||||
assert result["remaining"] == 0
|
||||
|
||||
async def test_processes_queued_upload(self, mock_quota_service, mock_queue_service):
|
||||
"""Should process a single queued upload successfully."""
|
||||
mock_queue_service.get_queued_uploads.side_effect = [
|
||||
[{"job_id": "job-123", "user_email": "user@test.com", "artist": "Artist", "title": "Title", "brand_code": "NOMAD-100"}],
|
||||
[], # After processing, no more queued
|
||||
]
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.get_youtube_quota_service', return_value=mock_quota_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_youtube_upload_queue_service', return_value=mock_queue_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_settings'), \
|
||||
patch('backend.workers.youtube_queue_processor._process_single_upload', new_callable=AsyncMock, return_value="https://youtube.com/watch?v=abc") as mock_upload, \
|
||||
patch('backend.workers.youtube_queue_processor._update_job_youtube_url'), \
|
||||
patch('backend.workers.youtube_queue_processor._send_youtube_upload_notification', new_callable=AsyncMock):
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue
|
||||
result = await process_youtube_upload_queue()
|
||||
|
||||
assert result["status"] == "processed"
|
||||
assert result["processed"] == 1
|
||||
assert result["failed"] == 0
|
||||
mock_queue_service.mark_completed.assert_called_once_with("job-123", "https://youtube.com/watch?v=abc")
|
||||
|
||||
async def test_handles_upload_failure(self, mock_quota_service, mock_queue_service):
|
||||
"""Should handle upload failure and mark as failed."""
|
||||
mock_queue_service.get_queued_uploads.side_effect = [
|
||||
[{"job_id": "job-fail", "user_email": "u@t.com", "artist": "A", "title": "T", "brand_code": None}],
|
||||
[],
|
||||
]
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.get_youtube_quota_service', return_value=mock_quota_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_youtube_upload_queue_service', return_value=mock_queue_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_settings'), \
|
||||
patch('backend.workers.youtube_queue_processor._process_single_upload', new_callable=AsyncMock, side_effect=Exception("Upload failed")):
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue
|
||||
result = await process_youtube_upload_queue()
|
||||
|
||||
assert result["failed"] == 1
|
||||
assert result["processed"] == 0
|
||||
mock_queue_service.mark_failed.assert_called_once()
|
||||
|
||||
async def test_stops_on_quota_exceeded(self, mock_quota_service, mock_queue_service):
|
||||
"""Should stop processing when quota exceeded error occurs."""
|
||||
mock_queue_service.get_queued_uploads.side_effect = [
|
||||
[
|
||||
{"job_id": "job-1", "user_email": "u@t.com", "artist": "A", "title": "T", "brand_code": None},
|
||||
{"job_id": "job-2", "user_email": "u@t.com", "artist": "A", "title": "T", "brand_code": None},
|
||||
],
|
||||
[],
|
||||
]
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.get_youtube_quota_service', return_value=mock_quota_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_youtube_upload_queue_service', return_value=mock_queue_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_settings'), \
|
||||
patch('backend.workers.youtube_queue_processor._process_single_upload', new_callable=AsyncMock, side_effect=Exception("quotaExceeded: daily limit reached")):
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue
|
||||
result = await process_youtube_upload_queue()
|
||||
|
||||
# Should stop after first quota exceeded error, not process job-2
|
||||
assert result["failed"] == 1
|
||||
assert mock_queue_service.mark_failed.call_count == 1
|
||||
|
||||
async def test_skips_unclaimed_entry(self, mock_quota_service, mock_queue_service):
|
||||
"""Should skip entries that can't be claimed (already processing)."""
|
||||
mock_queue_service.get_queued_uploads.side_effect = [
|
||||
[{"job_id": "job-claimed", "user_email": "u@t.com", "artist": "A", "title": "T", "brand_code": None}],
|
||||
[],
|
||||
]
|
||||
mock_queue_service.mark_processing.return_value = False
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.get_youtube_quota_service', return_value=mock_quota_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_youtube_upload_queue_service', return_value=mock_queue_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_settings'):
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue
|
||||
result = await process_youtube_upload_queue()
|
||||
|
||||
assert result["processed"] == 0
|
||||
assert result["failed"] == 0
|
||||
|
||||
async def test_rechecks_quota_before_each_upload(self, mock_quota_service, mock_queue_service):
|
||||
"""Should re-check quota before each upload, not just at the start."""
|
||||
mock_queue_service.get_queued_uploads.side_effect = [
|
||||
[
|
||||
{"job_id": "job-1", "user_email": "u@t.com", "artist": "A", "title": "T", "brand_code": None},
|
||||
{"job_id": "job-2", "user_email": "u@t.com", "artist": "A", "title": "T", "brand_code": None},
|
||||
],
|
||||
[],
|
||||
]
|
||||
|
||||
# Allow first check, deny second
|
||||
mock_quota_service.check_quota_available.side_effect = [
|
||||
(True, 9000, "ok"), # Initial check
|
||||
(True, 500, "ok"), # Before job-1
|
||||
(False, 0, "exhausted"), # Before job-2
|
||||
]
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.get_youtube_quota_service', return_value=mock_quota_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_youtube_upload_queue_service', return_value=mock_queue_service), \
|
||||
patch('backend.workers.youtube_queue_processor.get_settings'), \
|
||||
patch('backend.workers.youtube_queue_processor._process_single_upload', new_callable=AsyncMock, return_value="https://youtube.com/watch?v=x"), \
|
||||
patch('backend.workers.youtube_queue_processor._update_job_youtube_url'), \
|
||||
patch('backend.workers.youtube_queue_processor._send_youtube_upload_notification', new_callable=AsyncMock):
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue
|
||||
result = await process_youtube_upload_queue()
|
||||
|
||||
# Only job-1 should have been processed
|
||||
assert result["processed"] == 1
|
||||
|
||||
|
||||
class TestDownloadVideoFromGCS:
|
||||
"""Test video file download logic."""
|
||||
|
||||
def test_prioritizes_mkv(self):
|
||||
"""Should prefer MKV over MP4."""
|
||||
from backend.workers.youtube_queue_processor import _download_video_from_gcs
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.file_urls = {
|
||||
"finals": {
|
||||
"lossless_4k_mkv": "jobs/job-123/finals/lossless_4k_mkv.mkv",
|
||||
"lossless_4k_mp4": "jobs/job-123/finals/lossless_4k_mp4.mp4",
|
||||
}
|
||||
}
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.download_file = Mock()
|
||||
|
||||
with patch('os.path.isfile', return_value=True), \
|
||||
patch('os.path.getsize', return_value=1024):
|
||||
result = _download_video_from_gcs("job-123", mock_job, mock_storage, "/tmp/test")
|
||||
|
||||
assert result is not None
|
||||
assert result.endswith(".mkv")
|
||||
mock_storage.download_file.assert_called_once_with("jobs/job-123/finals/lossless_4k_mkv.mkv", "/tmp/test/video.mkv")
|
||||
|
||||
def test_falls_back_to_mp4(self):
|
||||
"""Should fall back to MP4 when MKV not available."""
|
||||
from backend.workers.youtube_queue_processor import _download_video_from_gcs
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.file_urls = {
|
||||
"finals": {
|
||||
"lossless_4k_mp4": "jobs/job-123/finals/lossless_4k_mp4.mp4",
|
||||
}
|
||||
}
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.download_file = Mock()
|
||||
|
||||
with patch('os.path.isfile', return_value=True), \
|
||||
patch('os.path.getsize', return_value=1024):
|
||||
result = _download_video_from_gcs("job-123", mock_job, mock_storage, "/tmp/test")
|
||||
|
||||
assert result is not None
|
||||
assert result.endswith(".mp4")
|
||||
|
||||
def test_returns_none_when_no_files(self):
|
||||
"""Should return None when no video files available."""
|
||||
from backend.workers.youtube_queue_processor import _download_video_from_gcs
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.file_urls = {}
|
||||
|
||||
mock_storage = Mock()
|
||||
result = _download_video_from_gcs("job-123", mock_job, mock_storage, "/tmp/test")
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_returns_none_on_download_failure(self):
|
||||
"""Should return None when download fails."""
|
||||
from backend.workers.youtube_queue_processor import _download_video_from_gcs
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.file_urls = {"finals": {"lossless_4k_mkv": "jobs/job-123/finals/lossless_4k_mkv.mkv"}}
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.download_file.side_effect = Exception("Download failed")
|
||||
|
||||
result = _download_video_from_gcs("job-123", mock_job, mock_storage, "/tmp/test")
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestUpdateJobYouTubeUrl:
|
||||
"""Test updating job state_data with YouTube URL."""
|
||||
|
||||
def test_updates_state_data(self):
|
||||
"""Should set youtube_url and clear queued flag."""
|
||||
from backend.workers.youtube_queue_processor import _update_job_youtube_url
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {"brand_code": "NOMAD-100"}
|
||||
mock_job_manager = Mock()
|
||||
mock_job_manager.get_job.return_value = mock_job
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.JobManager', return_value=mock_job_manager):
|
||||
_update_job_youtube_url("job-123", "https://youtube.com/watch?v=abc")
|
||||
|
||||
update_call = mock_job_manager.update_job.call_args[0]
|
||||
assert update_call[0] == "job-123"
|
||||
state_data = update_call[1]["state_data"]
|
||||
assert state_data["youtube_url"] == "https://youtube.com/watch?v=abc"
|
||||
assert state_data["youtube_upload_queued"] is False
|
||||
|
||||
def test_handles_missing_job(self):
|
||||
"""Should not raise when job not found."""
|
||||
from backend.workers.youtube_queue_processor import _update_job_youtube_url
|
||||
|
||||
mock_job_manager = Mock()
|
||||
mock_job_manager.get_job.return_value = None
|
||||
|
||||
with patch('backend.workers.youtube_queue_processor.JobManager', return_value=mock_job_manager):
|
||||
# Should not raise
|
||||
_update_job_youtube_url("nonexistent", "https://youtube.com/watch?v=abc")
|
||||
|
||||
mock_job_manager.update_job.assert_not_called()
|
||||
@@ -0,0 +1,278 @@
|
||||
"""
|
||||
Unit tests for YouTubeQuotaService.
|
||||
|
||||
Tests quota tracking, availability checks, and operation recording
|
||||
against the YouTube Data API v3's 10,000 units/day quota.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
from datetime import datetime
|
||||
|
||||
# Mock Google Cloud before imports
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.storage', MagicMock())
|
||||
|
||||
|
||||
class TestYouTubeQuotaService:
|
||||
"""Test YouTubeQuotaService functionality."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
return mock
|
||||
|
||||
@pytest.fixture
|
||||
def mock_settings(self):
|
||||
settings = Mock()
|
||||
settings.google_cloud_project = "test-project"
|
||||
settings.youtube_quota_daily_limit = 10000
|
||||
settings.youtube_quota_upload_cost = 300
|
||||
settings.youtube_quota_safety_margin = 500
|
||||
return settings
|
||||
|
||||
@pytest.fixture
|
||||
def quota_service(self, mock_db, mock_settings):
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
from backend.services.youtube_quota_service import YouTubeQuotaService
|
||||
service = YouTubeQuotaService(db=mock_db)
|
||||
return service
|
||||
|
||||
# =========================================================================
|
||||
# check_quota_available Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_quota_available_when_no_usage(self, quota_service, mock_db, mock_settings):
|
||||
"""Quota should be available when nothing consumed today."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
allowed, remaining, message = quota_service.check_quota_available()
|
||||
|
||||
assert allowed is True
|
||||
assert remaining == 9500 # 10000 - 500 safety margin
|
||||
assert "remaining" in message.lower()
|
||||
|
||||
def test_quota_available_with_partial_usage(self, quota_service, mock_db, mock_settings):
|
||||
"""Quota should be available when partial usage (under effective limit)."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"units_consumed": 3000}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
allowed, remaining, message = quota_service.check_quota_available()
|
||||
|
||||
assert allowed is True
|
||||
assert remaining == 6500 # 9500 - 3000
|
||||
|
||||
def test_quota_denied_when_insufficient(self, quota_service, mock_db, mock_settings):
|
||||
"""Quota should be denied when remaining units less than estimated cost."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"units_consumed": 9300}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
allowed, remaining, message = quota_service.check_quota_available()
|
||||
|
||||
assert allowed is False
|
||||
assert remaining == 200 # 9500 - 9300
|
||||
assert "insufficient" in message.lower()
|
||||
|
||||
def test_quota_denied_at_effective_limit(self, quota_service, mock_db, mock_settings):
|
||||
"""Quota should be denied when exactly at effective limit."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"units_consumed": 9500}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
allowed, remaining, message = quota_service.check_quota_available()
|
||||
|
||||
assert allowed is False
|
||||
assert remaining == 0
|
||||
|
||||
def test_quota_unlimited_when_limit_zero(self, quota_service, mock_db, mock_settings):
|
||||
"""Quota should be unlimited when daily limit is 0."""
|
||||
mock_settings.youtube_quota_daily_limit = 0
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
allowed, remaining, message = quota_service.check_quota_available()
|
||||
|
||||
assert allowed is True
|
||||
assert remaining == -1
|
||||
assert "no youtube quota limit" in message.lower()
|
||||
|
||||
def test_quota_check_with_custom_estimated_units(self, quota_service, mock_db, mock_settings):
|
||||
"""Check quota with a custom estimated_units value."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"units_consumed": 9400}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
# 50 units should fit (9400 + 50 = 9450 < 9500)
|
||||
allowed, remaining, _ = quota_service.check_quota_available(estimated_units=50)
|
||||
assert allowed is True
|
||||
|
||||
# 200 units should not fit (9400 + 200 = 9600 > 9500)
|
||||
allowed, remaining, _ = quota_service.check_quota_available(estimated_units=200)
|
||||
assert allowed is False
|
||||
|
||||
# =========================================================================
|
||||
# record_operation Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_record_operation_new_document(self, quota_service, mock_db, mock_settings):
|
||||
"""Recording an operation should create document if none exists."""
|
||||
import google.cloud.firestore as firestore_module
|
||||
firestore_module.transactional = lambda f: f
|
||||
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.transaction.return_value = Mock()
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
quota_service.record_operation(
|
||||
job_id="test-job-123",
|
||||
user_email="user@example.com",
|
||||
operation="videos.insert",
|
||||
units=100,
|
||||
)
|
||||
|
||||
# Verify transaction was used
|
||||
mock_db.transaction.assert_called_once()
|
||||
|
||||
def test_record_operation_uses_known_costs(self, quota_service, mock_db, mock_settings):
|
||||
"""When units not specified, should look up from QUOTA_COSTS."""
|
||||
import google.cloud.firestore as firestore_module
|
||||
firestore_module.transactional = lambda f: f
|
||||
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
quota_service.record_operation(
|
||||
job_id="test-job-123",
|
||||
user_email="user@example.com",
|
||||
operation="thumbnails.set",
|
||||
# units not specified - should use QUOTA_COSTS["thumbnails.set"] = 50
|
||||
)
|
||||
|
||||
mock_db.transaction.assert_called_once()
|
||||
|
||||
# =========================================================================
|
||||
# get_quota_stats Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_get_quota_stats_no_usage(self, quota_service, mock_db, mock_settings):
|
||||
"""Stats should show zero usage when no document exists."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
stats = quota_service.get_quota_stats()
|
||||
|
||||
assert stats["units_consumed"] == 0
|
||||
assert stats["units_limit"] == 10000
|
||||
assert stats["effective_limit"] == 9500
|
||||
assert stats["units_remaining"] == 9500
|
||||
assert stats["upload_cost"] == 300
|
||||
assert stats["estimated_uploads_remaining"] == 31 # 9500 // 300
|
||||
assert stats["operations_count"] == 0
|
||||
assert "seconds_until_reset" in stats
|
||||
|
||||
def test_get_quota_stats_with_usage(self, quota_service, mock_db, mock_settings):
|
||||
"""Stats should reflect current usage."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {
|
||||
"units_consumed": 2700,
|
||||
"operations": [
|
||||
{"operation": "videos.insert", "units": 100},
|
||||
{"operation": "search.list", "units": 100},
|
||||
{"operation": "thumbnails.set", "units": 50},
|
||||
] * 3 + [
|
||||
{"operation": "search.list", "units": 100},
|
||||
{"operation": "videos.insert", "units": 100},
|
||||
{"operation": "thumbnails.set", "units": 50},
|
||||
] * 3 + [
|
||||
{"operation": "search.list", "units": 100},
|
||||
{"operation": "videos.insert", "units": 100},
|
||||
{"operation": "thumbnails.set", "units": 50},
|
||||
] * 3,
|
||||
}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
stats = quota_service.get_quota_stats()
|
||||
|
||||
assert stats["units_consumed"] == 2700
|
||||
assert stats["units_remaining"] == 6800 # 9500 - 2700
|
||||
assert stats["estimated_uploads_remaining"] == 22 # 6800 // 300
|
||||
|
||||
# =========================================================================
|
||||
# _get_units_consumed_today Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_get_units_consumed_no_document(self, quota_service, mock_db, mock_settings):
|
||||
"""Should return 0 when no tracking document exists."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
consumed = quota_service._get_units_consumed_today()
|
||||
|
||||
assert consumed == 0
|
||||
|
||||
def test_get_units_consumed_with_document(self, quota_service, mock_db, mock_settings):
|
||||
"""Should return units_consumed from document."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"units_consumed": 4500}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
with patch('backend.services.youtube_quota_service.settings', mock_settings):
|
||||
consumed = quota_service._get_units_consumed_today()
|
||||
|
||||
assert consumed == 4500
|
||||
|
||||
|
||||
class TestQuotaCosts:
|
||||
"""Test that known API operation costs are correctly defined."""
|
||||
|
||||
def test_known_costs(self):
|
||||
from backend.services.youtube_quota_service import QUOTA_COSTS
|
||||
|
||||
assert QUOTA_COSTS["videos.insert"] == 100
|
||||
assert QUOTA_COSTS["search.list"] == 100
|
||||
assert QUOTA_COSTS["thumbnails.set"] == 50
|
||||
assert QUOTA_COSTS["videos.delete"] == 50
|
||||
assert QUOTA_COSTS["channels.list"] == 1
|
||||
|
||||
|
||||
class TestHelperFunctions:
|
||||
"""Test module-level helper functions."""
|
||||
|
||||
def test_get_today_date_pt_format(self):
|
||||
from backend.services.youtube_quota_service import _get_today_date_pt
|
||||
date_str = _get_today_date_pt()
|
||||
# Should be YYYY-MM-DD format
|
||||
assert len(date_str) == 10
|
||||
assert date_str[4] == "-"
|
||||
assert date_str[7] == "-"
|
||||
|
||||
def test_seconds_until_midnight_pt_positive(self):
|
||||
from backend.services.youtube_quota_service import _seconds_until_midnight_pt
|
||||
seconds = _seconds_until_midnight_pt()
|
||||
assert 0 < seconds <= 86400 # Between 0 and 24 hours
|
||||
@@ -0,0 +1,306 @@
|
||||
"""
|
||||
Unit tests for YouTubeUploadQueueService.
|
||||
|
||||
Tests queue management for deferred YouTube uploads including
|
||||
queuing, claiming, completion, failure handling, and retries.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
|
||||
# Mock Google Cloud before imports
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.storage', MagicMock())
|
||||
|
||||
|
||||
class TestYouTubeUploadQueueService:
|
||||
"""Test YouTubeUploadQueueService functionality."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
mock = MagicMock()
|
||||
return mock
|
||||
|
||||
@pytest.fixture
|
||||
def mock_settings(self):
|
||||
settings = Mock()
|
||||
settings.google_cloud_project = "test-project"
|
||||
return settings
|
||||
|
||||
@pytest.fixture
|
||||
def queue_service(self, mock_db, mock_settings):
|
||||
with patch('backend.services.youtube_upload_queue_service.settings', mock_settings):
|
||||
from backend.services.youtube_upload_queue_service import YouTubeUploadQueueService
|
||||
service = YouTubeUploadQueueService(db=mock_db)
|
||||
return service
|
||||
|
||||
# =========================================================================
|
||||
# queue_upload Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_queue_upload_creates_document(self, queue_service, mock_db):
|
||||
"""Queuing an upload should create a Firestore document."""
|
||||
queue_service.queue_upload(
|
||||
job_id="job-123",
|
||||
user_email="user@example.com",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
brand_code="NOMAD-1234",
|
||||
reason="quota_exceeded",
|
||||
)
|
||||
|
||||
mock_db.collection.return_value.document.assert_called_with("job-123")
|
||||
call_args = mock_db.collection.return_value.document.return_value.set.call_args[0][0]
|
||||
assert call_args["job_id"] == "job-123"
|
||||
assert call_args["status"] == "queued"
|
||||
assert call_args["user_email"] == "user@example.com"
|
||||
assert call_args["artist"] == "Test Artist"
|
||||
assert call_args["title"] == "Test Song"
|
||||
assert call_args["brand_code"] == "NOMAD-1234"
|
||||
assert call_args["reason"] == "quota_exceeded"
|
||||
assert call_args["attempts"] == 0
|
||||
assert call_args["max_attempts"] == 5
|
||||
assert call_args["youtube_url"] is None
|
||||
|
||||
def test_queue_upload_default_reason(self, queue_service, mock_db):
|
||||
"""Default reason should be quota_exceeded."""
|
||||
queue_service.queue_upload(
|
||||
job_id="job-456",
|
||||
user_email="user@example.com",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
brand_code=None,
|
||||
)
|
||||
|
||||
call_args = mock_db.collection.return_value.document.return_value.set.call_args[0][0]
|
||||
assert call_args["reason"] == "quota_exceeded"
|
||||
assert call_args["brand_code"] is None
|
||||
|
||||
# =========================================================================
|
||||
# get_queued_uploads Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_get_queued_uploads_returns_dicts(self, queue_service, mock_db):
|
||||
"""Should return list of dicts for queued entries."""
|
||||
mock_doc1 = Mock()
|
||||
mock_doc1.to_dict.return_value = {"job_id": "job-1", "status": "queued"}
|
||||
mock_doc2 = Mock()
|
||||
mock_doc2.to_dict.return_value = {"job_id": "job-2", "status": "queued"}
|
||||
|
||||
mock_query = mock_db.collection.return_value
|
||||
mock_query.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [
|
||||
mock_doc1, mock_doc2
|
||||
]
|
||||
|
||||
results = queue_service.get_queued_uploads(limit=10)
|
||||
|
||||
assert len(results) == 2
|
||||
assert results[0]["job_id"] == "job-1"
|
||||
assert results[1]["job_id"] == "job-2"
|
||||
|
||||
def test_get_queued_uploads_empty(self, queue_service, mock_db):
|
||||
"""Should return empty list when no queued uploads."""
|
||||
mock_query = mock_db.collection.return_value
|
||||
mock_query.where.return_value.order_by.return_value.limit.return_value.stream.return_value = []
|
||||
|
||||
results = queue_service.get_queued_uploads()
|
||||
assert results == []
|
||||
|
||||
# =========================================================================
|
||||
# mark_processing Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_mark_processing_success(self, queue_service, mock_db):
|
||||
"""Should claim a queued entry for processing."""
|
||||
import google.cloud.firestore as firestore_module
|
||||
firestore_module.transactional = lambda f: f
|
||||
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"status": "queued", "attempts": 0, "max_attempts": 5}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.transaction.return_value = Mock()
|
||||
|
||||
result = queue_service.mark_processing("job-123")
|
||||
|
||||
assert result is True
|
||||
|
||||
def test_mark_processing_not_queued(self, queue_service, mock_db):
|
||||
"""Should not claim an entry that's already processing."""
|
||||
import google.cloud.firestore as firestore_module
|
||||
firestore_module.transactional = lambda f: f
|
||||
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"status": "processing", "attempts": 1, "max_attempts": 5}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.transaction.return_value = Mock()
|
||||
|
||||
result = queue_service.mark_processing("job-123")
|
||||
|
||||
assert result is False
|
||||
|
||||
def test_mark_processing_not_found(self, queue_service, mock_db):
|
||||
"""Should return False for non-existent entry."""
|
||||
import google.cloud.firestore as firestore_module
|
||||
firestore_module.transactional = lambda f: f
|
||||
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.transaction.return_value = Mock()
|
||||
|
||||
result = queue_service.mark_processing("nonexistent")
|
||||
|
||||
assert result is False
|
||||
|
||||
def test_mark_processing_max_attempts_exceeded(self, queue_service, mock_db):
|
||||
"""Should mark as failed when max attempts exceeded."""
|
||||
import google.cloud.firestore as firestore_module
|
||||
firestore_module.transactional = lambda f: f
|
||||
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"status": "queued", "attempts": 5, "max_attempts": 5}
|
||||
mock_doc_ref = mock_db.collection.return_value.document.return_value
|
||||
mock_doc_ref.get.return_value = mock_doc
|
||||
mock_db.transaction.return_value = Mock()
|
||||
|
||||
result = queue_service.mark_processing("job-123")
|
||||
|
||||
assert result is False
|
||||
|
||||
# =========================================================================
|
||||
# mark_completed Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_mark_completed(self, queue_service, mock_db):
|
||||
"""Should update status and set youtube_url."""
|
||||
queue_service.mark_completed("job-123", "https://youtube.com/watch?v=abc123")
|
||||
|
||||
mock_db.collection.return_value.document.assert_called_with("job-123")
|
||||
update_data = mock_db.collection.return_value.document.return_value.update.call_args[0][0]
|
||||
assert update_data["status"] == "completed"
|
||||
assert update_data["youtube_url"] == "https://youtube.com/watch?v=abc123"
|
||||
assert "completed_at" in update_data
|
||||
|
||||
# =========================================================================
|
||||
# mark_failed Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_mark_failed_resets_to_queued_under_max_attempts(self, queue_service, mock_db):
|
||||
"""Should reset to queued if under max attempts."""
|
||||
import google.cloud.firestore as firestore_module
|
||||
firestore_module.transactional = lambda f: f
|
||||
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"attempts": 2, "max_attempts": 5}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.transaction.return_value = Mock()
|
||||
|
||||
queue_service.mark_failed("job-123", "Connection timeout")
|
||||
|
||||
mock_db.transaction.assert_called_once()
|
||||
|
||||
def test_mark_failed_permanent_at_max_attempts(self, queue_service, mock_db):
|
||||
"""Should mark permanently failed at max attempts."""
|
||||
import google.cloud.firestore as firestore_module
|
||||
firestore_module.transactional = lambda f: f
|
||||
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"attempts": 5, "max_attempts": 5}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.transaction.return_value = Mock()
|
||||
|
||||
queue_service.mark_failed("job-123", "Quota exceeded")
|
||||
|
||||
mock_db.transaction.assert_called_once()
|
||||
|
||||
def test_mark_failed_nonexistent_entry(self, queue_service, mock_db):
|
||||
"""Should silently return for non-existent entry."""
|
||||
import google.cloud.firestore as firestore_module
|
||||
firestore_module.transactional = lambda f: f
|
||||
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
mock_db.transaction.return_value = Mock()
|
||||
|
||||
# Should not raise
|
||||
queue_service.mark_failed("nonexistent", "Some error")
|
||||
|
||||
# =========================================================================
|
||||
# retry_upload Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_retry_upload_from_failed(self, queue_service, mock_db):
|
||||
"""Should reset a failed entry to queued."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"status": "failed", "attempts": 5}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
result = queue_service.retry_upload("job-123")
|
||||
|
||||
assert result is True
|
||||
update_data = mock_db.collection.return_value.document.return_value.update.call_args[0][0]
|
||||
assert update_data["status"] == "queued"
|
||||
assert update_data["attempts"] == 0
|
||||
assert update_data["last_error"] is None
|
||||
|
||||
def test_retry_upload_not_found(self, queue_service, mock_db):
|
||||
"""Should return False for non-existent entry."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = False
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
result = queue_service.retry_upload("nonexistent")
|
||||
assert result is False
|
||||
|
||||
def test_retry_upload_completed_not_retryable(self, queue_service, mock_db):
|
||||
"""Should return False for completed entries (not retryable)."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"status": "completed"}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
result = queue_service.retry_upload("job-123")
|
||||
assert result is False
|
||||
|
||||
def test_retry_upload_processing_not_retryable(self, queue_service, mock_db):
|
||||
"""Should return False for entries currently processing."""
|
||||
mock_doc = Mock()
|
||||
mock_doc.exists = True
|
||||
mock_doc.to_dict.return_value = {"status": "processing"}
|
||||
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
|
||||
|
||||
result = queue_service.retry_upload("job-123")
|
||||
assert result is False
|
||||
|
||||
# =========================================================================
|
||||
# get_queue_stats Tests
|
||||
# =========================================================================
|
||||
|
||||
def test_get_queue_stats(self, queue_service, mock_db):
|
||||
"""Should return aggregate counts by status."""
|
||||
def mock_stream_for_status(status):
|
||||
counts = {"queued": 3, "processing": 1, "failed": 2, "completed": 10}
|
||||
return [Mock() for _ in range(counts.get(status, 0))]
|
||||
|
||||
def mock_where(field, op, value):
|
||||
result = Mock()
|
||||
result.select.return_value.stream.return_value = mock_stream_for_status(value)
|
||||
return result
|
||||
|
||||
mock_db.collection.return_value.where = mock_where
|
||||
|
||||
stats = queue_service.get_queue_stats()
|
||||
|
||||
assert stats["queued"] == 3
|
||||
assert stats["processing"] == 1
|
||||
assert stats["failed"] == 2
|
||||
assert stats["completed"] == 10
|
||||
assert stats["total"] == 16
|
||||
@@ -485,6 +485,19 @@ async def download_audio(
|
||||
local_path = os.path.join(temp_dir, safe_filename)
|
||||
storage.download_file(job.input_media_gcs_path, local_path)
|
||||
logger.info(f"Job {job_id}: Downloaded uploaded file to {local_path}")
|
||||
|
||||
# Persist uploaded audio to jobs/ prefix (uploads/ has 7-day lifecycle)
|
||||
if job.input_media_gcs_path.startswith("uploads/"):
|
||||
try:
|
||||
persistent_path = f"jobs/{job_id}/input/{safe_filename}"
|
||||
storage.upload_file(local_path, persistent_path)
|
||||
jm = job_manager_instance or JobManager()
|
||||
jm.update_job(job_id, {'input_media_gcs_path': persistent_path})
|
||||
jm.update_file_url(job_id, 'input', 'audio', persistent_path)
|
||||
logger.info(f"Job {job_id}: Persisted upload to {persistent_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: Failed to persist upload to jobs/ prefix: {e}")
|
||||
|
||||
return local_path
|
||||
|
||||
# Case 2: URL download (from file_urls if already downloaded, or from job.url)
|
||||
|
||||
@@ -184,6 +184,12 @@ async def generate_screens(job_id: str) -> bool:
|
||||
job_log.info("Analyzing backing vocals for instrumental selection...")
|
||||
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
|
||||
|
||||
# Transcode review audio to OGG Opus for fast browser playback
|
||||
# This runs BEFORE review so all files are cached when the user opens the UI
|
||||
with job_span("transcode-review-audio", job_id):
|
||||
job_log.info("Transcoding review audio to OGG Opus...")
|
||||
await _transcode_review_audio(job_id, job_manager, job_log)
|
||||
|
||||
# Transition to AWAITING_REVIEW (combined lyrics + instrumental review)
|
||||
# Human must review lyrics AND select instrumental before video can be rendered
|
||||
logger.info(f"[job:{job_id}] Screens generated, awaiting combined review")
|
||||
@@ -615,6 +621,37 @@ async def _analyze_backing_vocals(
|
||||
})
|
||||
|
||||
|
||||
async def _transcode_review_audio(
|
||||
job_id: str,
|
||||
job_manager: JobManager,
|
||||
job_log: logging.Logger,
|
||||
) -> None:
|
||||
"""
|
||||
Transcode all review audio files to OGG Opus for fast browser playback.
|
||||
|
||||
This eagerly transcodes input audio + stems so the review UI serves
|
||||
~3 MB OGG files instead of 35+ MB FLACs. Non-fatal: if transcoding
|
||||
fails, the review UI falls back to original FLAC signed URLs.
|
||||
"""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
try:
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
job_log.warning(f"Could not get job {job_id} for review audio transcoding")
|
||||
return
|
||||
|
||||
transcoding = AudioTranscodingService()
|
||||
transcoded = transcoding.prepare_review_audio_for_job(job)
|
||||
|
||||
job_log.info(f"Review audio transcoding complete: {len(transcoded)} files")
|
||||
|
||||
except Exception as e:
|
||||
# Non-fatal: review UI will fall back to FLAC signed URLs
|
||||
job_log.warning(f"Review audio transcoding failed (non-fatal): {e}")
|
||||
logger.warning(f"Job {job_id}: Review audio transcoding failed: {e}")
|
||||
|
||||
|
||||
async def _apply_countdown_padding_if_needed(
|
||||
job_id: str,
|
||||
job_manager: JobManager,
|
||||
|
||||
+110
-31
@@ -237,15 +237,17 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
if rclone_service.setup_rclone_config():
|
||||
job_log.info("Rclone config loaded for Dropbox upload")
|
||||
|
||||
# Load YouTube credentials if needed
|
||||
# Load YouTube credentials if needed (skip for private/non-published tracks)
|
||||
youtube_credentials = None
|
||||
if getattr(job, 'enable_youtube_upload', False):
|
||||
if getattr(job, 'enable_youtube_upload', False) and not getattr(job, 'is_private', False):
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
youtube_credentials = youtube_service.get_credentials_dict()
|
||||
job_log.info("YouTube credentials loaded for video upload")
|
||||
else:
|
||||
job_log.warning("YouTube credentials not available - upload will be skipped")
|
||||
elif getattr(job, 'is_private', False):
|
||||
job_log.info("Private track - skipping YouTube upload")
|
||||
|
||||
try:
|
||||
# Wrap entire worker in a tracing span
|
||||
@@ -337,15 +339,27 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
# Store result metadata in job BEFORE transitioning to COMPLETE
|
||||
# This ensures youtube_url is available when completion email is sent
|
||||
logger.info(f"[job:{job_id}] Video generation complete")
|
||||
job_manager.update_job(job_id, {
|
||||
'state_data': {
|
||||
**job.state_data,
|
||||
'brand_code': result.brand_code,
|
||||
'youtube_url': result.youtube_url,
|
||||
'dropbox_link': result.dropbox_link,
|
||||
'gdrive_files': result.gdrive_files,
|
||||
}
|
||||
})
|
||||
state_update = {
|
||||
**job.state_data,
|
||||
'brand_code': result.brand_code,
|
||||
'youtube_url': result.youtube_url,
|
||||
'youtube_upload_queued': result.youtube_upload_queued,
|
||||
'dropbox_link': result.dropbox_link,
|
||||
'gdrive_files': result.gdrive_files,
|
||||
}
|
||||
if result.distribution_warnings:
|
||||
state_update['distribution_warnings'] = result.distribution_warnings
|
||||
job_manager.update_job(job_id, {'state_data': state_update})
|
||||
|
||||
# Send Pushbullet alert if any distribution uploads failed
|
||||
if result.distribution_warnings:
|
||||
_send_distribution_warning_notification(
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
warnings=result.distribution_warnings,
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
job_manager.transition_to_state(
|
||||
@@ -467,16 +481,18 @@ async def generate_video_legacy(job_id: str) -> bool:
|
||||
else:
|
||||
job_log.warning("Rclone config not available - Dropbox upload will be skipped")
|
||||
|
||||
# Load YouTube credentials if needed
|
||||
# Load YouTube credentials if needed (skip for private/non-published tracks)
|
||||
youtube_credentials = None
|
||||
if getattr(job, 'enable_youtube_upload', False):
|
||||
if getattr(job, 'enable_youtube_upload', False) and not getattr(job, 'is_private', False):
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
youtube_credentials = youtube_service.get_credentials_dict()
|
||||
job_log.info("YouTube credentials loaded for video upload")
|
||||
else:
|
||||
job_log.warning("YouTube credentials not available - upload will be skipped")
|
||||
|
||||
elif getattr(job, 'is_private', False):
|
||||
job_log.info("Private track - skipping YouTube upload")
|
||||
|
||||
try:
|
||||
# Wrap entire worker in a tracing span
|
||||
with job_span("video-worker", job_id, {"artist": job.artist, "title": job.title}) as root_span:
|
||||
@@ -776,10 +792,14 @@ async def _handle_native_distribution(
|
||||
brand_code = keep_brand_code
|
||||
result['brand_code'] = brand_code
|
||||
job_log.info(f"Using preserved brand code: {brand_code}")
|
||||
|
||||
|
||||
# Get effective distribution settings (applies private track overrides if is_private=True)
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
# Upload to Dropbox using native SDK
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
brand_prefix = getattr(job, 'brand_prefix', None)
|
||||
dropbox_path = dist.dropbox_path
|
||||
brand_prefix = dist.brand_prefix
|
||||
|
||||
if dropbox_path and brand_prefix:
|
||||
try:
|
||||
@@ -792,9 +812,11 @@ async def _handle_native_distribution(
|
||||
else:
|
||||
job_log.info(f"Starting native Dropbox upload to {dropbox_path}")
|
||||
|
||||
# Calculate brand code from existing folders (if not already generated)
|
||||
# Calculate brand code atomically (if not already generated)
|
||||
if not brand_code:
|
||||
brand_code = dropbox.get_next_brand_code(dropbox_path, brand_prefix)
|
||||
from backend.services.brand_code_service import get_brand_code_service
|
||||
brand_code_service = get_brand_code_service()
|
||||
brand_code = brand_code_service.allocate_brand_code(brand_prefix, dropbox_path)
|
||||
result['brand_code'] = brand_code
|
||||
job_log.info(f"Generated brand code: {brand_code}")
|
||||
|
||||
@@ -831,12 +853,13 @@ async def _handle_native_distribution(
|
||||
job_log.warning(f"Dropbox SDK not installed: {e}")
|
||||
except Exception as e:
|
||||
job_log.error(f"Native Dropbox upload failed: {e}", exc_info=True)
|
||||
result.setdefault('distribution_warnings', []).append(f"Dropbox upload failed: {e}")
|
||||
# Don't fail the job - distribution is optional
|
||||
|
||||
# Upload to Google Drive using native API
|
||||
# Skip if orchestrator already uploaded (gdrive_files already populated)
|
||||
# This prevents duplicate uploads when using the orchestrator path
|
||||
gdrive_folder_id = getattr(job, 'gdrive_folder_id', None)
|
||||
gdrive_folder_id = dist.gdrive_folder_id
|
||||
existing_gdrive_files = result.get('gdrive_files')
|
||||
|
||||
if gdrive_folder_id and not existing_gdrive_files:
|
||||
@@ -874,6 +897,7 @@ async def _handle_native_distribution(
|
||||
job_log.warning(f"Google API packages not installed: {e}")
|
||||
except Exception as e:
|
||||
job_log.error(f"Native Google Drive upload failed: {e}", exc_info=True)
|
||||
result.setdefault('distribution_warnings', []).append(f"Google Drive upload failed: {e}")
|
||||
# Don't fail the job - distribution is optional
|
||||
elif existing_gdrive_files:
|
||||
job_log.info(f"Skipping Google Drive upload - orchestrator already uploaded {len(existing_gdrive_files)} files")
|
||||
@@ -881,17 +905,64 @@ async def _handle_native_distribution(
|
||||
# Update job state_data with brand code and links
|
||||
if brand_code or result.get('dropbox_link') or result.get('gdrive_files'):
|
||||
try:
|
||||
job_manager.update_job(job_id, {
|
||||
'state_data': {
|
||||
**job.state_data,
|
||||
'brand_code': brand_code,
|
||||
'dropbox_link': result.get('dropbox_link'),
|
||||
'gdrive_files': result.get('gdrive_files'),
|
||||
}
|
||||
})
|
||||
state_update = {
|
||||
**job.state_data,
|
||||
'brand_code': brand_code,
|
||||
'dropbox_link': result.get('dropbox_link'),
|
||||
'gdrive_files': result.get('gdrive_files'),
|
||||
}
|
||||
if result.get('distribution_warnings'):
|
||||
state_update['distribution_warnings'] = result['distribution_warnings']
|
||||
job_manager.update_job(job_id, {'state_data': state_update})
|
||||
except Exception as e:
|
||||
job_log.warning(f"Failed to update job state_data: {e}")
|
||||
|
||||
# Send Pushbullet alert if any distribution uploads failed
|
||||
if result.get('distribution_warnings'):
|
||||
_send_distribution_warning_notification(
|
||||
job_id=job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
warnings=result['distribution_warnings'],
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
|
||||
def _send_distribution_warning_notification(
|
||||
job_id: str,
|
||||
artist: str,
|
||||
title: str,
|
||||
warnings: list[str],
|
||||
settings=None,
|
||||
) -> None:
|
||||
"""Send Pushbullet notification when distribution uploads fail."""
|
||||
try:
|
||||
if settings is None:
|
||||
settings = get_settings()
|
||||
api_key = settings.get_secret("pushbullet-api-key")
|
||||
if not api_key:
|
||||
logger.warning("Pushbullet API key not found, skipping distribution warning notification")
|
||||
return
|
||||
|
||||
import requests as req
|
||||
|
||||
push_title = f"Distribution Warning: {artist} - {title}"
|
||||
body = f"Job {job_id} completed but {len(warnings)} upload(s) failed:\n\n"
|
||||
body += "\n".join(f" - {w}" for w in warnings)
|
||||
|
||||
resp = req.post(
|
||||
"https://api.pushbullet.com/v2/pushes",
|
||||
headers={"Access-Token": api_key, "Content-Type": "application/json"},
|
||||
json={"type": "note", "title": push_title, "body": body},
|
||||
timeout=10,
|
||||
)
|
||||
if resp.ok:
|
||||
logger.info(f"[job:{job_id}] Distribution warning notification sent via Pushbullet")
|
||||
else:
|
||||
logger.warning(f"[job:{job_id}] Pushbullet notification failed: {resp.status_code} {resp.text}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to send Pushbullet notification: {e}")
|
||||
|
||||
|
||||
def _validate_prerequisites(job) -> bool:
|
||||
"""Validate that all prerequisites are met for video generation."""
|
||||
@@ -925,11 +996,12 @@ def _validate_prerequisites(job) -> bool:
|
||||
logger.error(f"Job {job.job_id}: Missing lyrics video")
|
||||
return False
|
||||
|
||||
# Check instrumental exists - for 'custom', check existing_instrumental_gcs_path instead of stems
|
||||
# Check instrumental exists - for 'custom', check uploaded file or mute-region stem
|
||||
if instrumental_selection == 'custom':
|
||||
existing_instrumental_path = getattr(job, 'existing_instrumental_gcs_path', None)
|
||||
if not existing_instrumental_path:
|
||||
logger.error(f"Job {job.job_id}: Custom instrumental selected but no existing_instrumental_gcs_path")
|
||||
stems = job.file_urls.get('stems', {})
|
||||
if not existing_instrumental_path and not stems.get('custom_instrumental'):
|
||||
logger.error(f"Job {job.job_id}: Custom instrumental selected but no existing_instrumental_gcs_path or custom_instrumental stem")
|
||||
return False
|
||||
return True # Other stem checks not needed for custom instrumental
|
||||
|
||||
@@ -1000,6 +1072,13 @@ async def _setup_working_directory(
|
||||
log_progress(f"Downloading user-provided existing instrumental...")
|
||||
storage.download_file(existing_instrumental_path, instrumental_path)
|
||||
log_progress("Downloaded user-provided instrumental")
|
||||
elif instrumental_selection == 'custom':
|
||||
# Custom instrumental from mute-region editing
|
||||
custom_url = job.file_urls['stems']['custom_instrumental']
|
||||
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental Custom).flac")
|
||||
log_progress("Downloading custom (mute-region) instrumental...")
|
||||
storage.download_file(custom_url, instrumental_path)
|
||||
log_progress("Downloaded custom instrumental")
|
||||
else:
|
||||
# Use AI-separated instrumental based on selection
|
||||
instrumental_key = 'instrumental_clean' if instrumental_selection == 'clean' else 'instrumental_with_backing'
|
||||
|
||||
@@ -75,6 +75,10 @@ class OrchestratorConfig:
|
||||
# Audio synchronization - pad instrumental to match countdown-padded vocals
|
||||
countdown_padding_seconds: Optional[float] = None
|
||||
|
||||
# CDG sync fix: track if LRC already has countdown timestamps
|
||||
# When True, CDG generation will strip the countdown segment and adjust timestamps
|
||||
lrc_has_countdown_padding: bool = False
|
||||
|
||||
# Encoding backend preference
|
||||
encoding_backend: str = "auto" # "auto", "local", "gce"
|
||||
|
||||
@@ -102,9 +106,13 @@ class OrchestratorResult:
|
||||
|
||||
# Distribution results
|
||||
youtube_url: Optional[str] = None
|
||||
youtube_upload_queued: bool = False # True if upload was deferred due to quota
|
||||
dropbox_link: Optional[str] = None
|
||||
gdrive_files: Optional[Dict[str, str]] = field(default_factory=dict)
|
||||
|
||||
# Distribution warnings (non-fatal upload failures)
|
||||
distribution_warnings: List[str] = field(default_factory=list)
|
||||
|
||||
# Timing
|
||||
encoding_time_seconds: Optional[float] = None
|
||||
total_time_seconds: Optional[float] = None
|
||||
@@ -224,6 +232,18 @@ class VideoWorkerOrchestrator:
|
||||
if self.config.enable_cdg or self.config.enable_txt:
|
||||
await self._run_packaging()
|
||||
|
||||
# Validate required packaging outputs before expensive encoding
|
||||
if self.config.enable_cdg and not self.result.final_karaoke_cdg_zip:
|
||||
raise RuntimeError(
|
||||
"CDG generation was enabled but failed. "
|
||||
"Check worker logs for CDG-related errors."
|
||||
)
|
||||
if self.config.enable_txt and not self.result.final_karaoke_txt_zip:
|
||||
raise RuntimeError(
|
||||
"TXT generation was enabled but failed. "
|
||||
"Check worker logs for TXT-related errors."
|
||||
)
|
||||
|
||||
# Stage 2: Encoding
|
||||
await self._run_encoding()
|
||||
|
||||
@@ -236,6 +256,11 @@ class VideoWorkerOrchestrator:
|
||||
# Stage 5: Notifications (Discord)
|
||||
await self._run_notifications()
|
||||
|
||||
# Stage 6: Post-distribution GDrive validation
|
||||
# Only for jobs that uploaded to the public share (non-private)
|
||||
if self.config.gdrive_folder_id:
|
||||
await self._trigger_gdrive_validation()
|
||||
|
||||
self.result.success = True
|
||||
self.result.total_time_seconds = time.time() - start_time
|
||||
|
||||
@@ -255,6 +280,10 @@ class VideoWorkerOrchestrator:
|
||||
self.job_log.info("Starting packaging stage (CDG/TXT)")
|
||||
|
||||
if not self.config.lrc_file_path or not os.path.isfile(self.config.lrc_file_path):
|
||||
if self.config.enable_cdg or self.config.enable_txt:
|
||||
raise RuntimeError(
|
||||
f"CDG/TXT generation enabled but LRC file not available: {self.config.lrc_file_path}"
|
||||
)
|
||||
self.job_log.warning("No LRC file available, skipping CDG/TXT packaging")
|
||||
return
|
||||
|
||||
@@ -263,7 +292,12 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
# Generate CDG package
|
||||
if self.config.enable_cdg:
|
||||
self.job_log.info("Generating CDG package")
|
||||
if self.config.lrc_has_countdown_padding:
|
||||
self.job_log.info(
|
||||
f"Generating CDG package (compensating for {self.config.countdown_padding_seconds}s countdown in LRC)"
|
||||
)
|
||||
else:
|
||||
self.job_log.info("Generating CDG package")
|
||||
try:
|
||||
cdg_zip_path = os.path.join(
|
||||
self.config.output_dir,
|
||||
@@ -286,6 +320,8 @@ class VideoWorkerOrchestrator:
|
||||
title=self.config.title,
|
||||
output_mp3_path=mp3_path,
|
||||
output_cdg_path=cdg_path,
|
||||
lrc_has_countdown_padding=self.config.lrc_has_countdown_padding,
|
||||
countdown_padding_seconds=self.config.countdown_padding_seconds or 3.0,
|
||||
)
|
||||
|
||||
self.result.final_karaoke_cdg_zip = zip_file
|
||||
@@ -457,18 +493,15 @@ class VideoWorkerOrchestrator:
|
||||
# Generate brand code from Dropbox if configured
|
||||
if self.config.dropbox_path and self.config.brand_prefix:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
from backend.services.brand_code_service import get_brand_code_service
|
||||
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
brand_code = dropbox.get_next_brand_code(
|
||||
self.config.dropbox_path,
|
||||
self.config.brand_prefix
|
||||
)
|
||||
self.result.brand_code = brand_code
|
||||
self.job_log.info(f"Generated brand code: {brand_code}")
|
||||
else:
|
||||
self.job_log.warning("Dropbox not configured, skipping brand code generation")
|
||||
brand_code_service = get_brand_code_service()
|
||||
brand_code = brand_code_service.allocate_brand_code(
|
||||
self.config.brand_prefix,
|
||||
self.config.dropbox_path
|
||||
)
|
||||
self.result.brand_code = brand_code
|
||||
self.job_log.info(f"Generated brand code: {brand_code}")
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Brand code generation failed: {e}")
|
||||
@@ -511,16 +544,24 @@ class VideoWorkerOrchestrator:
|
||||
"""Upload video to YouTube."""
|
||||
self.job_log.info("Uploading to YouTube")
|
||||
|
||||
# Check YouTube upload rate limit (system-wide)
|
||||
# Get user_email from job
|
||||
user_email = "unknown"
|
||||
if self.job_manager:
|
||||
job = self.job_manager.get_job(self.config.job_id)
|
||||
if job and job.user_email:
|
||||
user_email = job.user_email
|
||||
|
||||
# Check YouTube quota availability (unit-based tracking)
|
||||
try:
|
||||
from backend.services.rate_limit_service import get_rate_limit_service
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
allowed, remaining, message = rate_limit_service.check_youtube_upload_limit()
|
||||
from backend.services.youtube_quota_service import get_youtube_quota_service
|
||||
quota_service = get_youtube_quota_service()
|
||||
allowed, remaining, message = quota_service.check_quota_available()
|
||||
if not allowed:
|
||||
self.job_log.warning(f"YouTube upload skipped: {message}")
|
||||
self.job_log.warning(f"YouTube quota insufficient, queueing upload: {message}")
|
||||
self._queue_youtube_upload(user_email, reason="quota_exceeded")
|
||||
return
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"Rate limit check failed, proceeding with upload: {e}")
|
||||
self.job_log.warning(f"Quota check failed, proceeding with upload: {e}")
|
||||
|
||||
# Find the best video file to upload (prefer MKV for FLAC audio, then lossless MP4)
|
||||
video_to_upload = None
|
||||
@@ -560,27 +601,65 @@ class VideoWorkerOrchestrator:
|
||||
self.result.youtube_url = video_url
|
||||
self.job_log.info(f"Uploaded to YouTube: {video_url}")
|
||||
|
||||
# Record the upload for rate limiting
|
||||
# Record quota consumption for all operations in the upload flow
|
||||
try:
|
||||
# Get user_email from job if available
|
||||
user_email = "unknown"
|
||||
if self.job_manager:
|
||||
job = self.job_manager.get_job(self.config.job_id)
|
||||
if job and job.user_email:
|
||||
user_email = job.user_email
|
||||
quota_service = get_youtube_quota_service()
|
||||
# search.list (duplicate check) + videos.insert + thumbnails.set
|
||||
quota_service.record_operation(self.config.job_id, user_email, "search.list")
|
||||
quota_service.record_operation(self.config.job_id, user_email, "videos.insert")
|
||||
if self.config.title_jpg_path and os.path.isfile(self.config.title_jpg_path):
|
||||
quota_service.record_operation(self.config.job_id, user_email, "thumbnails.set")
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"Failed to record YouTube quota usage: {e}")
|
||||
|
||||
# Also record in legacy rate limit service for backward compatibility
|
||||
try:
|
||||
from backend.services.rate_limit_service import get_rate_limit_service
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
rate_limit_service.record_youtube_upload(
|
||||
job_id=self.config.job_id,
|
||||
user_email=user_email
|
||||
)
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"Failed to record YouTube upload for rate limiting: {e}")
|
||||
self.job_log.warning(f"Failed to record YouTube upload for legacy rate limiting: {e}")
|
||||
else:
|
||||
self.job_log.warning("YouTube upload did not return a URL")
|
||||
|
||||
except Exception as e:
|
||||
error_str = str(e)
|
||||
# Check for YouTube quota exceeded error (HTTP 403 with quotaExceeded reason)
|
||||
if "quotaExceeded" in error_str or (
|
||||
hasattr(e, 'resp') and hasattr(e.resp, 'status') and e.resp.status == 403
|
||||
):
|
||||
self.job_log.warning(f"YouTube quota exceeded during upload, queueing: {e}")
|
||||
self._queue_youtube_upload(user_email, reason="quota_exceeded_api")
|
||||
return
|
||||
|
||||
self.job_log.error(f"YouTube upload failed: {e}")
|
||||
self.result.distribution_warnings.append(f"YouTube upload failed: {e}")
|
||||
# Don't fail the pipeline - YouTube is optional
|
||||
|
||||
def _queue_youtube_upload(self, user_email: str, reason: str = "quota_exceeded"):
|
||||
"""Queue a YouTube upload for later processing when quota is insufficient."""
|
||||
try:
|
||||
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
|
||||
queue_service = get_youtube_upload_queue_service()
|
||||
queue_service.queue_upload(
|
||||
job_id=self.config.job_id,
|
||||
user_email=user_email,
|
||||
artist=self.config.artist,
|
||||
title=self.config.title,
|
||||
brand_code=self.result.brand_code,
|
||||
reason=reason,
|
||||
)
|
||||
self.result.youtube_upload_queued = True
|
||||
self.job_log.info(f"YouTube upload queued for later processing (reason: {reason})")
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Failed to queue YouTube upload: {e}")
|
||||
self.result.distribution_warnings.append(
|
||||
f"YouTube upload skipped (quota exceeded) and failed to queue: {e}"
|
||||
)
|
||||
|
||||
async def _upload_to_dropbox(self):
|
||||
"""Upload files to Dropbox."""
|
||||
self.job_log.info("Uploading to Dropbox")
|
||||
@@ -615,6 +694,7 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Dropbox upload failed: {e}")
|
||||
self.result.distribution_warnings.append(f"Dropbox upload failed: {e}")
|
||||
# Don't fail the pipeline - Dropbox is optional
|
||||
|
||||
async def _upload_to_gdrive(self):
|
||||
@@ -651,6 +731,7 @@ class VideoWorkerOrchestrator:
|
||||
|
||||
except Exception as e:
|
||||
self.job_log.error(f"Google Drive upload failed: {e}")
|
||||
self.result.distribution_warnings.append(f"Google Drive upload failed: {e}")
|
||||
# Don't fail the pipeline - GDrive is optional
|
||||
|
||||
async def _run_notifications(self):
|
||||
@@ -673,6 +754,28 @@ class VideoWorkerOrchestrator:
|
||||
self.job_log.error(f"Discord notification failed: {e}")
|
||||
# Don't fail the pipeline - notifications are optional
|
||||
|
||||
async def _trigger_gdrive_validation(self):
|
||||
"""Schedule delayed GDrive validation after uploading to the public share.
|
||||
|
||||
Uses Cloud Tasks to delay the validation by 5 minutes, giving E2E tests
|
||||
time to verify output and clean up (delete test files) before the validator
|
||||
checks for sequence gaps. Falls back to immediate trigger if scheduling fails.
|
||||
"""
|
||||
try:
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
success = await worker_service.schedule_gdrive_validation()
|
||||
if success:
|
||||
self.job_log.info("Scheduled delayed GDrive validation (5 min)")
|
||||
else:
|
||||
# Fallback: trigger immediately if scheduling failed
|
||||
self.job_log.warning("Cloud Tasks scheduling failed, triggering validation immediately")
|
||||
from backend.services.gdrive_validator_client import trigger_gdrive_validation
|
||||
trigger_gdrive_validation()
|
||||
except Exception as e:
|
||||
self.job_log.warning(f"GDrive validation trigger failed (non-fatal): {e}")
|
||||
# Never fail the pipeline for validation
|
||||
|
||||
|
||||
def create_orchestrator_config_from_job(
|
||||
job,
|
||||
@@ -706,18 +809,26 @@ def create_orchestrator_config_from_job(
|
||||
|
||||
# Get countdown padding info from lyrics metadata
|
||||
# This ensures instrumental is padded to match vocals if countdown was added
|
||||
# Also tracks if LRC has countdown padding so CDG can compensate
|
||||
lyrics_metadata = job.state_data.get('lyrics_metadata', {})
|
||||
countdown_padding_seconds = None
|
||||
if lyrics_metadata.get('has_countdown_padding'):
|
||||
lrc_has_countdown_padding = lyrics_metadata.get('has_countdown_padding', False)
|
||||
if lrc_has_countdown_padding:
|
||||
countdown_padding_seconds = lyrics_metadata.get('countdown_padding_seconds', 3.0)
|
||||
|
||||
if existing_instrumental:
|
||||
ext = Path(existing_instrumental).suffix.lower()
|
||||
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental User){ext}")
|
||||
elif instrumental_selection == 'custom':
|
||||
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental Custom).flac")
|
||||
else:
|
||||
instrumental_suffix = "Clean" if instrumental_selection == 'clean' else "Backing"
|
||||
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental {instrumental_suffix}).flac")
|
||||
|
||||
# Get effective distribution settings (applies private track overrides if is_private=True)
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
|
||||
return OrchestratorConfig(
|
||||
job_id=job.job_id,
|
||||
artist=job.artist,
|
||||
@@ -737,18 +848,18 @@ def create_orchestrator_config_from_job(
|
||||
# Feature flags
|
||||
enable_cdg=getattr(job, 'enable_cdg', False),
|
||||
enable_txt=getattr(job, 'enable_txt', False),
|
||||
enable_youtube_upload=getattr(job, 'enable_youtube_upload', False),
|
||||
enable_youtube_upload=dist.enable_youtube_upload,
|
||||
|
||||
# Service configurations
|
||||
brand_prefix=getattr(job, 'brand_prefix', None),
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
# Service configurations (distribution settings from helper, respects is_private)
|
||||
brand_prefix=dist.brand_prefix,
|
||||
discord_webhook_url=dist.discord_webhook_url,
|
||||
youtube_credentials=youtube_credentials,
|
||||
youtube_description_template=getattr(job, 'youtube_description_template', None),
|
||||
youtube_description_template=dist.youtube_description,
|
||||
cdg_styles=cdg_styles,
|
||||
|
||||
# Dropbox/GDrive
|
||||
dropbox_path=getattr(job, 'dropbox_path', None),
|
||||
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
|
||||
# Dropbox/GDrive (overridden for private tracks)
|
||||
dropbox_path=dist.dropbox_path,
|
||||
gdrive_folder_id=dist.gdrive_folder_id,
|
||||
|
||||
# Keep existing brand code
|
||||
keep_brand_code=getattr(job, 'keep_brand_code', None),
|
||||
@@ -759,6 +870,9 @@ def create_orchestrator_config_from_job(
|
||||
# Audio synchronization - pad instrumental to match countdown-padded vocals
|
||||
countdown_padding_seconds=countdown_padding_seconds,
|
||||
|
||||
# CDG sync fix: track if LRC already has countdown timestamps
|
||||
lrc_has_countdown_padding=lrc_has_countdown_padding,
|
||||
|
||||
# Encoding backend - auto selects GCE if available
|
||||
encoding_backend="auto",
|
||||
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
"""
|
||||
YouTube upload queue processor.
|
||||
|
||||
Processes deferred YouTube uploads when quota is available.
|
||||
Called by Cloud Scheduler via an internal endpoint (hourly).
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from typing import Dict, Any, Optional
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.youtube_quota_service import get_youtube_quota_service
|
||||
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def process_youtube_upload_queue() -> Dict[str, Any]:
|
||||
"""
|
||||
Process queued YouTube uploads.
|
||||
|
||||
Checks quota availability, then processes queued uploads one at a time.
|
||||
Stops if quota is exhausted during processing.
|
||||
|
||||
Returns:
|
||||
Summary dict with counts of processed, failed, and remaining items
|
||||
"""
|
||||
settings = get_settings()
|
||||
quota_service = get_youtube_quota_service()
|
||||
queue_service = get_youtube_upload_queue_service()
|
||||
|
||||
# Check if any quota is available
|
||||
allowed, remaining, message = quota_service.check_quota_available()
|
||||
if not allowed:
|
||||
logger.info(f"YouTube queue processor: no quota available, skipping. {message}")
|
||||
return {
|
||||
"status": "skipped",
|
||||
"reason": "no_quota",
|
||||
"message": message,
|
||||
"processed": 0,
|
||||
"failed": 0,
|
||||
"remaining": len(queue_service.get_queued_uploads()),
|
||||
}
|
||||
|
||||
# Get queued uploads
|
||||
queued = queue_service.get_queued_uploads(limit=20)
|
||||
if not queued:
|
||||
logger.info("YouTube queue processor: no uploads queued")
|
||||
return {
|
||||
"status": "empty",
|
||||
"message": "No uploads queued",
|
||||
"processed": 0,
|
||||
"failed": 0,
|
||||
"remaining": 0,
|
||||
}
|
||||
|
||||
logger.info(f"YouTube queue processor: processing {len(queued)} queued uploads")
|
||||
|
||||
processed = 0
|
||||
failed = 0
|
||||
|
||||
for entry in queued:
|
||||
job_id = entry["job_id"]
|
||||
|
||||
# Re-check quota before each upload
|
||||
allowed, remaining, message = quota_service.check_quota_available()
|
||||
if not allowed:
|
||||
logger.info(f"YouTube queue processor: quota exhausted after {processed} uploads")
|
||||
break
|
||||
|
||||
# Claim the entry
|
||||
if not queue_service.mark_processing(job_id):
|
||||
logger.info(f"YouTube queue processor: could not claim job {job_id}, skipping")
|
||||
continue
|
||||
|
||||
try:
|
||||
youtube_url = await _process_single_upload(job_id, entry, quota_service, settings)
|
||||
if youtube_url:
|
||||
queue_service.mark_completed(job_id, youtube_url)
|
||||
|
||||
# Update job state_data with the YouTube URL
|
||||
_update_job_youtube_url(job_id, youtube_url)
|
||||
|
||||
# Send follow-up email
|
||||
await _send_youtube_upload_notification(job_id, entry, youtube_url)
|
||||
|
||||
processed += 1
|
||||
else:
|
||||
queue_service.mark_failed(job_id, "Upload returned no URL")
|
||||
failed += 1
|
||||
|
||||
except Exception as e:
|
||||
error_str = str(e)
|
||||
logger.exception(f"YouTube queue processor: failed to process job {job_id}: {e}")
|
||||
|
||||
# If quota exceeded, stop processing entirely
|
||||
if "quotaExceeded" in error_str:
|
||||
queue_service.mark_failed(job_id, f"Quota exceeded: {error_str}")
|
||||
logger.warning("YouTube queue processor: quota exceeded, stopping")
|
||||
failed += 1
|
||||
break
|
||||
|
||||
queue_service.mark_failed(job_id, error_str)
|
||||
failed += 1
|
||||
|
||||
remaining_count = len(queue_service.get_queued_uploads())
|
||||
logger.info(
|
||||
f"YouTube queue processor: done. processed={processed} failed={failed} remaining={remaining_count}"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "processed",
|
||||
"processed": processed,
|
||||
"failed": failed,
|
||||
"remaining": remaining_count,
|
||||
}
|
||||
|
||||
|
||||
async def _process_single_upload(
|
||||
job_id: str,
|
||||
entry: Dict[str, Any],
|
||||
quota_service,
|
||||
settings,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
Process a single queued YouTube upload.
|
||||
|
||||
Downloads the video from GCS, uploads to YouTube, records quota.
|
||||
|
||||
Returns:
|
||||
YouTube URL if successful, None otherwise
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.error(f"YouTube queue processor: job {job_id} not found")
|
||||
return None
|
||||
|
||||
# Create temp directory for the download
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"yt-queue-{job_id[:8]}-")
|
||||
|
||||
try:
|
||||
# Find the video file in GCS (prefer MKV, then lossless MP4, then lossy)
|
||||
video_path = _download_video_from_gcs(job_id, job, storage, temp_dir)
|
||||
if not video_path:
|
||||
logger.error(f"YouTube queue processor: no video file found for job {job_id}")
|
||||
return None
|
||||
|
||||
# Download thumbnail if available
|
||||
thumbnail_path = _download_thumbnail_from_gcs(job_id, job, storage, temp_dir)
|
||||
|
||||
# Build YouTube service with fresh credentials
|
||||
youtube_service = _create_youtube_service(settings)
|
||||
if not youtube_service:
|
||||
logger.error("YouTube queue processor: failed to create YouTube service")
|
||||
return None
|
||||
|
||||
# Build metadata
|
||||
artist = entry.get("artist", job.artist or "Unknown")
|
||||
title = entry.get("title", job.title or "Unknown")
|
||||
youtube_title = f"{artist} - {title} (Karaoke)"
|
||||
if len(youtube_title) > 95:
|
||||
youtube_title = youtube_title[:92] + " ..."
|
||||
|
||||
description = settings.default_youtube_description or ""
|
||||
brand_code = entry.get("brand_code") or job.state_data.get("brand_code")
|
||||
if brand_code:
|
||||
description = f"{description}\n\nBrand Code: {brand_code}".strip()
|
||||
|
||||
# Upload
|
||||
video_id, video_url = youtube_service.upload_video(
|
||||
video_path=video_path,
|
||||
title=youtube_title,
|
||||
description=description,
|
||||
thumbnail_path=thumbnail_path,
|
||||
tags=["karaoke", artist, title],
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
if video_url:
|
||||
# Record quota consumption
|
||||
user_email = entry.get("user_email", "unknown")
|
||||
quota_service.record_operation(job_id, user_email, "search.list")
|
||||
quota_service.record_operation(job_id, user_email, "videos.insert")
|
||||
if thumbnail_path:
|
||||
quota_service.record_operation(job_id, user_email, "thumbnails.set")
|
||||
|
||||
logger.info(f"YouTube queue processor: uploaded job {job_id} -> {video_url}")
|
||||
return video_url
|
||||
|
||||
return None
|
||||
|
||||
finally:
|
||||
# Cleanup temp directory
|
||||
if os.path.exists(temp_dir):
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _download_video_from_gcs(
|
||||
job_id: str, job, storage: StorageService, temp_dir: str
|
||||
) -> Optional[str]:
|
||||
"""Download the best available video file from GCS."""
|
||||
file_urls = job.file_urls or {}
|
||||
finals = file_urls.get("finals", {}) if isinstance(file_urls.get("finals"), dict) else {}
|
||||
|
||||
# Priority order: MKV (FLAC audio) > lossless MP4 > lossy 4K MP4 > lossy 720p MP4
|
||||
candidates = [
|
||||
(finals.get("lossless_4k_mkv"), "lossless_4k_mkv", ".mkv"),
|
||||
(finals.get("lossless_4k_mp4"), "lossless_4k_mp4", ".mp4"),
|
||||
(finals.get("lossy_4k_mp4"), "lossy_4k_mp4", ".mp4"),
|
||||
(finals.get("lossy_720p_mp4"), "lossy_720p_mp4", ".mp4"),
|
||||
]
|
||||
|
||||
for gcs_path, key, ext in candidates:
|
||||
if gcs_path:
|
||||
local_path = os.path.join(temp_dir, f"video{ext}")
|
||||
try:
|
||||
storage.download_file(gcs_path, local_path)
|
||||
if os.path.isfile(local_path) and os.path.getsize(local_path) > 0:
|
||||
logger.info(f"Downloaded {key} from GCS for job {job_id}")
|
||||
return local_path
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to download {key} for job {job_id}: {e}")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _download_thumbnail_from_gcs(
|
||||
job_id: str, job, storage: StorageService, temp_dir: str
|
||||
) -> Optional[str]:
|
||||
"""Download the thumbnail from GCS if available."""
|
||||
file_urls = job.file_urls or {}
|
||||
screens = file_urls.get("screens", {}) if isinstance(file_urls.get("screens"), dict) else {}
|
||||
thumbnail_url = screens.get("title_jpg")
|
||||
if not thumbnail_url:
|
||||
return None
|
||||
|
||||
local_path = os.path.join(temp_dir, "thumbnail.jpg")
|
||||
try:
|
||||
storage.download_file(thumbnail_url, local_path)
|
||||
if os.path.isfile(local_path) and os.path.getsize(local_path) > 0:
|
||||
return local_path
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to download thumbnail for job {job_id}: {e}")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _create_youtube_service(settings):
|
||||
"""Create a YouTube upload service with fresh credentials from Secret Manager."""
|
||||
try:
|
||||
from backend.services.youtube_upload_service import YouTubeUploadService
|
||||
import json
|
||||
|
||||
youtube_creds_json = settings.get_secret("youtube-oauth-credentials")
|
||||
if not youtube_creds_json:
|
||||
logger.error("YouTube OAuth credentials not found in Secret Manager")
|
||||
return None
|
||||
|
||||
credentials = json.loads(youtube_creds_json)
|
||||
return YouTubeUploadService(
|
||||
credentials=credentials,
|
||||
non_interactive=True,
|
||||
server_side_mode=True,
|
||||
logger=logger,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception(f"Failed to create YouTube service: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def _update_job_youtube_url(job_id: str, youtube_url: str) -> None:
|
||||
"""Update job state_data with the YouTube URL after deferred upload."""
|
||||
try:
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if job:
|
||||
state_data = job.state_data or {}
|
||||
state_data["youtube_url"] = youtube_url
|
||||
state_data["youtube_upload_queued"] = False # No longer queued
|
||||
job_manager.update_job(job_id, {"state_data": state_data})
|
||||
logger.info(f"Updated job {job_id} state_data with YouTube URL")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update job {job_id} with YouTube URL: {e}")
|
||||
|
||||
|
||||
async def _send_youtube_upload_notification(
|
||||
job_id: str, entry: Dict[str, Any], youtube_url: str
|
||||
) -> None:
|
||||
"""Send follow-up email notifying user their YouTube upload is complete."""
|
||||
try:
|
||||
from backend.services.job_notification_service import get_job_notification_service
|
||||
notification_service = get_job_notification_service()
|
||||
|
||||
await notification_service.send_youtube_upload_complete_email(
|
||||
job_id=job_id,
|
||||
user_email=entry.get("user_email", ""),
|
||||
artist=entry.get("artist", ""),
|
||||
title=entry.get("title", ""),
|
||||
youtube_url=youtube_url,
|
||||
brand_code=entry.get("brand_code"),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send YouTube upload notification for job {job_id}: {e}")
|
||||
# Don't fail the upload over a notification error - mark it in the queue
|
||||
try:
|
||||
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
|
||||
queue_service = get_youtube_upload_queue_service()
|
||||
doc_ref = queue_service.db.collection("youtube_upload_queue").document(job_id)
|
||||
doc_ref.update({"notification_sent": False, "notification_error": str(e)})
|
||||
except Exception:
|
||||
pass
|
||||
+431
-10
@@ -77,9 +77,49 @@ Content-Type: multipart/form-data
|
||||
file: <audio file>
|
||||
artist: "Artist Name"
|
||||
title: "Song Title"
|
||||
is_private: false # Optional. If true, Dropbox uses Tracks-NonPublished/NOMADNP, no YouTube/GDrive
|
||||
```
|
||||
|
||||
Returns job ID. Triggers async processing.
|
||||
Returns job ID. Triggers async processing. Max request body ~32MB (Cloud Run limit). For larger files, use the signed URL upload flow below.
|
||||
|
||||
#### Create Job with Signed URL Upload (large files)
|
||||
|
||||
Three-step flow that bypasses Cloud Run's 32MB body limit. Used automatically by the frontend for files ≥25MB.
|
||||
|
||||
**Step 1: Create job and get signed URLs**
|
||||
```http
|
||||
POST /api/jobs/create-with-upload-urls
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "Artist Name",
|
||||
"title": "Song Title",
|
||||
"files": [{"filename": "song.wav", "content_type": "audio/wav", "file_type": "audio"}],
|
||||
"is_private": false
|
||||
}
|
||||
```
|
||||
|
||||
Returns `job_id` and `upload_urls` list. Each entry has `file_type`, `upload_url` (signed GCS URL), and `content_type`.
|
||||
|
||||
**Step 2: Upload file directly to GCS**
|
||||
```http
|
||||
PUT <upload_url>
|
||||
Content-Type: audio/wav
|
||||
|
||||
<file bytes>
|
||||
```
|
||||
|
||||
Direct PUT to GCS signed URL — does not go through the backend.
|
||||
|
||||
**Step 3: Notify backend**
|
||||
```http
|
||||
POST /api/jobs/{job_id}/uploads-complete
|
||||
Content-Type: application/json
|
||||
|
||||
{"uploaded_files": ["audio"]}
|
||||
```
|
||||
|
||||
Triggers async processing.
|
||||
|
||||
#### Get Job Status
|
||||
|
||||
@@ -100,12 +140,15 @@ GET /api/jobs
|
||||
GET /api/jobs?status=complete
|
||||
GET /api/jobs?limit=10&offset=0
|
||||
GET /api/jobs?exclude_test=false
|
||||
GET /api/jobs?fields=summary&hide_completed=true
|
||||
```
|
||||
|
||||
Query parameters:
|
||||
- `exclude_test` (bool, default: true) - Admin only: filter out jobs from test users
|
||||
- `status` - Filter by job status
|
||||
- `limit` / `offset` - Pagination
|
||||
- `fields` (string, optional) - Set to `summary` to return only dashboard-required fields using Firestore field projection. Reduces payload from ~16MB to <500KB for large job lists.
|
||||
- `hide_completed` (bool, default: false) - Exclude successful completions (complete, prep_complete) server-side. Failed jobs remain visible.
|
||||
|
||||
#### Delete Job
|
||||
|
||||
@@ -166,7 +209,105 @@ Generates preview video during review. The `use_background_image` option control
|
||||
GET /api/review/{job_id}/audio/{stem_type}
|
||||
```
|
||||
|
||||
Streams audio for review playback.
|
||||
Redirects to a signed GCS URL for review playback. Audio is served as OGG Opus (~3 MB) transcoded from the original FLAC (~35 MB). Transcoding happens eagerly during screen generation; if the transcoded file is missing, falls back to the original FLAC.
|
||||
|
||||
#### Create Custom Instrumental
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/create-custom-instrumental
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"mute_regions": [
|
||||
{"start_seconds": 17.0, "end_seconds": 42.0},
|
||||
{"start_seconds": 53.8, "end_seconds": 71.4}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Creates a custom instrumental by muting selected regions of backing vocals, combining with the clean instrumental, and uploading to GCS. Returns a signed audio URL for immediate playback.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"message": "Custom instrumental created with 2 mute regions",
|
||||
"audio_url": "https://storage.googleapis.com/...",
|
||||
"muted_duration_seconds": 42.6
|
||||
}
|
||||
```
|
||||
|
||||
#### Upload Custom Instrumental
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/upload-instrumental
|
||||
Content-Type: multipart/form-data
|
||||
|
||||
file: <audio file (mp3, wav, flac, ogg, aac, m4a)>
|
||||
```
|
||||
|
||||
Uploads an external instrumental audio file for use during review. The uploaded file's duration is validated against the original audio — must match within ±0.5 seconds. Requires job to be in `awaiting_review` or `in_review` state.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"duration_seconds": 240.0,
|
||||
"message": "Custom instrumental uploaded (240.0s)"
|
||||
}
|
||||
```
|
||||
|
||||
Error (duration mismatch):
|
||||
```json
|
||||
{
|
||||
"detail": "Duration mismatch: uploaded file is 235.0s but original audio is 240.0s. The instrumental must be exactly 240.0s (±0.5s)."
|
||||
}
|
||||
```
|
||||
|
||||
#### Submit Edit Log
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/edit-log
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"session_id": "abc123",
|
||||
"job_id": "test-job",
|
||||
"audio_hash": "hash",
|
||||
"started_at": "2026-03-01T00:00:00.000Z",
|
||||
"entries": [
|
||||
{
|
||||
"id": "entry-1",
|
||||
"timestamp": "2026-03-01T00:01:00.000Z",
|
||||
"operation": "word_change",
|
||||
"segment_id": "seg-0",
|
||||
"segment_index": 0,
|
||||
"word_ids_before": ["w1"],
|
||||
"word_ids_after": ["w1"],
|
||||
"text_before": "helo",
|
||||
"text_after": "hello",
|
||||
"feedback": { "reason": "misheard_word", "timestamp": "..." }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Stores a session edit log to GCS at `jobs/{job_id}/lyrics/edit_log_{session_id}.json`. Tracks all user edits and optional feedback reasons for transcription improvement. Called automatically on review submission.
|
||||
|
||||
#### Submit Annotations
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/v1/annotations
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"annotations": [
|
||||
{ "annotation_type": "SOUND_ALIKE", "original_text": "helo" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
|
||||
|
||||
### Instrumental Selection (Finalise-Only Jobs)
|
||||
|
||||
@@ -183,6 +324,91 @@ Content-Type: application/json
|
||||
|
||||
**Note**: For normal jobs, instrumental selection is now part of the combined review flow (see `/api/review/{job_id}/complete` above).
|
||||
|
||||
### Catalog (Song Lookup)
|
||||
|
||||
Proxies to karaoke-decide's MusicBrainz + Spotify catalog for autocomplete, and scrapes karaokenerds.com for community karaoke version detection. All endpoints require authentication and are rate-limited (20 requests/minute per user). Results are cached in-memory (5 min for catalog, 1 hour for community checks).
|
||||
|
||||
#### Search Artists
|
||||
|
||||
```http
|
||||
GET /api/catalog/artists?q=queen&limit=10
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
[
|
||||
{
|
||||
"name": "Queen",
|
||||
"mbid": "0383dadf-...",
|
||||
"disambiguation": null,
|
||||
"artist_type": "Group",
|
||||
"spotify_id": "1dfeR4HaWDbWqFHLkxsg1d",
|
||||
"popularity": 85,
|
||||
"genres": ["rock"],
|
||||
"tags": ["classic rock"]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
#### Search Tracks
|
||||
|
||||
```http
|
||||
GET /api/catalog/tracks?q=bohemian&artist=queen&limit=10
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
[
|
||||
{
|
||||
"track_name": "Bohemian Rhapsody - Remastered 2011",
|
||||
"artist_name": "Queen",
|
||||
"track_id": "4u7EnebtmKWzUH433cf5Qv",
|
||||
"artist_id": "1dfeR4HaWDbWqFHLkxsg1d",
|
||||
"popularity": 81,
|
||||
"duration_ms": 354320,
|
||||
"explicit": false
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
The `artist` query parameter is optional but recommended — filters results by artist for more relevant suggestions.
|
||||
|
||||
#### Check Community Versions
|
||||
|
||||
```http
|
||||
POST /api/catalog/community-check
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "Queen",
|
||||
"title": "Bohemian Rhapsody"
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"has_community": true,
|
||||
"songs": [
|
||||
{
|
||||
"title": "Bohemian Rhapsody",
|
||||
"artist": "Queen",
|
||||
"community_tracks": [
|
||||
{
|
||||
"brand_name": "ObsKure Karaoke",
|
||||
"brand_code": "OBSK",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=...",
|
||||
"is_community": true
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"best_youtube_url": "https://www.youtube.com/watch?v=..."
|
||||
}
|
||||
```
|
||||
|
||||
When `has_community` is true, the frontend shows a dismissible green banner suggesting the user check existing versions before creating a new one.
|
||||
|
||||
### Audio Search
|
||||
|
||||
#### Search for Audio
|
||||
@@ -232,6 +458,56 @@ Content-Type: application/json
|
||||
|
||||
Selects an audio source from the search results and starts processing.
|
||||
|
||||
#### Standalone Search (Guided Flow — Step 2)
|
||||
|
||||
```http
|
||||
POST /api/audio-search/search-standalone
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "Artist Name",
|
||||
"title": "Song Title"
|
||||
}
|
||||
```
|
||||
|
||||
Searches for audio **without creating a job**. Returns a short-lived search session (30-min TTL).
|
||||
Credits are checked here but **not deducted** — deduction happens at job creation.
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"search_session_id": "uuid",
|
||||
"results": [...],
|
||||
"results_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
No results returns `results: []` (not a 404). Use `search_session_id` with the create-from-search endpoint below.
|
||||
|
||||
#### Create Job from Search Session (Guided Flow — Step 3)
|
||||
|
||||
```http
|
||||
POST /api/jobs/create-from-search
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"search_session_id": "uuid",
|
||||
"selection_index": 0,
|
||||
"artist": "ABBA",
|
||||
"title": "Waterloo",
|
||||
"display_artist": "ABBA (Display)",
|
||||
"display_title": "Waterloo (Karaoke)",
|
||||
"is_private": false
|
||||
}
|
||||
```
|
||||
|
||||
Creates the job from a previously completed standalone search session. All final field values
|
||||
(is_private, display overrides) are set at creation time — no patching needed afterward.
|
||||
The job goes directly to `DOWNLOADING_AUDIO` (skips `AWAITING_AUDIO_SELECTION`).
|
||||
The session is consumed (deleted) on success.
|
||||
|
||||
Returns 404 with "Search expired — please search again" if the session has expired.
|
||||
|
||||
### Themes
|
||||
|
||||
```http
|
||||
@@ -304,6 +580,20 @@ GET /api/tenant/config/{tenant_id}
|
||||
|
||||
Get specific tenant config by ID. Returns 404 if tenant not found or inactive.
|
||||
|
||||
#### Tenant Asset Proxy
|
||||
|
||||
```http
|
||||
GET /api/tenant/asset/{tenant_id}/{filename}
|
||||
```
|
||||
|
||||
Serves tenant assets (logos, etc.) from GCS. No authentication required. Returns the file with appropriate content-type headers.
|
||||
|
||||
- `tenant_id`: Tenant identifier (e.g., `singa`, `vocalstar`)
|
||||
- `filename`: Asset filename (e.g., `logo.png`)
|
||||
- Returns 404 if asset not found
|
||||
|
||||
Used by the frontend `TenantLogo` component to load tenant logos. Tenant configs store logo paths as `https://api.nomadkaraoke.com/api/tenant/asset/{tenant_id}/logo.png` (the frontend also converts legacy `gs://` paths to this format as a fallback).
|
||||
|
||||
### Internal (Admin Only)
|
||||
|
||||
These endpoints are used by workers and require admin tokens.
|
||||
@@ -348,7 +638,9 @@ POST /api/internal/jobs/{job_id}/trigger-video
|
||||
Common status codes:
|
||||
- `400` - Bad request
|
||||
- `401` - Unauthorized
|
||||
- `402` - Insufficient credits (see [Credit Enforcement](#credit-enforcement))
|
||||
- `404` - Job not found
|
||||
- `429` - Rate limit exceeded
|
||||
- `500` - Server error
|
||||
|
||||
## User Authentication
|
||||
@@ -379,6 +671,8 @@ GET /api/users/me
|
||||
Authorization: Bearer SESSION_TOKEN
|
||||
```
|
||||
|
||||
Response includes `feedback_eligible: bool` indicating whether the user can earn credits by submitting feedback (requires 2+ completed jobs and no prior feedback submission).
|
||||
|
||||
### Logout
|
||||
|
||||
```http
|
||||
@@ -448,6 +742,30 @@ After payment completes via Stripe webhook:
|
||||
|
||||
**Email suppression**: Intermediate reminder emails (lyrics review, instrumental selection) are suppressed for made-for-you jobs since admin handles these directly. Only order confirmation and final delivery emails go to customer
|
||||
|
||||
### Credit Enforcement
|
||||
|
||||
Credits are checked and deducted at job creation time. The flow:
|
||||
|
||||
1. **Check** - `user_service.has_credits()` verifies the user has >= 1 credit
|
||||
2. **Create job** - Job is persisted to Firestore
|
||||
3. **Deduct** - `user_service.deduct_credit()` atomically deducts 1 credit (with job_id for audit trail)
|
||||
4. **Refund on failure** - If the job fails, 1 credit is automatically refunded
|
||||
|
||||
Admin users bypass credit checks entirely. New users receive 2 welcome credits. Users can earn 2 additional free credits by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
|
||||
|
||||
#### 402 Response
|
||||
|
||||
When a user has no credits, job creation returns HTTP 402:
|
||||
|
||||
```json
|
||||
{
|
||||
"detail": "You're out of credits. Buy more to continue creating karaoke videos.",
|
||||
"credits_available": 0,
|
||||
"credits_required": 1,
|
||||
"buy_url": "/#pricing"
|
||||
}
|
||||
```
|
||||
|
||||
### Stripe Webhook
|
||||
|
||||
```http
|
||||
@@ -456,7 +774,9 @@ POST /api/users/webhooks/stripe
|
||||
|
||||
Handles `checkout.session.completed` events.
|
||||
|
||||
## Beta Tester Program (PR #90)
|
||||
## Beta Tester Program (Deprecated)
|
||||
|
||||
> **Note**: The beta program was removed from the homepage in PR #430. These endpoints are preserved for backward compatibility but are no longer actively promoted. New users receive 2 welcome credits instead. See [User Feedback for Credits](#user-feedback-for-credits) for the current feedback-for-credits mechanism.
|
||||
|
||||
### Enroll as Beta Tester
|
||||
|
||||
@@ -473,7 +793,7 @@ Content-Type: application/json
|
||||
|
||||
Returns 1 free credit and session token.
|
||||
|
||||
### Submit Feedback
|
||||
### Submit Beta Feedback
|
||||
|
||||
```http
|
||||
POST /api/users/beta/feedback
|
||||
@@ -492,6 +812,56 @@ Content-Type: application/json
|
||||
|
||||
Bonus credit for detailed feedback (50+ chars).
|
||||
|
||||
### User Feedback for Credits
|
||||
|
||||
Available to all users (not just beta testers). Users who have completed 2+ jobs can submit feedback to earn 2 free credits.
|
||||
|
||||
#### Check Eligibility
|
||||
|
||||
```http
|
||||
GET /api/users/feedback/eligibility
|
||||
Authorization: Bearer SESSION_TOKEN
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"eligible": true,
|
||||
"has_submitted": false,
|
||||
"jobs_completed": 3,
|
||||
"credits_reward": 2
|
||||
}
|
||||
```
|
||||
|
||||
#### Submit Feedback
|
||||
|
||||
```http
|
||||
POST /api/users/feedback
|
||||
Authorization: Bearer SESSION_TOKEN
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"overall_rating": 4,
|
||||
"ease_of_use_rating": 5,
|
||||
"lyrics_accuracy_rating": 4,
|
||||
"correction_experience_rating": 3,
|
||||
"what_went_well": "The lyrics sync was really accurate...",
|
||||
"what_could_improve": "Would love more theme options...",
|
||||
"additional_comments": "",
|
||||
"would_recommend": true,
|
||||
"would_use_again": true
|
||||
}
|
||||
```
|
||||
|
||||
Requirements:
|
||||
- User must have completed 2+ jobs
|
||||
- At least one text field must have >50 characters
|
||||
- User can only submit once (duplicate prevention)
|
||||
|
||||
Grants 2 credits on success. Feedback stored in `user_feedback` Firestore collection.
|
||||
|
||||
The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide feedback prompts without an extra API call.
|
||||
|
||||
## Admin Endpoints
|
||||
|
||||
All admin endpoints require an admin-role session token.
|
||||
@@ -858,7 +1228,9 @@ Content-Type: application/json
|
||||
}
|
||||
```
|
||||
|
||||
Updates editable job fields. Allowed fields: `artist`, `title`, `user_email`, `theme_id`, `brand_prefix`, `discord_webhook_url`, `youtube_description`, `youtube_description_template`, `customer_email`, `customer_notes`, `enable_cdg`, `enable_txt`, `enable_youtube_upload`, `non_interactive`, `prep_only`.
|
||||
Updates editable job fields. Allowed fields: `artist`, `title`, `user_email`, `theme_id`, `brand_prefix`, `discord_webhook_url`, `youtube_description`, `youtube_description_template`, `customer_email`, `customer_notes`, `enable_cdg`, `enable_txt`, `enable_youtube_upload`, `non_interactive`, `prep_only`, `is_private`.
|
||||
|
||||
**Note:** Setting `is_private=true` on a completed job with existing outputs triggers automatic output deletion.
|
||||
|
||||
Response:
|
||||
```json
|
||||
@@ -895,7 +1267,7 @@ Allowed target states:
|
||||
**Note**: With the combined review flow, `awaiting_instrumental_selection` is no longer a valid reset target for new jobs. Use `awaiting_review` instead to re-select the instrumental.
|
||||
|
||||
The `instrumental_selected` state is useful for re-encoding and re-distributing a job after using "Delete Outputs":
|
||||
1. Delete outputs → Removes YouTube/Dropbox/GDrive files, frees brand code
|
||||
1. Delete outputs → Removes YouTube/Dropbox/GDrive files, recycles brand code
|
||||
2. Reset to `instrumental_selected` → Clears video state, keeps settings, auto-triggers video worker
|
||||
3. Job re-processes with same instrumental, lyrics, and distribution settings
|
||||
|
||||
@@ -990,6 +1362,30 @@ Response:
|
||||
|
||||
Screen generation takes 30-60 seconds. Monitor progress via job timeline or logs.
|
||||
|
||||
#### Prepare Review Audio
|
||||
|
||||
```http
|
||||
POST /api/admin/jobs/{job_id}/prepare-review-audio
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Transcodes all review audio files (input + stems) to OGG Opus 128kbps for fast browser playback. Idempotent — skips files already transcoded.
|
||||
|
||||
Use this to backfill existing jobs created before eager transcoding was deployed, or to re-transcode after stems are regenerated.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"job_id": "abc123",
|
||||
"transcoded_files": [
|
||||
"jobs/abc123/review-audio/song.ogg",
|
||||
"jobs/abc123/review-audio/instrumental_clean.ogg"
|
||||
],
|
||||
"message": "Transcoded 2 files to OGG Opus"
|
||||
}
|
||||
```
|
||||
|
||||
#### Restart Job
|
||||
|
||||
```http
|
||||
@@ -1096,7 +1492,7 @@ POST /api/admin/jobs/{job_id}/delete-outputs
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Deletes all distributed outputs (YouTube, Dropbox, Google Drive) for a job while preserving the job record. Use this to fix quality issues: delete outputs, reset to `awaiting_review`, correct lyrics, and re-process.
|
||||
Deletes all distributed outputs (YouTube, Dropbox, Google Drive) for a job and recycles the brand code. The job record is preserved. Use this to fix quality issues: delete outputs, reset to `awaiting_review`, correct lyrics, and re-process.
|
||||
|
||||
Requirements:
|
||||
- Job must be in terminal state (`complete`, `prep_complete`, `failed`, or `cancelled`)
|
||||
@@ -1111,7 +1507,8 @@ Response:
|
||||
"deleted_services": {
|
||||
"youtube": {"status": "success", "video_id": "dQw4w9WgXcQ"},
|
||||
"dropbox": {"status": "success", "path": "/Karaoke/NOMAD-1234 - Artist - Title"},
|
||||
"gdrive": {"status": "success", "files": {"mp4": true, "mp4_720p": true}}
|
||||
"gdrive": {"status": "success", "files": {"mp4": true, "mp4_720p": true}},
|
||||
"brand_code": {"status": "recycled", "code": "NOMAD-1234"}
|
||||
},
|
||||
"cleared_state_data": ["youtube_url", "brand_code", "dropbox_link", "gdrive_files"],
|
||||
"outputs_deleted_at": "2026-01-10T12:00:00Z"
|
||||
@@ -1120,7 +1517,7 @@ Response:
|
||||
|
||||
Service statuses: `success`, `failed`, `skipped` (not configured or no data), `partial` (some files failed), `error` (exception).
|
||||
|
||||
The brand code is freed for reuse when the Dropbox folder is deleted. When the job is re-processed and outputs are re-uploaded, the `outputs_deleted_at` flag is automatically cleared.
|
||||
The brand code is automatically recycled after both Dropbox and GDrive cleanup succeed. If either cleanup fails, the brand code is preserved to prevent collisions. Brand code recycling status is returned in `deleted_services.brand_code`. The `DELETE /api/jobs/{id}` endpoint also recycles brand codes before deletion. When the job is re-processed and outputs are re-uploaded, the `outputs_deleted_at` flag is automatically cleared.
|
||||
|
||||
#### Clear Worker Progress
|
||||
|
||||
@@ -1171,7 +1568,7 @@ Called by Cloud Tasks 5 minutes after a job enters a blocking state (primarily `
|
||||
### User Limits
|
||||
|
||||
- **Jobs per day**: 5 (configurable via `RATE_LIMIT_JOBS_PER_DAY`)
|
||||
- **YouTube uploads per day**: 10 system-wide (configurable via `RATE_LIMIT_YOUTUBE_UPLOADS_PER_DAY`)
|
||||
- **YouTube uploads**: Quota-aware, ~33 uploads/day within 10,000 units/day API quota (configurable via `YOUTUBE_QUOTA_DAILY_LIMIT`, `YOUTUBE_QUOTA_UPLOAD_COST`, `YOUTUBE_QUOTA_SAFETY_MARGIN`). Uploads exceeding quota are queued and processed hourly.
|
||||
- **Beta enrollment per IP**: 1 per 24 hours (configurable via `RATE_LIMIT_BETA_IP_PER_DAY`)
|
||||
|
||||
Rate limiting can be disabled via `ENABLE_RATE_LIMITING=false`.
|
||||
@@ -1226,6 +1623,30 @@ DELETE /api/admin/rate-limits/overrides/{email}
|
||||
```
|
||||
Manage user overrides (bypass or custom limits).
|
||||
|
||||
### YouTube Upload Queue
|
||||
|
||||
```http
|
||||
GET /api/admin/rate-limits/youtube-queue
|
||||
```
|
||||
Returns list of queued/processing/failed YouTube uploads with job details, status, attempt count, and timestamps.
|
||||
|
||||
```http
|
||||
POST /api/admin/rate-limits/youtube-queue/{job_id}/retry
|
||||
```
|
||||
Reset a failed upload back to queued status for retry.
|
||||
|
||||
```http
|
||||
POST /api/admin/rate-limits/youtube-queue/process
|
||||
```
|
||||
Manually trigger queue processing (normally runs hourly via Cloud Scheduler).
|
||||
|
||||
### Internal YouTube Queue Processing
|
||||
|
||||
```http
|
||||
POST /api/internal/youtube-queue/process
|
||||
```
|
||||
Called by Cloud Scheduler hourly. Processes queued uploads while quota is available. Returns summary of processed/failed/remaining uploads.
|
||||
|
||||
## Webhooks
|
||||
|
||||
Stripe webhooks implemented at `/api/users/webhooks/stripe`.
|
||||
|
||||
+48
-6
@@ -55,10 +55,11 @@
|
||||
└────────┬────────┘ └────────┬────────┘
|
||||
└──────────┬───────────┘
|
||||
▼
|
||||
3. SCREENS GENERATION + BACKING VOCALS ANALYSIS
|
||||
3. SCREENS GENERATION + BACKING VOCALS ANALYSIS + AUDIO TRANSCODING
|
||||
• Title screen (5s video)
|
||||
• End screen (5s video)
|
||||
• Analyze backing vocals track (for instrumental selection)
|
||||
• Transcode audio to OGG Opus for review UI (~3 MB vs 35 MB FLAC)
|
||||
▼
|
||||
4. COMBINED HUMAN REVIEW (AWAITING_REVIEW)
|
||||
• React UI for lyrics correction
|
||||
@@ -118,6 +119,8 @@ jobs/{job_id}/
|
||||
├── lyrics/
|
||||
│ ├── corrections.json # Auto-corrected
|
||||
│ ├── corrections_updated.json # After human review
|
||||
│ ├── edit_log_{session}.json # User edit log with feedback
|
||||
│ ├── annotations.json # Correction annotations
|
||||
│ └── karaoke.ass
|
||||
├── screens/
|
||||
│ ├── title.mov
|
||||
@@ -164,7 +167,10 @@ LyricsTranscriber LyricsTranscriber
|
||||
| Flacfetch | Audio downloads (YouTube, torrents) | Recommended* |
|
||||
| YouTube API | Video upload | Optional |
|
||||
| SendGrid | Email notifications | Optional |
|
||||
| Cloud Tasks | Delayed task scheduling (idle reminders) | Optional |
|
||||
| Cloud Tasks | Delayed task scheduling (idle reminders, YouTube queue) | Optional |
|
||||
| Cloud Scheduler | Hourly YouTube upload queue processing | Optional |
|
||||
| karaoke-decide | Song catalog (MusicBrainz + Spotify) for autocomplete | Optional |
|
||||
| KaraokeNerds | Community karaoke version detection | Optional |
|
||||
|
||||
*Flacfetch runs on a dedicated GCE VM with YouTube cookies and tracker access. Without it, YouTube downloads will fail due to bot detection on Cloud Run IPs.
|
||||
|
||||
@@ -179,7 +185,10 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
|
||||
| `jobs/{job_id}/logs` | Worker log entries (subcollection) | timestamp, level, worker, message, ttl_expiry |
|
||||
| `sessions` | Magic link auth sessions | user_email, token, expires_at |
|
||||
| `magic_links` | Passwordless auth tokens | email, token, expires_at, used |
|
||||
| `beta_feedback` | Beta program feedback | user_email, ratings, comments |
|
||||
| `user_feedback` | User feedback for credits (all users) | user_email, ratings, comments, created_at |
|
||||
| `beta_feedback` | Beta program feedback (deprecated) | user_email, ratings, comments |
|
||||
| `youtube_quota` | Daily YouTube API quota tracking | date_pt, units_consumed, units_limit, operations[] |
|
||||
| `youtube_upload_queue` | Deferred YouTube uploads | job_id, status, user_email, queued_at, youtube_url |
|
||||
|
||||
**Note**: The `users` collection in the same Firestore instance belongs to karaoke-decide (different schema: user_id, is_guest, quiz_* fields). Don't use it for karaoke-gen.
|
||||
|
||||
@@ -228,6 +237,11 @@ The Video Worker uses an orchestrator pattern to ensure all features work regard
|
||||
| `email_service.py` | SendGrid email delivery with CC support |
|
||||
| `template_service.py` | GCS-backed email templates |
|
||||
| `job_notification_service.py` | Email orchestration (completion, reminders) |
|
||||
| `audio_transcoding_service.py` | Transcode FLAC → OGG Opus for review UI playback |
|
||||
| `youtube_quota_service.py` | Track YouTube API quota units (Firestore, PT midnight reset) |
|
||||
| `youtube_upload_queue_service.py` | Deferred YouTube upload queue management |
|
||||
| `catalog_proxy_service.py` | Proxy to karaoke-decide catalog API (artist/track search) |
|
||||
| `karaokenerds_service.py` | Scrape karaokenerds.com for community karaoke versions |
|
||||
|
||||
## Audio Source Download Flow
|
||||
|
||||
@@ -434,15 +448,42 @@ if tenant_config and not tenant_config.features.audio_search:
|
||||
raise HTTPException(403, "Audio search not enabled for this tenant")
|
||||
```
|
||||
|
||||
### First Tenant: Vocal Star
|
||||
### Active Tenants
|
||||
|
||||
- Subdomain: `vocalstar.nomadkaraoke.com`
|
||||
**Vocal Star** (`vocalstar.nomadkaraoke.com`)
|
||||
- Features: File upload only (no audio search, no YouTube URL)
|
||||
- Distribution: Download only (no YouTube/Dropbox/GDrive)
|
||||
- Theme: Locked to "vocalstar" theme (yellow/blue)
|
||||
- Auth: Restricted to `@vocal-star.com` and `@vocalstarmusic.com` emails
|
||||
- Setup: `python scripts/setup-vocalstar-tenant.py`
|
||||
|
||||
**Singa** (`singa.nomadkaraoke.com`)
|
||||
- Features: File upload only (no audio search, no YouTube URL)
|
||||
- Distribution: Download only
|
||||
- Theme: Locked to "singa" theme (green/black)
|
||||
- Auth: Restricted to `@singa.com` emails
|
||||
- Setup: `python scripts/setup-singa-tenant.py`
|
||||
|
||||
### Tenant Portal Frontend (B2B Deployment)
|
||||
|
||||
B2B tenants are served from a **separate Cloudflare Pages project** (`karaoke-gen-tenant`) built with `NEXT_PUBLIC_TENANT_PORTAL=true`. This build flag enables tree-shaking of consumer-only content (landing page, pricing, beta enrollment) at build time, keeping the bundle lean for white-label deployments.
|
||||
|
||||
**Runtime tenant injection**: A Cloudflare Pages edge function intercepts HTML responses and injects tenant-specific configuration before the page reaches the browser:
|
||||
|
||||
```javascript
|
||||
// Injected by edge function into <head>
|
||||
window.__TENANT_CONFIG__ = { id: "vocalstar", branding: { ... }, features: { ... } }
|
||||
// CSS variables for dynamic theming
|
||||
--tenant-primary-color: #ffd700;
|
||||
--tenant-background-color: #1a1a2e;
|
||||
```
|
||||
|
||||
The frontend's `TenantProvider` reads `window.__TENANT_CONFIG__` on startup (no API round-trip needed for initial render). This approach works for both custom domains (`vocalstar.nomadkaraoke.com`) and the shared tenant portal domain.
|
||||
|
||||
**Magic link emails**: When a tenant user requests a magic link, the email uses the tenant-specific URL (e.g., `https://vocalstar.nomadkaraoke.com/auth/verify?token=...`) rather than the main app URL. The `job_notification_service.py` resolves the correct base URL from the tenant config's `subdomain` field.
|
||||
|
||||
**Admin preview**: Admins can preview any tenant's branding in the main app by appending `?preview_tenant=<tenant_id>` to any URL. This bypasses subdomain detection and loads the specified tenant config, useful for verifying branding before DNS cutover.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Backend**: FastAPI, Python 3.12, Cloud Run
|
||||
@@ -450,7 +491,8 @@ if tenant_config and not tenant_config.features.audio_search:
|
||||
- **Database**: Firestore
|
||||
- **Storage**: Google Cloud Storage
|
||||
- **Secrets**: Google Secret Manager
|
||||
- **Task Queues**: Cloud Tasks (idle reminders)
|
||||
- **Task Queues**: Cloud Tasks (idle reminders, YouTube upload queue)
|
||||
- **Scheduling**: Cloud Scheduler (hourly YouTube queue processing)
|
||||
- **Email**: SendGrid
|
||||
- **IaC**: Pulumi
|
||||
- **CI/CD**: GitHub Actions
|
||||
@@ -131,6 +131,20 @@ npm run build
|
||||
npx wrangler pages deploy out
|
||||
```
|
||||
|
||||
Requires `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` environment variables (set via `.envrc` or exported manually). The `wrangler.toml` in the repo root configures the project name and build output directory.
|
||||
|
||||
### Testing Tenant Portals Locally
|
||||
|
||||
To test a tenant portal on `localhost:3000`, add a `?tenant=` query parameter:
|
||||
|
||||
```
|
||||
http://localhost:3000/?tenant=singa # Singa portal (green/black)
|
||||
http://localhost:3000/?tenant=vocalstar # Vocal Star portal (yellow/blue)
|
||||
http://localhost:3000/ # Default Nomad Karaoke (no tenant)
|
||||
```
|
||||
|
||||
The frontend's `detectTenantFromUrl()` checks for the `tenant` query param on localhost. In production, tenants are detected from the subdomain (e.g., `singa.nomadkaraoke.com`).
|
||||
|
||||
## Environment Variables
|
||||
|
||||
### Backend (.env)
|
||||
@@ -174,6 +188,8 @@ TESTMAIL_NAMESPACE=... # testmail.app namespace
|
||||
| `./scripts/analyze_log_timing.py <log>` | Profile karaoke-gen performance from logs |
|
||||
| `./scripts/benchmark_ffmpeg.py` | Isolated FFmpeg encoding benchmark |
|
||||
| `./scripts/compare_local_vs_remote.py` | Compare local vs cloud karaoke-gen performance |
|
||||
| `./scripts/setup-singa-tenant.py` | Generate Singa tenant assets and upload to GCS |
|
||||
| `./scripts/setup-vocalstar-tenant.py` | Generate Vocal Star tenant assets and upload to GCS |
|
||||
|
||||
## Project Structure
|
||||
|
||||
|
||||
@@ -17,11 +17,10 @@
|
||||
### 1. New User Registration (testmail.app)
|
||||
|
||||
- [ ] Navigate to landing page (`gen.nomadkaraoke.com`)
|
||||
- [ ] Click "Sign In" or "Get Started" button
|
||||
- [ ] Click "Sign Up Free" button on landing page
|
||||
- [ ] Generate a unique test email address (testmail.app namespace)
|
||||
- [ ] Enter the test email in the beta enrollment form
|
||||
- [ ] Submit the form
|
||||
- [ ] Wait for welcome/magic-link email via testmail.app API
|
||||
- [ ] Enter the test email in the AuthDialog and click "Send Sign-In Link"
|
||||
- [ ] Wait for magic-link email via testmail.app API
|
||||
- [ ] Extract the magic link from the email
|
||||
- [ ] Click/navigate to the magic link to authenticate
|
||||
- [ ] Verify user is logged in and has credits
|
||||
@@ -36,12 +35,13 @@
|
||||
- [ ] Click "Search" or equivalent button
|
||||
- [ ] Wait for search results to appear in the UI
|
||||
|
||||
### 3. Audio Selection (UI Only)
|
||||
### 3. Audio Selection & Customization (UI Only)
|
||||
|
||||
- [ ] Audio selection dialog/panel should appear
|
||||
- [ ] View available audio options in the UI
|
||||
- [ ] Click to select the first/best audio option
|
||||
- [ ] Confirm the selection via UI button
|
||||
- [ ] **Enable private mode** (check the `#guided-private` checkbox) — test jobs use `NOMADNP` prefix to avoid consuming public `NOMAD` brand codes and skip GDrive/YouTube uploads
|
||||
- [ ] Wait for job to transition to processing state
|
||||
|
||||
### 4. Wait for Lyrics Transcription
|
||||
@@ -93,14 +93,12 @@
|
||||
> **CRITICAL**: Test MUST clean up after itself to avoid polluting production distribution channels
|
||||
|
||||
- [ ] Verify job.state_data contains distribution results:
|
||||
- [ ] `brand_code` - The generated brand code (e.g., "NOMAD-1234")
|
||||
- [ ] `youtube_url` - YouTube video URL (if YouTube enabled)
|
||||
- [ ] `brand_code` - The generated brand code (e.g., `NOMADNP-0042` for private mode)
|
||||
- [ ] `dropbox_link` - Dropbox shared link (if Dropbox enabled)
|
||||
- [ ] `gdrive_files` - Google Drive file IDs (if GDrive enabled)
|
||||
- [ ] **CLEANUP** - After verification, delete all distributed content:
|
||||
- [ ] Delete YouTube video via API (using stored youtube_url)
|
||||
- [ ] Delete Dropbox folder via API (using brand_code + dropbox_path)
|
||||
- [ ] Delete Google Drive files via API (using gdrive_files IDs)
|
||||
- [ ] YouTube and GDrive should NOT be present (private mode skips them)
|
||||
- [ ] **CLEANUP** - After verification, clean up via `cleanup-distribution` endpoint:
|
||||
- [ ] Deletes Dropbox folder and recycles brand code
|
||||
- [ ] YouTube/GDrive cleanup skipped for private jobs
|
||||
- [ ] Delete the test job from the system (GCS + Firestore)
|
||||
|
||||
## Technical Requirements
|
||||
@@ -137,7 +135,7 @@ Use `piri - dog` because:
|
||||
|
||||
Capture screenshots at each major milestone:
|
||||
1. Landing page loaded
|
||||
2. Beta form submitted
|
||||
2. Magic link sent
|
||||
3. Email received
|
||||
4. Logged in successfully
|
||||
5. Job created
|
||||
|
||||
Loaded 100 of 753 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user