mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 09:06:04 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73fa5d7c01 | ||
|
|
5f72e618cc | ||
|
|
032ac11a45 | ||
|
|
055a5d3f73 | ||
|
|
53bed95e76 |
No files matched your search
@@ -2175,7 +2175,7 @@ jobs:
|
||||
--max-instances 20 \
|
||||
--min-instances 0 \
|
||||
--clear-vpc-connector \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,STORAGE_RETENTION_DRY_RUN=false,STORAGE_RETENTION_MAX_JOBS_PER_RUN=50,CONVERSION_EMAILS_ENABLED=true,REVIEW_LAST_CHANCE_ENABLED=true,CONVERSION_OFFER_PERCENT=25,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,STORAGE_RETENTION_DRY_RUN=false,STORAGE_RETENTION_MAX_JOBS_PER_RUN=50,CONVERSION_EMAILS_ENABLED=true,REVIEW_LAST_CHANCE_ENABLED=true,CONVERSION_OFFER_PERCENT=25,YOUTUBE_COMMENT_AUTOREPLY_ENABLED=true,YOUTUBE_COMMENT_AUTOREPLY_START=2026-04-22T00:00:00Z,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,GEMINI_API_KEY=gemini-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,LRCLIB_APP_ID=lrclib-app-id:latest,LRCLIB_SECRET_KEY=lrclib-api-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest,DECIDE_GEN_PARTNER_SECRET=decide-gen-partner-secret:latest"
|
||||
|
||||
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
|
||||
|
||||
@@ -63,6 +63,10 @@ AudioDownloadResult = AudioFetchResult
|
||||
# parity tests in backend/tests/test_bulk_foundations.py guard the behaviour.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Seeders a lossless torrent needs to count as "BEST CHOICE" (and so be auto-picked).
|
||||
# A lossless torrent with even ~10 seeders is almost always the right source.
|
||||
BEST_CHOICE_MIN_SEEDERS = 10
|
||||
|
||||
_BEST_RESULT_PRIORITY = [
|
||||
"BEST CHOICE",
|
||||
"STUDIO ALBUMS",
|
||||
@@ -92,7 +96,7 @@ def _categorize_result(result: Dict[str, Any]) -> str:
|
||||
# Vinyl rips checked before BEST CHOICE (surface noise -> poor for karaoke)
|
||||
if is_lossless and media == "vinyl":
|
||||
return "VINYL RIPS"
|
||||
if is_lossless and seeders >= 50:
|
||||
if is_lossless and seeders >= BEST_CHOICE_MIN_SEEDERS:
|
||||
return "BEST CHOICE"
|
||||
if is_lossless and is_24bit:
|
||||
return "HI-RES 24-BIT"
|
||||
@@ -175,7 +179,7 @@ def pick_auto_selection(results: List[Dict[str, Any]], search_title: str = "") -
|
||||
"""Return the index to auto-select, or None if no confident lossless pick.
|
||||
|
||||
Tier-1 rule (mirrors getSearchConfidence): the best result must be in the
|
||||
BEST CHOICE category (lossless, 50+ seeders, non-vinyl) AND its filename
|
||||
BEST CHOICE category (lossless, BEST_CHOICE_MIN_SEEDERS+ seeders, non-vinyl) AND its filename
|
||||
must match ``search_title`` (the song the user searched for). Otherwise we
|
||||
defer to human selection.
|
||||
"""
|
||||
|
||||
@@ -23,6 +23,7 @@ from backend.services.fake_workers.config import FakeConfig, get_fake_config
|
||||
from backend.services.fake_workers.lyrics import build_corrections, build_lrc
|
||||
from backend.services.fake_workers.media import MediaSet, get_media
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.quick_version import service as quick
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -116,6 +117,27 @@ async def run_audio_download(job_id: str) -> bool:
|
||||
|
||||
# ---------------------------------------------------------------- audio separation
|
||||
|
||||
async def _emit_quick_version(job, job_manager: JobManager, storage: StorageService, media: MediaSet) -> None:
|
||||
"""kjbox make-it jobs: write the same ``state_data.quick_version`` +
|
||||
``file_urls.quick.video_mp4`` the real audio worker's quick-version thread does
|
||||
(``services/quick_version``), using the tiny fixture mp4. Same gate as prod
|
||||
(``should_build_quick_version``), so non-kjbox jobs are untouched."""
|
||||
if not quick.should_build_quick_version(job):
|
||||
return
|
||||
job_id = job.job_id
|
||||
quick.set_quick_state(job_manager, job_id, quick.STATUS_SEPARATING, started_at=quick._now_iso())
|
||||
quick.set_quick_state(job_manager, job_id, quick.STATUS_RENDERING)
|
||||
gcs_path = f"jobs/{job_id}/quick/quick.mp4"
|
||||
await asyncio.to_thread(storage.upload_file, media.final_mp4, gcs_path)
|
||||
job_manager.update_file_url(job_id, quick.FILE_CATEGORY, quick.FILE_KEY, gcs_path)
|
||||
quick.set_quick_state(
|
||||
job_manager, job_id, quick.STATUS_READY,
|
||||
lyrics_tier="fake_workers", line_count=0,
|
||||
duration_seconds=float(media.duration),
|
||||
size_bytes=os.path.getsize(media.final_mp4), ready_at=quick._now_iso(),
|
||||
)
|
||||
|
||||
|
||||
async def run_audio(job_id: str) -> bool:
|
||||
config = await _begin("audio", job_id)
|
||||
from backend.workers.audio_worker import _transcode_review_stems, upload_separation_results
|
||||
@@ -123,11 +145,18 @@ async def run_audio(job_id: str) -> bool:
|
||||
from backend.workers.worker_logging import create_job_logger
|
||||
|
||||
job_manager, storage = JobManager(), StorageService()
|
||||
if not _job_or_none(job_manager, job_id):
|
||||
job = _job_or_none(job_manager, job_id)
|
||||
if not job:
|
||||
return False
|
||||
job_log = create_job_logger(job_id, "audio")
|
||||
media = await asyncio.to_thread(_media_for, config)
|
||||
|
||||
try:
|
||||
await _emit_quick_version(job, job_manager, storage, media)
|
||||
except Exception as e: # non-fatal, same as the real worker
|
||||
logger.warning(f"[job:{job_id}] fake audio: quick version failed: {e}")
|
||||
quick.set_quick_state(job_manager, job_id, quick.STATUS_FAILED, error=str(e)[:500])
|
||||
|
||||
job_manager.update_state_data(job_id, "audio_progress", {
|
||||
"stage": "separating", "progress": 30, "message": "Separating audio (fake)",
|
||||
})
|
||||
|
||||
@@ -9,7 +9,7 @@ every provider "works".
|
||||
(``getSearchConfidence`` in frontend/lib/audio-search-utils.ts):
|
||||
|
||||
- ``perfect`` (tier 1): well-seeded lossless torrent of the right track ("BEST CHOICE").
|
||||
- ``recommended`` (tier 2): the right track, lossless, but only 20 seeders.
|
||||
- ``recommended`` (tier 2): the right track, lossless, but only 5 seeders.
|
||||
- ``unsure`` (tier 3): every result names a different track; 3 seeders.
|
||||
|
||||
``frontend_fixture()`` writes these shapes to ``FRONTEND_FIXTURE``, which the
|
||||
@@ -39,7 +39,7 @@ def _source_id(provider: str, artist: str, title: str) -> str:
|
||||
|
||||
def build_results(artist: str, title: str, duration: int, confidence: str = "perfect") -> List[AudioSearchResult]:
|
||||
"""The three fake results for ``artist`` / ``title`` in ``confidence``'s shape."""
|
||||
seeders = {"perfect": 120, "recommended": 20, "unsure": 3}[confidence]
|
||||
seeders = {"perfect": 120, "recommended": 5, "unsure": 3}[confidence]
|
||||
track = _MISMATCHED_TITLE if confidence == "unsure" else title
|
||||
results = [
|
||||
AudioSearchResult(
|
||||
|
||||
@@ -469,6 +469,11 @@ def decide(
|
||||
# ---------------------------------------------------------------------------
|
||||
# YouTube API helpers (shared by the replay script and the worker)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reads are idempotent, so retry them: a long run idles the shared HTTP connection
|
||||
# between calls (Gemini work in between) and Google drops it ("Broken pipe").
|
||||
# Writes (post_reply) are NOT retried: a lost response could mean a double reply.
|
||||
READ_RETRIES = 3
|
||||
|
||||
def iter_comment_threads(youtube, channel_id: str = NOMAD_CHANNEL_ID,
|
||||
stop_before: Optional[datetime] = None, max_pages: int = 500):
|
||||
"""Yield ``commentThreads.list`` items for the whole channel, newest first.
|
||||
@@ -482,7 +487,7 @@ def iter_comment_threads(youtube, channel_id: str = NOMAD_CHANNEL_ID,
|
||||
youtube.commentThreads()
|
||||
.list(part="snippet,replies", allThreadsRelatedToChannelId=channel_id,
|
||||
order="time", maxResults=100, textFormat="plainText", pageToken=token)
|
||||
.execute()
|
||||
.execute(num_retries=READ_RETRIES)
|
||||
)
|
||||
items = resp.get("items", [])
|
||||
reached_end = False
|
||||
@@ -507,7 +512,7 @@ def fetch_owner_replies(youtube, parent_id: str, channel_id: str = NOMAD_CHANNEL
|
||||
youtube.comments()
|
||||
.list(part="snippet", parentId=parent_id, maxResults=100,
|
||||
textFormat="plainText", pageToken=token)
|
||||
.execute()
|
||||
.execute(num_retries=READ_RETRIES)
|
||||
)
|
||||
for c in resp.get("items", []):
|
||||
s = c.get("snippet", {})
|
||||
@@ -528,7 +533,9 @@ def load_thread(youtube, item: Dict, channel_id: str = NOMAD_CHANNEL_ID) -> Comm
|
||||
|
||||
|
||||
def post_reply(youtube, parent_comment_id: str, text: str) -> str:
|
||||
"""Post a reply as the channel (needs the youtube.force-ssl scope; 50 units)."""
|
||||
"""Post a reply as the channel (needs the youtube.force-ssl scope; 50 units).
|
||||
|
||||
Pass a freshly built client in long runs (see READ_RETRIES): never retried."""
|
||||
resp = (
|
||||
youtube.comments()
|
||||
.insert(part="snippet", body={"snippet": {"parentId": parent_comment_id, "textOriginal": text}})
|
||||
|
||||
@@ -72,9 +72,14 @@ class TestPickAutoSelection:
|
||||
assert pick_auto_selection([_lossy(0), _lossy(1)], "Bohemian Rhapsody") is None
|
||||
|
||||
def test_lossless_but_low_seeders_returns_none(self):
|
||||
# seeders < 50 -> STUDIO ALBUMS, not BEST CHOICE -> tier 2, no auto-pick
|
||||
# seeders < 10 -> STUDIO ALBUMS, not BEST CHOICE -> tier 2, no auto-pick
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
assert pick_auto_selection([_lossless_best(0, seeders=10)], "Bohemian Rhapsody") is None
|
||||
assert pick_auto_selection([_lossless_best(0, seeders=9)], "Bohemian Rhapsody") is None
|
||||
|
||||
def test_lossless_with_ten_seeders_is_auto_picked(self):
|
||||
# A modestly-seeded lossless album torrent (e.g. 15-31 seeders) is still the right pick.
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
assert pick_auto_selection([_lossy(0), _lossless_best(1, seeders=10)], "Bohemian Rhapsody") == 1
|
||||
|
||||
def test_filename_mismatch_returns_none(self):
|
||||
# best is lossless+well-seeded but the file is clearly a different track
|
||||
@@ -106,3 +111,15 @@ class TestPickAutoSelection:
|
||||
from backend.services.audio_search_service import pick_auto_selection
|
||||
r = _lossless_best(0, seeders=80, title="Someone", target_file="04 - Someone.flac")
|
||||
assert pick_auto_selection([r], "One") is None
|
||||
|
||||
|
||||
def test_best_choice_min_seeders_matches_frontend():
|
||||
"""The tier-1 seeder bar is duplicated in the frontend; keep the two in lockstep."""
|
||||
import re
|
||||
from pathlib import Path
|
||||
from backend.services.audio_search_service import BEST_CHOICE_MIN_SEEDERS
|
||||
|
||||
ts = (Path(__file__).resolve().parents[2] / "frontend" / "lib" / "audio-search-utils.ts").read_text()
|
||||
m = re.search(r"export const BEST_CHOICE_MIN_SEEDERS = (\d+)", ts)
|
||||
assert m, "BEST_CHOICE_MIN_SEEDERS not found in frontend/lib/audio-search-utils.ts"
|
||||
assert int(m.group(1)) == BEST_CHOICE_MIN_SEEDERS
|
||||
@@ -465,12 +465,14 @@ class TestFakeSearchConfidence:
|
||||
FakeConfig(search_confidence="maybe").validate()
|
||||
|
||||
def test_fake_search_confidence_shapes(self):
|
||||
from backend.services.audio_search_service import BEST_CHOICE_MIN_SEEDERS
|
||||
|
||||
perfect = self._search("perfect")
|
||||
assert perfect[0]["seeders"] >= 50 and perfect[0]["target_file"] == "01 - Song.flac"
|
||||
|
||||
recommended = self._search("recommended")
|
||||
# Lossless and the right track, but not well seeded enough for "BEST CHOICE".
|
||||
assert recommended[0]["is_lossless"] is True and 10 <= recommended[0]["seeders"] < 50
|
||||
assert recommended[0]["is_lossless"] is True and 0 < recommended[0]["seeders"] < BEST_CHOICE_MIN_SEEDERS
|
||||
assert recommended[0]["target_file"] == "01 - Song.flac"
|
||||
|
||||
unsure = self._search("unsure")
|
||||
@@ -492,3 +494,43 @@ class TestFakeSearchConfidence:
|
||||
|
||||
with open(FRONTEND_FIXTURE) as f:
|
||||
assert json.load(f) == frontend_fixture()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- kjbox quick version
|
||||
|
||||
class TestKjboxQuickVersion:
|
||||
def _run_audio(self, request_metadata):
|
||||
from backend.services.fake_workers import pipeline
|
||||
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = SimpleNamespace(
|
||||
job_id="job1", user_email="u@example.com", artist="A", title="T",
|
||||
request_metadata=request_metadata, state_data={},
|
||||
)
|
||||
jm.advance_to_screens_if_ready = AsyncMock()
|
||||
jm.resume_video_if_waiting_for_stems = AsyncMock()
|
||||
storage = MagicMock()
|
||||
media = MagicMock(final_mp4=__file__, duration=30)
|
||||
with patch.object(pipeline, "JobManager", return_value=jm), \
|
||||
patch.object(pipeline, "StorageService", return_value=storage), \
|
||||
patch.object(pipeline, "_media_for", return_value=media), \
|
||||
patch.object(pipeline, "get_fake_config", return_value=FakeConfig(step_delay_seconds=0)), \
|
||||
patch("backend.workers.audio_worker.upload_separation_results", AsyncMock()), \
|
||||
patch("backend.workers.audio_worker._transcode_review_stems", AsyncMock()), \
|
||||
patch("backend.workers.screens_worker._analyze_backing_vocals", AsyncMock()), \
|
||||
patch("backend.workers.worker_logging.create_job_logger"):
|
||||
assert asyncio.run(pipeline.run("audio", "job1")) is True
|
||||
return jm, storage
|
||||
|
||||
def test_fake_workers_emit_quick_version_for_kjbox_jobs(self):
|
||||
jm, storage = self._run_audio({"client_id": "kjbox"})
|
||||
jm.update_file_url.assert_called_once_with("job1", "quick", "video_mp4", "jobs/job1/quick/quick.mp4")
|
||||
storage.upload_file.assert_called_once()
|
||||
statuses = [c.args[2]["status"] for c in jm.update_state_data.call_args_list
|
||||
if c.args[1] == "quick_version"]
|
||||
assert statuses == ["separating", "rendering", "ready"]
|
||||
|
||||
def test_non_kjbox_jobs_get_no_quick_version(self):
|
||||
jm, storage = self._run_audio({"client_id": "web"})
|
||||
jm.update_file_url.assert_not_called()
|
||||
assert not [c for c in jm.update_state_data.call_args_list if c.args[1] == "quick_version"]
|
||||
@@ -774,3 +774,39 @@ class TestCatalogResolve:
|
||||
assert client.post("/api/kjbox/catalog/resolve", json={"query": "x"}).status_code == 403
|
||||
assert self._post(client, "").status_code == 422
|
||||
assert self._post(client, " ").status_code == 422
|
||||
|
||||
|
||||
def _local_stack_env(monkeypatch, **overrides):
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
script = Path(__file__).resolve().parents[2] / "scripts" / "local-stack.sh"
|
||||
env = {k: v for k, v in os.environ.items()
|
||||
if k not in ("KJBOX_PARTNER_SECRET", "DECIDE_GEN_PARTNER_SECRET")}
|
||||
env.update(overrides)
|
||||
out = subprocess.run([str(script), "env"], capture_output=True, text=True, check=True, env=env).stdout
|
||||
return dict(line.split("=", 1) for line in out.splitlines() if "=" in line)
|
||||
|
||||
|
||||
def test_kjbox_routes_accept_local_secret(monkeypatch):
|
||||
"""With nothing set externally, local-stack.sh defaults KJBOX_PARTNER_SECRET to
|
||||
local-stack-secret and the partner gate accepts exactly that value."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
env = _local_stack_env(monkeypatch)
|
||||
local_secret = env["KJBOX_PARTNER_SECRET"]
|
||||
assert local_secret == "local-stack-secret"
|
||||
assert env["DECIDE_GEN_PARTNER_SECRET"] == "local-stack-secret"
|
||||
|
||||
monkeypatch.setattr(kjbox, "get_settings", lambda: SimpleNamespace(kjbox_partner_secret=local_secret))
|
||||
assert kjbox.require_kjbox_partner(local_secret) == local_secret
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
kjbox.require_kjbox_partner("wrong")
|
||||
assert exc.value.status_code == 403
|
||||
|
||||
|
||||
def test_local_stack_honours_external_partner_secrets(monkeypatch):
|
||||
env = _local_stack_env(monkeypatch, KJBOX_PARTNER_SECRET="ext-kjbox", DECIDE_GEN_PARTNER_SECRET="ext-decide")
|
||||
assert env["KJBOX_PARTNER_SECRET"] == "ext-kjbox"
|
||||
assert env["DECIDE_GEN_PARTNER_SECRET"] == "ext-decide"
|
||||
@@ -261,6 +261,7 @@ class FakeYouTube:
|
||||
self.pages = pages
|
||||
self.reply_pages = reply_pages or []
|
||||
self.inserted = []
|
||||
self.retries = []
|
||||
|
||||
def commentThreads(self):
|
||||
return self
|
||||
@@ -277,7 +278,8 @@ class FakeYouTube:
|
||||
self._kw = {"insert": True}
|
||||
return self
|
||||
|
||||
def execute(self):
|
||||
def execute(self, num_retries=0):
|
||||
self.retries.append((("insert" if self._kw.get("insert") else "list"), num_retries))
|
||||
if self._kw.get("insert"):
|
||||
return {"id": "reply1"}
|
||||
if "parentId" in self._kw:
|
||||
@@ -305,3 +307,11 @@ class TestApiHelpers:
|
||||
yt = FakeYouTube([])
|
||||
assert bot.post_reply(yt, "c1", "hi") == "reply1"
|
||||
assert yt.inserted[0]["body"]["snippet"] == {"parentId": "c1", "textOriginal": "hi"}
|
||||
|
||||
|
||||
def test_reads_retry_but_posts_never_do(self):
|
||||
yt = FakeYouTube([{"items": [_item()]}], reply_pages=[{"items": []}])
|
||||
list(bot.iter_comment_threads(yt))
|
||||
bot.load_thread(yt, _item(replies=[("UCa", "x")], total_replies=7))
|
||||
bot.post_reply(yt, "c1", "hi")
|
||||
assert yt.retries == [("list", bot.READ_RETRIES), ("list", bot.READ_RETRIES), ("insert", 0)]
|
||||
@@ -71,7 +71,7 @@ class FakeYouTube:
|
||||
self._kw = {"insert": True}
|
||||
return self
|
||||
|
||||
def execute(self):
|
||||
def execute(self, num_retries=0):
|
||||
if self._kw.get("insert"):
|
||||
return {"id": f"reply{len(self.inserted)}"}
|
||||
return {"items": self.items}
|
||||
@@ -236,3 +236,28 @@ def test_post_noise_disables_discord_mentions(monkeypatch):
|
||||
monkeypatch.setattr(w.requests, "post", lambda url, json, timeout: sent.append(json) or SimpleNamespace(ok=True))
|
||||
w._post_noise(SimpleNamespace(get_secret=lambda name: "https://discord.test/hook"), "@everyone hi")
|
||||
assert sent[0]["allowed_mentions"] == {"parse": []}
|
||||
|
||||
|
||||
def test_failed_later_page_still_processes_fetched_threads(env, monkeypatch):
|
||||
def pages(youtube, stop_before=None):
|
||||
yield _item("c1")
|
||||
raise BrokenPipeError(32, "Broken pipe")
|
||||
monkeypatch.setattr(w.bot, "iter_comment_threads", pages)
|
||||
summary = w.run_comment_bot_sync()
|
||||
assert summary["replied"] == 1
|
||||
assert env.db.store[(w.STATE_COLLECTION, w.STATE_DOC)]["incomplete"] is True
|
||||
w._alert.assert_called_once()
|
||||
|
||||
|
||||
def test_poster_build_failure_leaves_comment_unclaimed(env, monkeypatch):
|
||||
calls = {"n": 0}
|
||||
yt = env.yt
|
||||
|
||||
def build(creds):
|
||||
calls["n"] += 1
|
||||
if calls["n"] > 1: # first call is the reading client
|
||||
raise RuntimeError("token refresh failed")
|
||||
return yt
|
||||
monkeypatch.setattr(w.ytb, "build_youtube", build)
|
||||
summary = w.run_comment_bot_sync()
|
||||
assert summary["errors"] == 1 and "c1" not in _actions(env.db) and yt.inserted == []
|
||||
@@ -174,14 +174,28 @@ def run_comment_bot_sync(dry_run: bool = False, max_replies: Optional[int] = Non
|
||||
generate = bot.gemini_generate()
|
||||
quota = get_youtube_quota_service()
|
||||
|
||||
# A run that stops early (reply cap, quota, a transient classifier error, a failed
|
||||
# page fetch) must not advance the high-water mark, or older unprocessed threads
|
||||
# would fall out of the next run's window. Re-reading is cheap: handled comments
|
||||
# have an action doc.
|
||||
incomplete = False
|
||||
summary = {"status": "ok", "dry_run": dry_run, "threads": 0, "replied": 0, "skipped": {},
|
||||
"errors": 0, "actions": []}
|
||||
newest = high_water
|
||||
# A run that stops early (reply cap, quota, a transient classifier error) must not
|
||||
# advance the high-water mark, or older unprocessed threads would fall out of the
|
||||
# next run's window. Re-reading is cheap: handled comments have an action doc.
|
||||
incomplete = False
|
||||
for item in bot.iter_comment_threads(youtube, stop_before=stop_before):
|
||||
# Fetch every page up front (a few quick reads) rather than lazily between slow
|
||||
# per-thread work, which idles the connection until Google drops it. If a page
|
||||
# still fails after retries, process what we have and retry the rest next run.
|
||||
items = []
|
||||
try:
|
||||
for item in bot.iter_comment_threads(youtube, stop_before=stop_before):
|
||||
items.append(item)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
incomplete = True
|
||||
logger.warning("YOUTUBE_COMMENT_BOT: comment fetch failed after %d threads: %s", len(items), exc)
|
||||
_alert("fetch", f"YouTube comment bot: reading channel comments failed after {len(items)} threads "
|
||||
f"({exc}). {'Processing those; older' if items else 'No replies this run;'} "
|
||||
"comments are retried next run (high-water not advanced).")
|
||||
for item in items:
|
||||
thread = bot.load_thread(youtube, item)
|
||||
summary["threads"] += 1
|
||||
if thread.published and thread.published > newest:
|
||||
@@ -219,11 +233,21 @@ def run_comment_bot_sync(dry_run: bool = False, max_replies: Optional[int] = Non
|
||||
logger.warning("YOUTUBE_COMMENT_BOT: quota low (%s left); stopping", remaining)
|
||||
incomplete = True
|
||||
break
|
||||
# Fresh client per post: the shared connection may have idled out, and a post
|
||||
# must never be retried (double-reply risk). Built before claiming, so a
|
||||
# failure here leaves the comment unclaimed for the next run.
|
||||
try:
|
||||
poster = ytb.build_youtube(creds)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
incomplete = True
|
||||
summary["errors"] += 1
|
||||
logger.warning("YOUTUBE_COMMENT_BOT: couldn't build posting client: %s", exc)
|
||||
break
|
||||
# Claim the comment BEFORE posting so a concurrent run can't double-reply.
|
||||
if not _create(action_ref, {**record, "action": "replying"}):
|
||||
continue
|
||||
try:
|
||||
reply_id = bot.post_reply(youtube, thread.comment_id, decision.reply_text)
|
||||
reply_id = bot.post_reply(poster, thread.comment_id, decision.reply_text)
|
||||
quota.record_upload(f"comment-reply:{thread.comment_id}", units=REPLY_COST)
|
||||
action_ref.update({"action": "replied", "reply_id": reply_id, "replied_at": datetime.now(timezone.utc)})
|
||||
summary["replied"] += 1
|
||||
|
||||
+10
-1
@@ -527,7 +527,16 @@ and `docs/archive/2026-07-20-edge-security-*.md`.
|
||||
(`getSearchConfidence`) and `backend/services/audio_search_service.py`
|
||||
(`pick_auto_selection`). The backend port drives the `bulk_search_worker`
|
||||
auto-select decision. If you change the rule, change BOTH — the parity is guarded
|
||||
by `backend/tests/test_bulk_foundations.py`.
|
||||
by `backend/tests/test_bulk_foundations.py`. The seeder bar for BEST CHOICE is the
|
||||
`BEST_CHOICE_MIN_SEEDERS` constant on both sides (10 since Oct 2026; it was 50, which
|
||||
parked well-matched lossless album torrents with 15-31 seeders for manual choice). A
|
||||
test asserts the two values match. The bar also applies to unattended KaraokeHunt
|
||||
conversions (`karaokehunt_conversion.py` calls `pick_auto_selection`), where the
|
||||
title/filename check is the guard against wrong picks.
|
||||
- **Album cover thumbnails** in the By-album picker load straight from the Cover Art
|
||||
Archive in the browser (`coverartarchive.org/release-group/{mbid}/front-250`), with the
|
||||
disc icon as fallback when there's no cover. This isn't the live MusicBrainz API, and no
|
||||
request goes through our backend.
|
||||
- **The duration-delta charge is replicated** in `bulk_search_worker._auto_select`
|
||||
using the same primitives/state keys (`credits_charged`/`select_charge_applied`)
|
||||
as `audio_search.select_audio_source`, rather than refactoring the proven money
|
||||
|
||||
@@ -171,6 +171,10 @@ anonymous YouTuber to sign in with an email; follow-up emails do the gen convers
|
||||
- `..._MAX_REPLIES` (20 per run) and `..._MIN_CONFIDENCE` (0.8).
|
||||
- Notifications: each reply posts a one-liner to Discord **#noise**. Missing credentials,
|
||||
missing scope, YouTube errors and failed replies go to **#alerts**, throttled to 6h.
|
||||
- Long runs: all comment pages are fetched up front and reads retry (`num_retries`).
|
||||
Each post uses a freshly built client and is never retried. Without this, the slow
|
||||
Gemini work between calls (background tasks are CPU-throttled) idled the shared
|
||||
connection until Google dropped it (`BrokenPipeError`, first prod run 2026-10-22).
|
||||
- Quota: `commentThreads.list` costs 1 unit per page and each reply costs 50, recorded through
|
||||
`YouTubeQuotaService` as `comment-reply:<comment_id>`.
|
||||
|
||||
|
||||
@@ -334,6 +334,14 @@ settings object in a unit test never turns it on.
|
||||
| Postmark | console provider + captured outbox | `ConsoleEmailProvider` |
|
||||
| Secret Manager, DeBounce, encoding VM | skipped | `get_secret`, `is_disposable_domain`, warmup |
|
||||
|
||||
**kjbox partner calls.** The stack exports `KJBOX_PARTNER_SECRET=local-stack-secret`
|
||||
(and `DECIDE_GEN_PARTNER_SECRET`, same value) so a local kjbox stack can call
|
||||
`/api/kjbox/*` with `X-Kjbox-Secret: local-stack-secret`. For jobs created with
|
||||
`X-Client-Id: kjbox…` the fake audio worker also writes the real "quick version"
|
||||
outputs (`state_data.quick_version` separating -> rendering -> ready, and
|
||||
`file_urls.quick.video_mp4` from the fixture mp4), so `/api/jobs/{id}/download-urls`
|
||||
lists `quick/video_mp4` and `/download/quick/video_mp4` streams it, like prod.
|
||||
|
||||
The audio worker reuses the real stem upload, OGG transcode and backing-vocals
|
||||
analysis. The review preview video is the real local ffmpeg render. Startup
|
||||
**refuses** `FAKE_WORKERS` in production (`validate_production_config`).
|
||||
|
||||
@@ -151,3 +151,43 @@ describe('BulkMode (album sub-mode)', () => {
|
||||
expect(screen.getByRole('button', { name: 'Create 2 karaoke videos' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BulkAlbumMode cover art', () => {
|
||||
async function walkToAlbums() {
|
||||
fireEvent.change(screen.getByPlaceholderText('Search for an artist…'), { target: { value: 'Britney' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Search$/ }))
|
||||
fireEvent.click(await screen.findByRole('button', { name: /Britney Spears/ }))
|
||||
await screen.findByText('Choose an album')
|
||||
}
|
||||
|
||||
const coverImg = (container: HTMLElement) =>
|
||||
container.querySelector('img[src^="https://coverartarchive.org/"]') as HTMLImageElement | null
|
||||
|
||||
it('requests the release-group front cover for each album row, hidden until loaded', async () => {
|
||||
const { container } = render(<Harness />)
|
||||
await walkToAlbums()
|
||||
const img = coverImg(container)!
|
||||
expect(img.getAttribute('src')).toBe('https://coverartarchive.org/release-group/rg-1/front-250')
|
||||
expect(img).toHaveAttribute('loading', 'lazy')
|
||||
expect(img.className).toContain('invisible')
|
||||
fireEvent.load(img)
|
||||
expect(img.className).not.toContain('invisible')
|
||||
})
|
||||
|
||||
it('falls back to the disc icon when the album has no cover art', async () => {
|
||||
const { container } = render(<Harness />)
|
||||
await walkToAlbums()
|
||||
fireEvent.error(coverImg(container)!)
|
||||
expect(coverImg(container)).toBeNull()
|
||||
// The album row is still there and clickable.
|
||||
expect(screen.getByRole('button', { name: /Oops!\.\.\.I Did It Again/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('shows the picked album cover on the tracklist step', async () => {
|
||||
const { container } = render(<Harness />)
|
||||
await walkToTracklist()
|
||||
expect(coverImg(container)?.getAttribute('src')).toBe(
|
||||
'https://coverartarchive.org/release-group/rg-1/front-250',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -127,9 +127,45 @@ function StepHeading({ icon: Icon, title, subtitle }: { icon: LucideIcon; title:
|
||||
)
|
||||
}
|
||||
|
||||
/** Cover Art Archive front-cover thumbnail for a release group (free, keyed by MBID). */
|
||||
export function coverArtUrl(releaseGroupMbid: string, size: 250 | 500 = 250): string {
|
||||
return `https://coverartarchive.org/release-group/${encodeURIComponent(releaseGroupMbid)}/front-${size}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Album cover with the icon tile as placeholder: the image is only revealed once
|
||||
* it loads, and albums with no cover in the archive (404) keep the icon.
|
||||
*/
|
||||
function AlbumArt({ mbid, icon: Icon, className }: { mbid?: string | null; icon: LucideIcon; className: string }) {
|
||||
const [state, setState] = useState<"loading" | "loaded" | "failed">("loading")
|
||||
return (
|
||||
<span
|
||||
className={`${className} relative rounded-md overflow-hidden flex items-center justify-center shrink-0`}
|
||||
style={{ backgroundColor: "rgba(255,255,255,0.06)", color: "var(--text-muted)" }}
|
||||
>
|
||||
{state !== "loaded" && <Icon className="w-4 h-4" />}
|
||||
{mbid && state !== "failed" && (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={coverArtUrl(mbid)}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
referrerPolicy="no-referrer"
|
||||
onLoad={() => setState("loaded")}
|
||||
onError={() => setState("failed")}
|
||||
className={`absolute inset-0 w-full h-full object-cover ${state === "loaded" ? "" : "invisible"}`}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** A bordered, obviously-clickable result row (artist or album) with a trailing chevron. */
|
||||
function PickRow({ icon: Icon, title, subtitle, meta, onClick, disabled }: {
|
||||
function PickRow({ icon: Icon, artMbid, title, subtitle, meta, onClick, disabled }: {
|
||||
icon: LucideIcon
|
||||
/** Release-group MBID → show its cover art in place of the icon (album rows). */
|
||||
artMbid?: string
|
||||
title: string
|
||||
subtitle?: string
|
||||
meta?: ReactNode
|
||||
@@ -144,12 +180,16 @@ function PickRow({ icon: Icon, title, subtitle, meta, onClick, disabled }: {
|
||||
className="w-full text-start rounded-md border px-2.5 py-2 flex items-center gap-3 transition-colors hover:bg-white/5 hover:border-pink-400/50 disabled:opacity-50 disabled:pointer-events-none"
|
||||
style={{ borderColor: "var(--card-border)" }}
|
||||
>
|
||||
<span
|
||||
className="w-8 h-8 rounded-md flex items-center justify-center shrink-0"
|
||||
style={{ backgroundColor: "rgba(255,255,255,0.06)", color: "var(--text-muted)" }}
|
||||
>
|
||||
<Icon className="w-4 h-4" />
|
||||
</span>
|
||||
{artMbid ? (
|
||||
<AlbumArt mbid={artMbid} icon={Icon} className="w-10 h-10" />
|
||||
) : (
|
||||
<span
|
||||
className="w-8 h-8 rounded-md flex items-center justify-center shrink-0"
|
||||
style={{ backgroundColor: "rgba(255,255,255,0.06)", color: "var(--text-muted)" }}
|
||||
>
|
||||
<Icon className="w-4 h-4" />
|
||||
</span>
|
||||
)}
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block text-sm truncate" style={{ color: "var(--text)" }}>{title}</span>
|
||||
{subtitle && <span className="block text-xs truncate" style={{ color: "var(--text-muted)" }}>{subtitle}</span>}
|
||||
@@ -307,7 +347,10 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{stepper}
|
||||
<StepHeading icon={ListMusic} title={t("chooseTracks")} subtitle={`${artist.name} — ${tracklist.title}`} />
|
||||
<div className="flex items-center gap-3">
|
||||
{albumMbid && <AlbumArt key={albumMbid} mbid={albumMbid} icon={Disc3} className="w-12 h-12" />}
|
||||
<StepHeading icon={ListMusic} title={t("chooseTracks")} subtitle={`${artist.name} — ${tracklist.title}`} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -417,6 +460,7 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
|
||||
<PickRow
|
||||
key={a.release_group_mbid}
|
||||
icon={Disc3}
|
||||
artMbid={a.release_group_mbid}
|
||||
onClick={() => pickAlbum(a)}
|
||||
disabled={disabled}
|
||||
title={a.title}
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
import { test as base, expect, chromium, type Page, type BrowserContext } from '@playwright/test';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { BEST_CHOICE_MIN_SEEDERS } from '../../lib/audio-search-utils';
|
||||
|
||||
// --- Persistent Chrome profile (bookmarks bar enabled) ---
|
||||
|
||||
@@ -100,14 +101,14 @@ function computeTier(fixture: Fixture): 1 | 2 | 3 {
|
||||
for (const r of fixture.results) {
|
||||
if (r.is_lossless && r.quality_data?.media?.toLowerCase() === 'vinyl') continue;
|
||||
if (!best) { best = r; continue; }
|
||||
const isBestChoice = r.is_lossless && (r.seeders ?? 0) >= 50 && r.quality_data?.media?.toLowerCase() !== 'vinyl';
|
||||
const currentIsBest = best.is_lossless && (best.seeders ?? 0) >= 50 && best.quality_data?.media?.toLowerCase() !== 'vinyl';
|
||||
const isBestChoice = r.is_lossless && (r.seeders ?? 0) >= BEST_CHOICE_MIN_SEEDERS && r.quality_data?.media?.toLowerCase() !== 'vinyl';
|
||||
const currentIsBest = best.is_lossless && (best.seeders ?? 0) >= BEST_CHOICE_MIN_SEEDERS && best.quality_data?.media?.toLowerCase() !== 'vinyl';
|
||||
if (isBestChoice && !currentIsBest) best = r;
|
||||
else if (isBestChoice && currentIsBest && (r.seeders ?? 0) > (best.seeders ?? 0)) best = r;
|
||||
}
|
||||
if (!best) best = fixture.results[0];
|
||||
|
||||
const isBestChoice = best.is_lossless && (best.seeders ?? 0) >= 50 && best.quality_data?.media?.toLowerCase() !== 'vinyl';
|
||||
const isBestChoice = best.is_lossless && (best.seeders ?? 0) >= BEST_CHOICE_MIN_SEEDERS && best.quality_data?.media?.toLowerCase() !== 'vinyl';
|
||||
const hasLossless = fixture.results.some(
|
||||
(r: any) => r.is_lossless && r.provider?.toLowerCase() !== 'youtube' && r.quality_data?.media?.toLowerCase() !== 'vinyl'
|
||||
);
|
||||
|
||||
@@ -36,7 +36,12 @@ describe('categorizeResult', () => {
|
||||
expect(categorizeResult(result)).toBe('YOUTUBE')
|
||||
})
|
||||
|
||||
it('categorizes lossless with 50+ seeders as BEST CHOICE', () => {
|
||||
it('categorizes lossless with 10 seeders as BEST CHOICE', () => {
|
||||
expect(categorizeResult(makeResult({ is_lossless: true, seeders: 10, release_type: 'Album' }))).toBe('BEST CHOICE')
|
||||
expect(categorizeResult(makeResult({ is_lossless: true, seeders: 9, release_type: 'Album' }))).toBe('STUDIO ALBUMS')
|
||||
})
|
||||
|
||||
it('categorizes well-seeded lossless (100) as BEST CHOICE', () => {
|
||||
const result = makeResult({ index: 0, is_lossless: true, seeders: 55 })
|
||||
expect(categorizeResult(result)).toBe('BEST CHOICE')
|
||||
})
|
||||
@@ -164,7 +169,7 @@ describe('groupResults', () => {
|
||||
it('groups results by category', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 100 }), // BEST CHOICE
|
||||
makeResult({ index: 1, is_lossless: true, seeders: 10, release_type: 'Album' }), // STUDIO ALBUMS
|
||||
makeResult({ index: 1, is_lossless: true, seeders: 5, release_type: 'Album' }), // STUDIO ALBUMS
|
||||
makeResult({ index: 2, is_lossless: true, seeders: 60 }), // BEST CHOICE
|
||||
]
|
||||
const groups = groupResults(results)
|
||||
@@ -446,9 +451,9 @@ describe('getSearchConfidence', () => {
|
||||
expect(confidence.warnings.some(w => w.includes('Spies'))).toBe(true)
|
||||
})
|
||||
|
||||
it('returns tier 2 for studio album with moderate seeders', () => {
|
||||
it('returns tier 2 for studio album with few seeders', () => {
|
||||
const results = [
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 20, release_type: 'Album', target_file: '01 - Yellow.flac' }),
|
||||
makeResult({ index: 0, is_lossless: true, seeders: 9, release_type: 'Album', target_file: '01 - Yellow.flac' }),
|
||||
]
|
||||
const confidence = getSearchConfidence(results, 'Yellow')
|
||||
expect(confidence.tier).toBe(2)
|
||||
|
||||
@@ -68,7 +68,7 @@
|
||||
"quality": "FLAC 16bit CD",
|
||||
"source_id": "30871261464f73cc",
|
||||
"index": 0,
|
||||
"seeders": 20,
|
||||
"seeders": 5,
|
||||
"target_file": "01 - Fake Song.flac",
|
||||
"year": 2001,
|
||||
"label": "Fake Records",
|
||||
|
||||
@@ -27,6 +27,12 @@ export interface CategoryConfig {
|
||||
borderColor: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Seeders a lossless torrent needs to count as BEST CHOICE (and tier 1 / auto-pick).
|
||||
* Keep in sync with BEST_CHOICE_MIN_SEEDERS in backend/services/audio_search_service.py.
|
||||
*/
|
||||
export const BEST_CHOICE_MIN_SEEDERS = 10
|
||||
|
||||
export const CATEGORY_CONFIG: Record<string, CategoryConfig> = {
|
||||
'BEST CHOICE': { name: 'BEST CHOICE', maxDisplay: 3, color: 'text-amber-400', borderColor: 'border-amber-500/30' },
|
||||
'HI-RES 24-BIT': { name: 'HI-RES 24-BIT', maxDisplay: 3, color: 'text-purple-400', borderColor: 'border-purple-500/30' },
|
||||
@@ -78,8 +84,8 @@ export function categorizeResult(result: ExtendedAudioSearchResult): string {
|
||||
return 'VINYL RIPS'
|
||||
}
|
||||
|
||||
// Best choice (50+ seeders, lossless, non-vinyl)
|
||||
if (isLossless && seeders >= 50) {
|
||||
// Best choice (lossless, non-vinyl, enough seeders to download reliably)
|
||||
if (isLossless && seeders >= BEST_CHOICE_MIN_SEEDERS) {
|
||||
return 'BEST CHOICE'
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ only app-specific stacks (e.g. karaoke-decide's Cloud Run + its API-proxy Worker
|
||||
| `email_routing.py` | Gmail destination address; Email Routing enablement (**protected**), catch-all and `google@` rules for nomadkaraoke.com, nomadkaroke.com, karaokehunt.com |
|
||||
| `tunnels.py` | `nomad-kjbox` (NomadPC: sing, kjbox, kjssh, kjvnc) and `nomad-hf2` (fiverrbot) tunnels (**protected**) + ingress |
|
||||
| `access.py` | Zero Trust org (**protected**), one-time-PIN + Google IdPs (Google OAuth client in GCP `nomadkaraoke`, secret in Pulumi config `googleOauthClientSecret`), `claude-code-kjbox` service token, reusable policies and the KJ Controller / FiverrBot noVNC apps |
|
||||
| `pages_workers.py` | Pages projects `karaoke-gen` + `karaoke-gen-tenant`, `gen.nomadkaraoke.com` Pages domain, nomadkaraoke.com/www Worker custom domains, `create.karaokehunt.com/*` and `requests.nomadkaraoke.com/*` routes |
|
||||
| `pages_workers.py` | Pages projects `karaoke-gen` + `karaoke-gen-tenant`, `gen.nomadkaraoke.com` Pages domain, nomadkaraoke.com/www Worker custom domains, `create.karaokehunt.com/*` and `requests.nomadkaraoke.com/*` routes, plus the `kjbox-cc-well-known` Worker script (`kjbox-cc-well-known/worker.js`, built by `well_known.py`) and its `kjbox.cc/.well-known/*` route |
|
||||
|
||||
All resource IDs (`ids.py`) are non-secret. Removing a non-protected resource from code deletes it
|
||||
on the next `pulumi up`, and `pulumi preview` always shows that first.
|
||||
@@ -36,6 +36,19 @@ on the next `pulumi up`, and `pulumi preview` always shows that first.
|
||||
| Tunnel connector tokens / cloudflared processes | NomadPC systemd `cloudflared-nomad`, hf2 `~/nomad-tunnel` compose |
|
||||
| Registrar, billing, API tokens, account members | Dashboard (admin@nomadkaraoke.com) |
|
||||
|
||||
## kjbox.cc app-link files
|
||||
|
||||
`kjbox.cc/.well-known/assetlinks.json` (Android App Links) and `apple-app-site-association` (iOS universal
|
||||
links) are served by the `kjbox-cc-well-known` Worker, routes `kjbox.cc/.well-known/*` and `www.kjbox.cc/.well-known/*` (scheme-agnostic, so
|
||||
http and https). The JSON mirrors what the kjbox box serves on `sing.nomadkaraoke.com`. The
|
||||
`kjbox.cc/<code>` redirect rule excludes `/.well-known/` so the Worker answers instead of redirecting.
|
||||
Android SHA-256 cert fingerprints come from Pulumi config, baked into the script at deploy time
|
||||
(empty list = `assetlinks.json` is `[]`):
|
||||
|
||||
```bash
|
||||
pulumi config set --path 'kjboxcc_android_sha256_fingerprints[0]' 'AA:BB:...' # then pulumi up
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
@@ -47,7 +60,7 @@ pulumi preview # must be clean (0 changes) before you start
|
||||
pulumi up
|
||||
```
|
||||
|
||||
Unit tests for the import-list builder: `venv/bin/pip install pytest && venv/bin/python -m pytest tests -c /dev/null`
|
||||
Unit tests (import-list builder, kjbox.cc well-known Worker; the Worker tests need `node`): `venv/bin/pip install pytest && venv/bin/python -m pytest tests -c /dev/null`
|
||||
(`-c /dev/null` skips the repo-root pytest config, which needs the backend's plugins).
|
||||
|
||||
As with the GCP project, **CI does not run Pulumi**. Apply locally, then merge the PR.
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// kjbox.cc/.well-known/* : app-link association files for the Nomad Karaoke app.
|
||||
// Must match what the kjbox box serves on sing.nomadkaraoke.com/.well-known/.
|
||||
// The fingerprint list is substituted at deploy time by ../well_known.py from Pulumi config
|
||||
// `kjboxcc_android_sha256_fingerprints`.
|
||||
const ANDROID_SHA256_FINGERPRINTS = /*FINGERPRINTS*/[]/*END*/;
|
||||
|
||||
const ASSETLINKS = ANDROID_SHA256_FINGERPRINTS.length === 0 ? [] : [{
|
||||
relation: ["delegate_permission/common.handle_all_urls"],
|
||||
target: {
|
||||
namespace: "android_app",
|
||||
package_name: "com.nomadkaraoke.mobile",
|
||||
sha256_cert_fingerprints: ANDROID_SHA256_FINGERPRINTS,
|
||||
},
|
||||
}];
|
||||
|
||||
const AASA = {
|
||||
applinks: {
|
||||
details: [{
|
||||
appIDs: ["55B76HN73D.com.nomadkaraoke.mobile"],
|
||||
components: [{ "/": "/", "?": { t: "?*" } }, { "/": "/*" }],
|
||||
}],
|
||||
},
|
||||
};
|
||||
|
||||
const FILES = {
|
||||
"/.well-known/assetlinks.json": ASSETLINKS,
|
||||
"/.well-known/apple-app-site-association": AASA,
|
||||
};
|
||||
|
||||
export default {
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url);
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
return new Response("Method Not Allowed", { status: 405, headers: { Allow: "GET, HEAD" } });
|
||||
}
|
||||
const body = FILES[url.pathname];
|
||||
if (body === undefined) return new Response("Not Found", { status: 404 });
|
||||
return new Response(request.method === "HEAD" ? null : JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json", "Cache-Control": "public, max-age=300" },
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -7,6 +7,7 @@ import pulumi
|
||||
import pulumi_cloudflare as cloudflare
|
||||
|
||||
from ids import ACCOUNT_ID, ZONE_IDS
|
||||
from well_known import ROUTE_PATTERNS, build_worker_script
|
||||
|
||||
worker_route_create_karaokehunt_com = cloudflare.WorkersRoute("worker-route-create-karaokehunt-com",
|
||||
pattern="create.karaokehunt.com/*",
|
||||
@@ -75,3 +76,20 @@ worker_domain_www_nomadkaraoke_com = cloudflare.WorkersCustomDomain("worker-doma
|
||||
service="nomadkaraoke-com-static",
|
||||
zone_id=ZONE_IDS["nomadkaraoke.com"],
|
||||
zone_name="nomadkaraoke.com")
|
||||
|
||||
# kjbox.cc/.well-known/*: Android App Links (assetlinks.json) + iOS universal links (AASA) for the
|
||||
# Nomad Karaoke app, so the venue QR (kjbox.cc/<code>) can open the app. The script is deployed by
|
||||
# Pulumi (fingerprints come from config `kjboxcc_android_sha256_fingerprints`, empty by default);
|
||||
# the kjbox.cc/<code> redirect rule in rulesets.py excludes /.well-known/ so this route answers.
|
||||
_kjbox_fingerprints = pulumi.Config().get_object("kjboxcc_android_sha256_fingerprints") or []
|
||||
worker_script_kjbox_cc_well_known = cloudflare.WorkersScript("worker-script-kjbox-cc-well-known",
|
||||
account_id=ACCOUNT_ID,
|
||||
script_name="kjbox-cc-well-known",
|
||||
content=build_worker_script(_kjbox_fingerprints),
|
||||
main_module="worker.js",
|
||||
compatibility_date="2026-09-01")
|
||||
for _name, _pattern in ROUTE_PATTERNS.items():
|
||||
cloudflare.WorkersRoute(f"worker-route-{_name}-well-known",
|
||||
pattern=_pattern,
|
||||
script=worker_script_kjbox_cc_well_known.script_name,
|
||||
zone_id=ZONE_IDS["kjbox.cc"])
|
||||
@@ -11,6 +11,7 @@ import pulumi
|
||||
import pulumi_cloudflare as cloudflare
|
||||
|
||||
from ids import ACCOUNT_ID, ZONE_IDS
|
||||
from well_known import WELL_KNOWN_EXCLUSION
|
||||
|
||||
ruleset_karaokehunt_com_request_dynamic_redirect = cloudflare.Ruleset("ruleset-karaokehunt-com-request-dynamic-redirect",
|
||||
kind="zone",
|
||||
@@ -95,7 +96,7 @@ ruleset_kjbox_cc_request_dynamic_redirect = cloudflare.Ruleset("ruleset-kjbox-cc
|
||||
},
|
||||
"description": "kjbox.cc/<code> -> sing.nomadkaraoke.com/?t=<code>",
|
||||
"enabled": True,
|
||||
"expression": "(http.host in {\"kjbox.cc\" \"www.kjbox.cc\"} and http.request.uri.path ne \"/\")",
|
||||
"expression": "(http.host in {\"kjbox.cc\" \"www.kjbox.cc\"} and http.request.uri.path ne \"/\"" + WELL_KNOWN_EXCLUSION + ")",
|
||||
"ref": "1f2e8fb05f844449ae29e7c1237ffc5c",
|
||||
},
|
||||
],
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""kjbox.cc/.well-known/*: the Worker serves the app-link files and the redirect rule excludes the path."""
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
import well_known
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
FP = "AA:BB:CC:DD"
|
||||
|
||||
|
||||
def test_redirect_rule_excludes_well_known_and_is_otherwise_unchanged():
|
||||
src = (ROOT / "rulesets.py").read_text()
|
||||
assert "WELL_KNOWN_EXCLUSION" in src
|
||||
assert 'starts_with(http.request.uri.path, "/.well-known/")' in well_known.WELL_KNOWN_EXCLUSION
|
||||
# The code-entry rule (path eq "/") is untouched.
|
||||
assert '"(http.host in {\\"kjbox.cc\\" \\"www.kjbox.cc\\"} and http.request.uri.path eq \\"/\\")"' in src
|
||||
assert 'http.request.uri.path ne \\"/\\"" + WELL_KNOWN_EXCLUSION + ")"' in src
|
||||
|
||||
|
||||
def test_build_worker_script_bakes_fingerprints():
|
||||
assert "ANDROID_SHA256_FINGERPRINTS = []" in well_known.build_worker_script([])
|
||||
assert f'ANDROID_SHA256_FINGERPRINTS = ["{FP}"]' in well_known.build_worker_script([FP])
|
||||
|
||||
|
||||
def _run_worker(fps, path, method="GET"):
|
||||
script = well_known.build_worker_script(fps)
|
||||
js = script.replace("export default", "const worker =") + f"""
|
||||
worker.fetch(new Request("https://kjbox.cc{path}", {{method: "{method}"}})).then(async r =>
|
||||
console.log(JSON.stringify({{status: r.status, ct: r.headers.get("content-type"), body: await r.text()}})));
|
||||
"""
|
||||
out = subprocess.run(["node", "-e", js], capture_output=True, text=True, check=True).stdout
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
@pytest.mark.skipif(shutil.which("node") is None, reason="node not installed")
|
||||
class TestWorker:
|
||||
def test_assetlinks_with_fingerprint(self):
|
||||
r = _run_worker([FP], "/.well-known/assetlinks.json")
|
||||
assert r["status"] == 200 and r["ct"] == "application/json"
|
||||
assert json.loads(r["body"]) == [{
|
||||
"relation": ["delegate_permission/common.handle_all_urls"],
|
||||
"target": {"namespace": "android_app", "package_name": "com.nomadkaraoke.mobile",
|
||||
"sha256_cert_fingerprints": [FP]}}]
|
||||
|
||||
def test_assetlinks_empty_when_no_fingerprints(self):
|
||||
assert json.loads(_run_worker([], "/.well-known/assetlinks.json")["body"]) == []
|
||||
|
||||
def test_aasa(self):
|
||||
r = _run_worker([], "/.well-known/apple-app-site-association")
|
||||
assert r["status"] == 200 and r["ct"] == "application/json"
|
||||
assert json.loads(r["body"]) == {"applinks": {"details": [{
|
||||
"appIDs": ["55B76HN73D.com.nomadkaraoke.mobile"],
|
||||
"components": [{"/": "/", "?": {"t": "?*"}}, {"/": "/*"}]}]}}
|
||||
|
||||
def test_unknown_path_404_and_post_405(self):
|
||||
assert _run_worker([], "/.well-known/other")["status"] == 404
|
||||
assert _run_worker([], "/.well-known/assetlinks.json", "POST")["status"] == 405
|
||||
|
||||
|
||||
def test_routes_cover_apex_and_www():
|
||||
# The redirect exclusion matches both hosts, so both need the Worker route.
|
||||
assert sorted(well_known.ROUTE_PATTERNS.values()) == ["kjbox.cc/.well-known/*", "www.kjbox.cc/.well-known/*"]
|
||||
src = (ROOT / "pages_workers.py").read_text()
|
||||
assert "for _name, _pattern in ROUTE_PATTERNS.items()" in src
|
||||
@@ -0,0 +1,16 @@
|
||||
"""kjbox.cc/.well-known/* Worker: script builder + the redirect-rule exclusion (no pulumi imports, unit-testable)."""
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
WORKER_JS = pathlib.Path(__file__).parent / "kjbox-cc-well-known" / "worker.js"
|
||||
PLACEHOLDER = "/*FINGERPRINTS*/[]/*END*/"
|
||||
ROUTE_PATTERNS = {"kjbox-cc": "kjbox.cc/.well-known/*", "www-kjbox-cc": "www.kjbox.cc/.well-known/*"}
|
||||
|
||||
# Appended to the kjbox.cc/<code> redirect rule so the Worker route (not the redirect) answers.
|
||||
WELL_KNOWN_EXCLUSION = ' and not starts_with(http.request.uri.path, "/.well-known/")'
|
||||
|
||||
|
||||
def build_worker_script(fingerprints):
|
||||
src = WORKER_JS.read_text()
|
||||
assert src.count(PLACEHOLDER) == 1, "worker.js placeholder missing"
|
||||
return src.replace(PLACEHOLDER, json.dumps(list(fingerprints)))
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.280.0"
|
||||
version = "0.281.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -49,6 +49,8 @@ REVIEW_AUDIO_PROXY=1
|
||||
MAX_SIGNUPS_PER_IP=100000
|
||||
BOARD_MAX_SIGNUPS_PER_IP=100000
|
||||
LOGIN_CODES_PER_IP_PER_HOUR=100000
|
||||
KJBOX_PARTNER_SECRET=${KJBOX_PARTNER_SECRET:-local-stack-secret}
|
||||
DECIDE_GEN_PARTNER_SECRET=${DECIDE_GEN_PARTNER_SECRET:-local-stack-secret}
|
||||
POSTMARK_SERVER_TOKEN=
|
||||
STRIPE_SECRET_KEY=
|
||||
EOF
|
||||
|
||||
Reference in new issue
Block a user