mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-06 01:47:39 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac12f2cb19 | ||
|
|
ca9f3bd5ba | ||
|
|
f017ba7d77 |
No files matched your search
@@ -56,6 +56,52 @@ def _is_youtube_url(url: str) -> bool:
|
||||
router = APIRouter(tags=["jobs"])
|
||||
|
||||
|
||||
def _apply_tenant_overrides(
|
||||
dist: EffectiveDistributionSettings,
|
||||
tenant_config,
|
||||
effective_theme_id: str | None,
|
||||
is_private: bool,
|
||||
enable_youtube_upload: bool,
|
||||
) -> tuple:
|
||||
"""
|
||||
Apply tenant-specific overrides to distribution settings and job options.
|
||||
|
||||
For tenant jobs:
|
||||
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
|
||||
(only when not already set in the request body / dist)
|
||||
- Forces is_private = True
|
||||
- Applies locked_theme as effective theme
|
||||
- Disables YouTube upload
|
||||
|
||||
Returns:
|
||||
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
|
||||
"""
|
||||
if not tenant_config:
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
defaults = tenant_config.defaults
|
||||
|
||||
# Overlay tenant distribution defaults (request-level values take precedence)
|
||||
if defaults.brand_prefix and not dist.brand_prefix:
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
if defaults.dropbox_path and not dist.dropbox_path:
|
||||
dist.dropbox_path = defaults.dropbox_path
|
||||
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id
|
||||
|
||||
# Force private for all tenant jobs
|
||||
is_private = True
|
||||
|
||||
# Apply locked_theme (overrides any user selection)
|
||||
if defaults.locked_theme:
|
||||
effective_theme_id = defaults.locked_theme
|
||||
|
||||
# Disable YouTube upload for tenants
|
||||
enable_youtube_upload = False
|
||||
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Pydantic models for signed URL upload flow
|
||||
# ============================================================================
|
||||
@@ -510,7 +556,7 @@ async def upload_and_create_job(
|
||||
"auth_url": "/api/auth/status"
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# Extract request metadata for tracking and filtering
|
||||
request_metadata = extract_request_metadata(request, created_from="upload")
|
||||
|
||||
@@ -534,6 +580,14 @@ async def upload_and_create_job(
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Apply tenant-specific overrides (brand, paths, privacy, theme)
|
||||
dist, effective_theme_id, is_private, effective_enable_youtube_upload = _apply_tenant_overrides(
|
||||
dist, tenant_config, effective_theme_id, is_private, effective_enable_youtube_upload,
|
||||
)
|
||||
if tenant_config:
|
||||
logger.info(f"Applied tenant overrides for '{tenant_config.id}': "
|
||||
f"brand={dist.brand_prefix}, private={is_private}, theme={effective_theme_id}")
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(
|
||||
effective_theme_id, enable_cdg, enable_txt
|
||||
@@ -1077,12 +1131,29 @@ async def create_job_with_upload_urls(
|
||||
settings = get_settings()
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
|
||||
|
||||
# Apply default theme if none specified
|
||||
effective_theme_id = body.theme_id
|
||||
if effective_theme_id is None:
|
||||
theme_service = get_theme_service()
|
||||
effective_theme_id = theme_service.get_default_theme_id()
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Apply tenant-specific overrides (brand, paths, privacy, theme)
|
||||
effective_is_private = body.is_private
|
||||
dist, effective_theme_id, effective_is_private, effective_enable_youtube_upload = _apply_tenant_overrides(
|
||||
dist, tenant_config, effective_theme_id, effective_is_private, effective_enable_youtube_upload,
|
||||
)
|
||||
if tenant_config:
|
||||
logger.info(f"Applied tenant overrides for '{tenant_config.id}': "
|
||||
f"brand={dist.brand_prefix}, private={effective_is_private}, theme={effective_theme_id}")
|
||||
|
||||
# Validate credentials for requested distribution services
|
||||
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
|
||||
invalid_services = []
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload and not body.is_private:
|
||||
if effective_enable_youtube_upload and not effective_is_private:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -1092,7 +1163,7 @@ async def create_job_with_upload_urls(
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id and not body.is_private:
|
||||
if dist.gdrive_folder_id and not effective_is_private:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -1114,15 +1185,6 @@ async def create_job_with_upload_urls(
|
||||
# Get original audio filename
|
||||
audio_file = audio_files[0]
|
||||
|
||||
# Apply default theme if none specified
|
||||
# This ensures all karaoke videos use the Nomad theme by default
|
||||
effective_theme_id = body.theme_id
|
||||
if effective_theme_id is None:
|
||||
theme_service = get_theme_service()
|
||||
effective_theme_id = theme_service.get_default_theme_id()
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(
|
||||
effective_theme_id, body.enable_cdg, body.enable_txt
|
||||
@@ -1161,7 +1223,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,
|
||||
is_private=effective_is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
|
||||
@@ -1213,9 +1213,9 @@ async def download_file(
|
||||
storage = StorageService()
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=f'.{ext}') as tmp:
|
||||
tmp_path = tmp.name
|
||||
|
||||
|
||||
storage.download_file(gcs_path, tmp_path)
|
||||
|
||||
|
||||
def file_iterator():
|
||||
try:
|
||||
with open(tmp_path, 'rb') as f:
|
||||
@@ -1224,12 +1224,23 @@ async def download_file(
|
||||
finally:
|
||||
import os
|
||||
os.unlink(tmp_path)
|
||||
|
||||
|
||||
# Build Content-Disposition header with RFC 5987 encoding for non-ASCII filenames
|
||||
# (e.g. Chinese, Japanese, Korean characters that can't be encoded in latin-1)
|
||||
from urllib.parse import quote
|
||||
try:
|
||||
filename.encode('latin-1')
|
||||
content_disposition = f'attachment; filename="{filename}"'
|
||||
except UnicodeEncodeError:
|
||||
ascii_filename = filename.encode('ascii', 'replace').decode('ascii')
|
||||
utf8_filename = quote(filename)
|
||||
content_disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{utf8_filename}"
|
||||
|
||||
return StreamingResponse(
|
||||
file_iterator(),
|
||||
media_type=content_type,
|
||||
headers={
|
||||
'Content-Disposition': f'attachment; filename="{filename}"'
|
||||
'Content-Disposition': content_disposition
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
|
||||
@@ -95,6 +95,12 @@ class TenantDefaults(BaseModel):
|
||||
brand_prefix: Optional[str] = Field(
|
||||
None, description="Prefix for output filenames (e.g., 'VSTAR')"
|
||||
)
|
||||
dropbox_path: Optional[str] = Field(
|
||||
None, description="Tenant-specific Dropbox folder path (e.g., '/Karaoke/Vocal-Star')"
|
||||
)
|
||||
gdrive_folder_id: Optional[str] = Field(
|
||||
None, description="Tenant-specific Google Drive folder ID for output uploads"
|
||||
)
|
||||
youtube_description_template: Optional[str] = Field(
|
||||
None, description="Default YouTube description template"
|
||||
)
|
||||
|
||||
@@ -80,6 +80,17 @@ def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings:
|
||||
EffectiveDistributionSettings with private overrides applied if needed
|
||||
"""
|
||||
if getattr(job, 'is_private', False):
|
||||
# Tenant jobs: use the job's own distribution fields (set at creation from tenant config)
|
||||
# Non-tenant private jobs: override to NonPublished paths
|
||||
if getattr(job, 'tenant_id', None):
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=getattr(job, 'dropbox_path', None),
|
||||
brand_prefix=getattr(job, 'brand_prefix', None),
|
||||
enable_youtube_upload=False,
|
||||
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=None,
|
||||
)
|
||||
settings = get_settings()
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=settings.default_private_dropbox_path,
|
||||
|
||||
@@ -406,6 +406,7 @@ class TestOrchestratorConfigPrivate:
|
||||
job.gdrive_folder_id = "folder-123"
|
||||
job.keep_brand_code = None
|
||||
job.existing_instrumental_gcs_path = None
|
||||
job.tenant_id = None # Non-tenant job
|
||||
|
||||
config = create_orchestrator_config_from_job(
|
||||
job=job,
|
||||
|
||||
@@ -603,3 +603,68 @@ class TestScreensWorkerBackingVocalsAnalysis:
|
||||
analysis = job.state_data.get('backing_vocals_analysis', {})
|
||||
assert analysis.get('recommended_selection') is not None
|
||||
|
||||
|
||||
class TestContentDispositionHeader:
|
||||
"""Tests for Content-Disposition header building in download_file.
|
||||
|
||||
Verifies that filenames with non-latin-1 characters (CJK, Cyrillic, etc.)
|
||||
use RFC 5987 filename*=UTF-8'' encoding instead of crashing.
|
||||
"""
|
||||
|
||||
def _build_content_disposition(self, filename: str) -> str:
|
||||
"""Replicate the Content-Disposition logic from download_file."""
|
||||
from urllib.parse import quote
|
||||
try:
|
||||
filename.encode('latin-1')
|
||||
return f'attachment; filename="{filename}"'
|
||||
except UnicodeEncodeError:
|
||||
ascii_filename = filename.encode('ascii', 'replace').decode('ascii')
|
||||
utf8_filename = quote(filename)
|
||||
return f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{utf8_filename}"
|
||||
|
||||
def test_ascii_filename_uses_simple_header(self):
|
||||
header = self._build_content_disposition("Artist - Song (Final Karaoke).mp4")
|
||||
assert header == 'attachment; filename="Artist - Song (Final Karaoke).mp4"'
|
||||
assert "filename*" not in header
|
||||
|
||||
def test_latin1_accented_filename_uses_simple_header(self):
|
||||
header = self._build_content_disposition("Café - Señorita.mp4")
|
||||
assert header == 'attachment; filename="Café - Señorita.mp4"'
|
||||
assert "filename*" not in header
|
||||
|
||||
def test_chinese_filename_uses_rfc5987(self):
|
||||
header = self._build_content_disposition("周杰倫 - 青花瓷 (Final Karaoke).mp4")
|
||||
assert "filename*=UTF-8''" in header
|
||||
# ASCII fallback should be present
|
||||
assert 'filename="' in header
|
||||
# Should be encodable as latin-1 (the whole header)
|
||||
# The ASCII fallback part is safe; the UTF-8 part is percent-encoded
|
||||
assert "%E5%91%A8" in header # 周 percent-encoded
|
||||
|
||||
def test_japanese_filename_uses_rfc5987(self):
|
||||
header = self._build_content_disposition("宇多田ヒカル - First Love.mp4")
|
||||
assert "filename*=UTF-8''" in header
|
||||
|
||||
def test_korean_filename_uses_rfc5987(self):
|
||||
header = self._build_content_disposition("방탄소년단 - Dynamite.mp4")
|
||||
assert "filename*=UTF-8''" in header
|
||||
|
||||
def test_cyrillic_filename_uses_rfc5987(self):
|
||||
header = self._build_content_disposition("Тату - Нас не догонят.mp4")
|
||||
assert "filename*=UTF-8''" in header
|
||||
|
||||
def test_rfc5987_header_is_latin1_safe(self):
|
||||
"""The entire header string must be encodable as latin-1 for HTTP."""
|
||||
header = self._build_content_disposition("周杰倫 - 青花瓷.mp4")
|
||||
# The header uses percent-encoding for non-ASCII, so it should be ASCII-safe
|
||||
header.encode('latin-1') # Should not raise
|
||||
|
||||
def test_rfc5987_preserves_original_filename(self):
|
||||
"""The UTF-8 encoded filename should decode back to the original."""
|
||||
from urllib.parse import unquote
|
||||
header = self._build_content_disposition("周杰倫 - 青花瓷.mp4")
|
||||
# Extract the filename* value
|
||||
utf8_part = header.split("filename*=UTF-8''")[1]
|
||||
decoded = unquote(utf8_part)
|
||||
assert decoded == "周杰倫 - 青花瓷.mp4"
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
"""
|
||||
Unit tests for tenant-aware job defaults and distribution overrides.
|
||||
|
||||
Tests that:
|
||||
- Tenant config fields (brand_prefix, dropbox_path, gdrive_folder_id) are applied to jobs
|
||||
- All tenant jobs are forced private
|
||||
- Locked theme overrides user selection
|
||||
- Private tenant jobs use tenant-specific paths (not NonPublished)
|
||||
- Non-tenant private jobs still use NonPublished paths
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from backend.models.tenant import TenantConfig, TenantDefaults, TenantFeatures, TenantBranding, TenantAuth
|
||||
from backend.services.job_defaults_service import (
|
||||
get_effective_distribution_settings,
|
||||
get_effective_distribution_for_job,
|
||||
EffectiveDistributionSettings,
|
||||
)
|
||||
|
||||
|
||||
def _make_tenant_config(**defaults_kwargs) -> TenantConfig:
|
||||
"""Create a TenantConfig with custom defaults for testing."""
|
||||
return TenantConfig(
|
||||
id="vocalstar",
|
||||
name="Vocal Star",
|
||||
subdomain="vocalstar.nomadkaraoke.com",
|
||||
defaults=TenantDefaults(
|
||||
locked_theme="vocalstar",
|
||||
distribution_mode="cloud_only",
|
||||
brand_prefix="VSTAR",
|
||||
dropbox_path="/Karaoke/Vocal-Star",
|
||||
gdrive_folder_id="gdrive-folder-123",
|
||||
**defaults_kwargs,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _make_job_mock(**kwargs):
|
||||
"""Create a mock job object with the given attributes."""
|
||||
defaults = {
|
||||
"is_private": False,
|
||||
"tenant_id": None,
|
||||
"dropbox_path": None,
|
||||
"gdrive_folder_id": None,
|
||||
"brand_prefix": None,
|
||||
"enable_youtube_upload": False,
|
||||
"discord_webhook_url": None,
|
||||
"youtube_description_template": None,
|
||||
}
|
||||
defaults.update(kwargs)
|
||||
job = MagicMock()
|
||||
for key, value in defaults.items():
|
||||
setattr(job, key, value)
|
||||
return job
|
||||
|
||||
|
||||
class TestApplyTenantOverrides:
|
||||
"""Tests for _apply_tenant_overrides() in file_upload.py."""
|
||||
|
||||
def _get_apply_fn(self):
|
||||
"""Import the function under test."""
|
||||
from backend.api.routes.file_upload import _apply_tenant_overrides
|
||||
return _apply_tenant_overrides
|
||||
|
||||
def test_tenant_defaults_applied_to_distribution(self):
|
||||
"""Tenant brand_prefix, dropbox_path, gdrive_folder_id are applied to distribution settings."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None,
|
||||
gdrive_folder_id=None,
|
||||
discord_webhook_url=None,
|
||||
brand_prefix=None,
|
||||
enable_youtube_upload=True,
|
||||
youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, theme, is_private, yt_upload = apply_fn(
|
||||
dist, tenant_config, "default", False, True
|
||||
)
|
||||
|
||||
assert new_dist.brand_prefix == "VSTAR"
|
||||
assert new_dist.dropbox_path == "/Karaoke/Vocal-Star"
|
||||
assert new_dist.gdrive_folder_id == "gdrive-folder-123"
|
||||
|
||||
def test_tenant_job_forced_private(self):
|
||||
"""All tenant jobs are forced to is_private=True."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
_, _, is_private, _ = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert is_private is True
|
||||
|
||||
def test_tenant_locked_theme_applied(self):
|
||||
"""locked_theme overrides the user's theme selection."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
_, theme, _, _ = apply_fn(dist, tenant_config, "user-selected-theme", False, True)
|
||||
assert theme == "vocalstar"
|
||||
|
||||
def test_tenant_youtube_upload_disabled(self):
|
||||
"""YouTube upload is disabled for tenant jobs."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
_, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert yt_upload is False
|
||||
|
||||
def test_request_values_take_precedence(self):
|
||||
"""Explicit request-level values are not overridden by tenant defaults."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
tenant_config = _make_tenant_config()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path="/Custom/Path",
|
||||
gdrive_folder_id="custom-folder",
|
||||
discord_webhook_url=None,
|
||||
brand_prefix="CUSTOM",
|
||||
enable_youtube_upload=True,
|
||||
youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
|
||||
assert new_dist.brand_prefix == "CUSTOM"
|
||||
assert new_dist.dropbox_path == "/Custom/Path"
|
||||
assert new_dist.gdrive_folder_id == "custom-folder"
|
||||
|
||||
def test_no_tenant_config_passthrough(self):
|
||||
"""When no tenant config, all values pass through unchanged."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path="/Some/Path", gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix="NOMAD", enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, theme, is_private, yt_upload = apply_fn(
|
||||
dist, None, "nomad", False, True
|
||||
)
|
||||
assert new_dist.brand_prefix == "NOMAD"
|
||||
assert new_dist.dropbox_path == "/Some/Path"
|
||||
assert theme == "nomad"
|
||||
assert is_private is False
|
||||
assert yt_upload is True
|
||||
|
||||
def test_partial_tenant_defaults_only_overrides_set_fields(self):
|
||||
"""When tenant config has only some defaults, only those are applied."""
|
||||
apply_fn = self._get_apply_fn()
|
||||
# Only brand_prefix set, no dropbox_path or gdrive_folder_id
|
||||
tenant_config = TenantConfig(
|
||||
id="partial",
|
||||
name="Partial Tenant",
|
||||
subdomain="partial.nomadkaraoke.com",
|
||||
defaults=TenantDefaults(
|
||||
brand_prefix="PART",
|
||||
dropbox_path=None,
|
||||
gdrive_folder_id=None,
|
||||
locked_theme=None,
|
||||
),
|
||||
)
|
||||
|
||||
dist = EffectiveDistributionSettings(
|
||||
dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None,
|
||||
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
|
||||
)
|
||||
|
||||
new_dist, theme, is_private, yt_upload = apply_fn(
|
||||
dist, tenant_config, "user-theme", False, True
|
||||
)
|
||||
|
||||
# brand_prefix applied
|
||||
assert new_dist.brand_prefix == "PART"
|
||||
# dropbox/gdrive remain None since tenant has None
|
||||
assert new_dist.dropbox_path is None
|
||||
assert new_dist.gdrive_folder_id is None
|
||||
# No locked_theme, so user theme preserved
|
||||
assert theme == "user-theme"
|
||||
# Still forced private and no YT
|
||||
assert is_private is True
|
||||
assert yt_upload is False
|
||||
|
||||
|
||||
class TestTenantJobDistribution:
|
||||
"""Tests for get_effective_distribution_for_job() with tenant jobs."""
|
||||
|
||||
def test_private_tenant_job_uses_tenant_paths(self):
|
||||
"""Private tenant jobs use their own Dropbox/GDrive paths, not NonPublished."""
|
||||
job = _make_job_mock(
|
||||
is_private=True,
|
||||
tenant_id="vocalstar",
|
||||
dropbox_path="/Karaoke/Vocal-Star",
|
||||
gdrive_folder_id="gdrive-folder-123",
|
||||
brand_prefix="VSTAR",
|
||||
)
|
||||
|
||||
result = get_effective_distribution_for_job(job)
|
||||
|
||||
assert result.dropbox_path == "/Karaoke/Vocal-Star"
|
||||
assert result.gdrive_folder_id == "gdrive-folder-123"
|
||||
assert result.brand_prefix == "VSTAR"
|
||||
assert result.enable_youtube_upload is False
|
||||
|
||||
@patch("backend.services.job_defaults_service.get_settings")
|
||||
def test_non_tenant_private_job_still_uses_nonpublished(self, mock_settings):
|
||||
"""Non-tenant private jobs still get the NonPublished path override."""
|
||||
mock_settings.return_value = MagicMock(
|
||||
default_private_dropbox_path="/Tracks-NonPublished",
|
||||
default_private_brand_prefix="NOMADNP",
|
||||
)
|
||||
|
||||
job = _make_job_mock(
|
||||
is_private=True,
|
||||
tenant_id=None,
|
||||
dropbox_path="/Some/User/Path",
|
||||
brand_prefix="SOMETHING",
|
||||
)
|
||||
|
||||
result = get_effective_distribution_for_job(job)
|
||||
|
||||
assert result.dropbox_path == "/Tracks-NonPublished"
|
||||
assert result.brand_prefix == "NOMADNP"
|
||||
assert result.enable_youtube_upload is False
|
||||
assert result.gdrive_folder_id is None
|
||||
|
||||
def test_non_private_job_uses_own_settings(self):
|
||||
"""Non-private jobs (tenant or not) use their own distribution settings."""
|
||||
job = _make_job_mock(
|
||||
is_private=False,
|
||||
tenant_id="vocalstar",
|
||||
dropbox_path="/Karaoke/Vocal-Star",
|
||||
gdrive_folder_id="gdrive-folder-123",
|
||||
brand_prefix="VSTAR",
|
||||
enable_youtube_upload=False,
|
||||
)
|
||||
|
||||
result = get_effective_distribution_for_job(job)
|
||||
|
||||
assert result.dropbox_path == "/Karaoke/Vocal-Star"
|
||||
assert result.gdrive_folder_id == "gdrive-folder-123"
|
||||
assert result.brand_prefix == "VSTAR"
|
||||
@@ -209,6 +209,39 @@ class TestSanitizationInContext:
|
||||
# Note: The test above with 'é' passes latin-1; smart quotes do not
|
||||
assert can_encode
|
||||
|
||||
def test_content_disposition_cjk_uses_rfc5987(self):
|
||||
"""Verify CJK filenames use RFC 5987 encoding in Content-Disposition.
|
||||
|
||||
Chinese/Japanese/Korean characters can't be encoded in latin-1,
|
||||
so the download endpoint must use filename*=UTF-8'' encoding.
|
||||
"""
|
||||
from urllib.parse import quote
|
||||
|
||||
artist = "周杰倫"
|
||||
title = "青花瓷"
|
||||
|
||||
safe_artist = sanitize_filename(artist) if artist else None
|
||||
safe_title = sanitize_filename(title) if title else None
|
||||
filename = f"{safe_artist} - {safe_title} (Final Karaoke).mp4"
|
||||
|
||||
# CJK characters cannot be encoded as latin-1
|
||||
with pytest.raises(UnicodeEncodeError):
|
||||
filename.encode('latin-1')
|
||||
|
||||
# The download endpoint should fall back to RFC 5987 encoding
|
||||
ascii_filename = filename.encode('ascii', 'replace').decode('ascii')
|
||||
utf8_filename = quote(filename)
|
||||
content_disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{utf8_filename}"
|
||||
|
||||
# ASCII fallback should be safe
|
||||
ascii_filename.encode('latin-1')
|
||||
|
||||
# UTF-8 encoded filename should contain the original characters when decoded
|
||||
from urllib.parse import unquote
|
||||
decoded = unquote(utf8_filename)
|
||||
assert "周杰倫" in decoded
|
||||
assert "青花瓷" in decoded
|
||||
|
||||
def test_google_drive_query_safe(self):
|
||||
"""Verify filenames don't break Google Drive API queries."""
|
||||
base_name = "Artist\u2019s \u201cSong\u201d"
|
||||
|
||||
@@ -453,10 +453,11 @@ if tenant_config and not tenant_config.features.audio_search:
|
||||
### Active Tenants
|
||||
|
||||
**Vocal Star** (`vocalstar.nomadkaraoke.com`)
|
||||
- Features: File upload only (no audio search, no YouTube URL)
|
||||
- Distribution: Download only (no YouTube/Dropbox/GDrive)
|
||||
- Features: File upload only (no audio search, no YouTube URL), streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio)
|
||||
- Distribution: Cloud only (Dropbox + Google Drive to tenant-specific folders, no YouTube)
|
||||
- Theme: Locked to "vocalstar" theme (yellow/blue)
|
||||
- Auth: Restricted to `@vocal-star.com` and `@vocalstarmusic.com` emails
|
||||
- All jobs automatically private with VSTAR brand prefix
|
||||
- Setup: `python scripts/setup-vocalstar-tenant.py`
|
||||
|
||||
**Singa** (`singa.nomadkaraoke.com`)
|
||||
|
||||
@@ -664,6 +664,21 @@ export function PrimaryButton({ children, ...props }) {
|
||||
|
||||
---
|
||||
|
||||
## Public Video Style Consistency Rule
|
||||
|
||||
**All videos published to Nomad Karaoke distribution channels (YouTube, Google Drive, venue libraries) MUST use the standard Nomad Karaoke visual style.** No customization of colors, backgrounds, fonts, or other visual elements is permitted for public videos.
|
||||
|
||||
This ensures:
|
||||
- Consistent brand identity across the entire Nomad Karaoke catalog
|
||||
- Professional, recognizable appearance at venues worldwide
|
||||
- Uniform experience for audiences browsing the YouTube channel or venue libraries
|
||||
|
||||
Only the **display artist name** and **display title** text can be overridden for public videos (e.g. to format a soundtrack or cover correctly).
|
||||
|
||||
Custom video styling (backgrounds, colors, fonts) is available exclusively for **private** deliveries where the user takes full responsibility for distribution.
|
||||
|
||||
---
|
||||
|
||||
## Checklist for Brand Compliance
|
||||
|
||||
### Landing Pages
|
||||
|
||||
+12
-1
@@ -301,7 +301,18 @@ Escape special chars in Google Drive API queries: `'` → `\'`, `\` → `\\\\`.
|
||||
For subprocess without shell, FFmpeg filter paths need: apostrophes escaped as `'\\''`, special chars as `\\[char]`.
|
||||
|
||||
### Unicode in HTTP Headers
|
||||
Sanitize user input (artist/title) to ASCII for HTTP headers. Smart quotes, em dashes from copy/paste cause encoding errors.
|
||||
Sanitize user input (artist/title) to ASCII for HTTP headers. Smart quotes, em dashes from copy/paste cause encoding errors. For CJK characters (Chinese, Japanese, Korean) that can't be replaced with ASCII equivalents, use RFC 5987 `filename*=UTF-8''` encoding in Content-Disposition headers instead of trying to force latin-1.
|
||||
|
||||
### CJK Characters in Title Cards (Mar 2026)
|
||||
**What happened**: Job `f8a36b60` with Chinese artist/title rendered question marks on the title card, and download links failed with `'latin-1' codec can't encode characters`.
|
||||
|
||||
**Root cause (title card)**: The title screen uses `Montserrat-Bold.ttf` which has no CJK glyphs. PIL renders missing glyphs as question marks. The karaoke subtitle renderer already uses Noto Sans (with `fonts-noto-cjk` installed in Docker), but the title card `VideoGenerator` had no font fallback.
|
||||
|
||||
**Root cause (downloads)**: `sanitize_filename()` correctly preserves CJK characters (they're valid in filenames), but the `Content-Disposition` header used simple `filename="..."` which requires latin-1 encoding. CJK characters can't be encoded in latin-1.
|
||||
|
||||
**Fix**: (1) Added CJK font fallback in `VideoGenerator._render_all_text()` - detects CJK characters per text element and uses system Noto Sans CJK font via `fontconfig` (`fc-match`). (2) Added RFC 5987 encoding for Content-Disposition headers when filename contains non-latin-1 characters.
|
||||
|
||||
**Pattern**: When rendering text with PIL, the configured font may not support all scripts. Check if text contains characters outside the font's coverage and fall back to a system font with broader Unicode support (Noto Sans CJK). For HTTP headers, always handle the case where filenames contain characters beyond latin-1.
|
||||
|
||||
### Unicode in File Paths (Feb 2026)
|
||||
**What happened**: Job `1eab1172` with Russian title "я куплю тебе дом" (Cyrillic) failed with FFmpeg exit code 183. The temp subtitle file path contained Unicode characters: `temp_subtitles_zivert___я_куплю_тебе_дом_1770150285852.ass`.
|
||||
|
||||
@@ -45,6 +45,8 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Tenant Portal UI Rework** (2026-03-04): Replaced the multi-step consumer wizard with a streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) for B2B tenant portals. Vocal Star's portal now uses the new `TenantJobFlow` component instead of `GuidedJobFlow`. All tenant jobs are automatically private with tenant-specific distribution: Dropbox delivery to `/MediaUnsynced/Karaoke/Tracks-VocalStar`, Google Drive upload to tenant folder, VSTAR brand prefix. Backend adds `_apply_tenant_overrides()` helper that forces private, applies locked theme, and overlays tenant distribution settings. Private tenant jobs now use their own Dropbox/GDrive paths instead of the NonPublished override. Frontend conditionally renders `TenantJobFlow` vs `GuidedJobFlow` based on tenant detection. See [archive/2026-03-04-tenant-portal-ui-rework.md](archive/2026-03-04-tenant-portal-ui-rework.md).
|
||||
|
||||
- **Custom Video Styling for Private Jobs** (2026-03-04): Users who select "Private (no YouTube upload)" can now customize their karaoke video styling. New options in the guided flow's customize step: upload a custom **karaoke background image** (replaces the starfield behind lyrics), upload a custom **title card background image**, and change **artist/title text colors** via color pickers. Both backgrounds show accurate canvas-based live previews. Style assets are uploaded to GCS via signed URLs after job creation (non-blocking — job falls back to default theme on upload failure). Backend: 2 new endpoints (`style-upload-urls`, `style-uploads-complete`) that validate ownership, cutoff status, and merge custom assets into the theme's `style_params.json`. See [API.md](API.md#get-style-upload-urls).
|
||||
|
||||
- **Tenant Portal Frontend Separation** (2026-03-03): B2B tenants now served from a dedicated Cloudflare Pages project (`karaoke-gen-tenant`) built with `NEXT_PUBLIC_TENANT_PORTAL=true` to tree-shake consumer content. A Cloudflare edge function injects `window.__TENANT_CONFIG__` and CSS variables into HTML at the edge, eliminating the initial API round-trip for tenant config. Magic link emails now use tenant-specific URLs (e.g., `vocalstar.nomadkaraoke.com/auth/verify`). Admins can preview any tenant's branding via `?preview_tenant=<id>`. See [ARCHITECTURE.md](ARCHITECTURE.md#tenant-portal-frontend-b2b-deployment).
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
# Tenant Portal UI Rework
|
||||
|
||||
**Date**: 2026-03-04
|
||||
**Branch**: `feat/sess-20260304-0007-tenant-ui-rework`
|
||||
**Worktree**: `karaoke-gen-tenant-ui-rework`
|
||||
**Status**: Implementation + Config Complete — Ready for PR
|
||||
|
||||
## Context
|
||||
|
||||
The tenant portal at `vocalstar.nomadkaraoke.com` shows the same 3-step consumer wizard (song search -> audio source -> customize) designed for end users. B2B white-label customers like Vocal Star always provide their own mixed audio AND instrumental files. They don't need audio search, YouTube URL input, theme selection, privacy toggles, or customization options.
|
||||
|
||||
**Goal**: Replace the multi-step wizard with a streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) for tenant portals. All tracks are automatically private, delivered to tenant-specific Dropbox/Google Drive folders, with tenant brand codes and styling.
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Phase 1: Backend — Tenant Distribution Defaults
|
||||
|
||||
| Step | File | Change | Status |
|
||||
|------|------|--------|--------|
|
||||
| 1.1 | `backend/models/tenant.py` | Add `dropbox_path`, `gdrive_folder_id` to TenantDefaults | Done |
|
||||
| 1.2 | `backend/api/routes/file_upload.py` | Create `_apply_tenant_overrides()`, call in 2 endpoints | Done |
|
||||
| 1.3 | `backend/services/job_defaults_service.py` | Tenant-aware private job handling (skip NonPublished override) | Done |
|
||||
| 1.4 | `frontend/lib/api.ts` | Add `existing_instrumental` flag to createJobWithUploadUrls | Done |
|
||||
| 1.5 | `backend/tests/test_tenant_job_defaults.py` | 9 unit tests for tenant override logic | Done |
|
||||
|
||||
**1.1 Details**: Two new Optional fields on TenantDefaults:
|
||||
- `dropbox_path: Optional[str]` — e.g., `/Karaoke/Vocal-Star`
|
||||
- `gdrive_folder_id: Optional[str]` — tenant GDrive folder ID
|
||||
|
||||
Already excluded from TenantPublicConfig (line 194 only copies theme_id, locked_theme, distribution_mode).
|
||||
|
||||
**1.2 Details**: `_apply_tenant_overrides(dist, tenant_config, body)` helper that:
|
||||
1. Overlays tenant `brand_prefix`, `dropbox_path`, `gdrive_folder_id` onto EffectiveDistributionSettings
|
||||
2. Forces `is_private = True` for all tenant jobs
|
||||
3. Applies `locked_theme` as effective theme
|
||||
4. Disables YouTube upload
|
||||
|
||||
Called in: `create_job_with_upload_urls` (line 971) and `upload_and_create_job` (line 324).
|
||||
|
||||
**1.3 Details**: In `get_effective_distribution_for_job` (line 64), if `job.tenant_id` is set AND `is_private=True`, skip the NonPublished path override. Use job's own distribution fields (which contain tenant defaults from creation). Still disable YouTube.
|
||||
|
||||
**1.4 Details**: The backend `CreateJobWithUploadUrlsRequest` already has `existing_instrumental: bool` (line 170). Frontend `api.ts` `createJobWithUploadUrls()` just needs to pass it through in the request body.
|
||||
|
||||
**1.5 Tests**:
|
||||
- `test_tenant_defaults_applied_to_distribution` — brand_prefix, dropbox_path, gdrive_folder_id applied
|
||||
- `test_tenant_job_forced_private` — is_private always True for tenant jobs
|
||||
- `test_tenant_locked_theme_applied` — locked_theme overrides user theme
|
||||
- `test_private_tenant_job_uses_tenant_paths` — uses tenant Dropbox/GDrive, NOT NonPublished
|
||||
- `test_non_tenant_private_job_still_uses_nonpublished` — existing behavior preserved
|
||||
|
||||
### Phase 2: Frontend — TenantJobFlow Component
|
||||
|
||||
| Step | File | Change | Status |
|
||||
|------|------|--------|--------|
|
||||
| 2.1 | `frontend/components/job/TenantJobFlow.tsx` | **Create** single-page 4-field form | Done |
|
||||
| 2.2 | `frontend/app/app/page.tsx` | TenantLogo in header, conditional form rendering | Done |
|
||||
| 2.3 | `frontend/__tests__/tenant-job-flow.test.tsx` | Component tests (4 tests) | Done |
|
||||
|
||||
**2.1 Details**: Single-page form (~250 lines) with:
|
||||
- Artist text input, Title text input
|
||||
- Mixed Audio file upload (drag-and-drop, accepts .mp3,.wav,.flac,.m4a,.ogg,.aac)
|
||||
- Instrumental Audio file upload (same types)
|
||||
- Submit button (disabled until all 4 fields filled)
|
||||
- Submission: `createJobWithUploadUrls` -> `uploadToSignedUrl` x2 -> `completeJobUpload`
|
||||
- Success view: simplified timeline (review lyrics -> video delivered), "Create Another" button
|
||||
- Omits "audio processing" step since instrumental is provided
|
||||
|
||||
**2.2 Details**:
|
||||
- Replace hardcoded `<img src="/nomad-karaoke-logo.svg">` (line 196) with `<TenantLogo size="sm" />`
|
||||
- Tenant-aware title using `branding.site_title`
|
||||
- Conditional: `<TenantJobFlow>` when `!isDefault`, else `<GuidedJobFlow>`
|
||||
- Card text: "Submit Track" / "Upload your mixed audio and instrumental" for tenants
|
||||
- Hide feedback banner for non-default users
|
||||
|
||||
### Phase 3: Config & Deployment
|
||||
|
||||
| Step | Change | Status |
|
||||
|------|--------|--------|
|
||||
| 3.1 | Update Vocalstar tenant config in GCS | Done |
|
||||
| 3.2 | Post-deploy setup tasks | Done — all verified |
|
||||
|
||||
Config additions needed:
|
||||
```json
|
||||
{
|
||||
"defaults": {
|
||||
"locked_theme": "vocalstar",
|
||||
"distribution_mode": "cloud_only",
|
||||
"brand_prefix": "VSTAR",
|
||||
"dropbox_path": "<user-to-provide>",
|
||||
"gdrive_folder_id": "<user-to-provide>"
|
||||
},
|
||||
"features": {
|
||||
"audio_search": false,
|
||||
"file_upload": true,
|
||||
"youtube_url": false,
|
||||
"youtube_upload": false,
|
||||
"theme_selection": false,
|
||||
"color_overrides": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 4: Production Verification
|
||||
|
||||
| Step | File | Change | Status |
|
||||
|------|------|--------|--------|
|
||||
| 4.1 | `frontend/e2e/production/tenant-job-submission.spec.ts` | **Create** Playwright E2E test (3 tests) | Done |
|
||||
|
||||
Full lifecycle: navigate tenant portal -> verify branding -> submit track -> wait for processing -> approve reviews -> verify outputs delivered to tenant paths.
|
||||
|
||||
## Key Files
|
||||
|
||||
| File | Action |
|
||||
|------|--------|
|
||||
| `backend/models/tenant.py` | Modify — add 2 fields to TenantDefaults |
|
||||
| `backend/api/routes/file_upload.py` | Modify — add `_apply_tenant_overrides()`, call in 2 endpoints |
|
||||
| `backend/services/job_defaults_service.py` | Modify — tenant-aware private job handling |
|
||||
| `frontend/components/job/TenantJobFlow.tsx` | **Create** — new simplified 4-field form |
|
||||
| `frontend/app/app/page.tsx` | Modify — TenantLogo in header, conditional form |
|
||||
| `frontend/lib/api.ts` | Modify — add `existing_instrumental` flag |
|
||||
| `backend/tests/test_tenant_job_defaults.py` | **Create** — backend tests |
|
||||
| `frontend/__tests__/components/job/TenantJobFlow.test.tsx` | **Create** — component tests |
|
||||
| `frontend/e2e/production/tenant-job-submission.spec.ts` | **Create** — E2E prod test |
|
||||
|
||||
## Implementation Log
|
||||
|
||||
### Phase 1 — Backend (Complete)
|
||||
- Added `dropbox_path` and `gdrive_folder_id` to `TenantDefaults` model
|
||||
- Created `_apply_tenant_overrides()` helper in `file_upload.py` — overlays tenant config, forces private, applies locked_theme, disables YouTube
|
||||
- Wired into both `upload_and_create_job` and `create_job_with_upload_urls` endpoints
|
||||
- Fixed `get_effective_distribution_for_job` to respect tenant paths for private jobs (skips NonPublished override when `tenant_id` is set)
|
||||
- Added `existing_instrumental` option to frontend `api.createJobWithUploadUrls()`
|
||||
- 9 unit tests in `test_tenant_job_defaults.py` — all pass
|
||||
|
||||
### Phase 2 — Frontend (Complete)
|
||||
- Created `TenantJobFlow.tsx` (~300 lines) — 4-field form with drag-and-drop, progress tracking, success timeline
|
||||
- Updated `app/page.tsx`:
|
||||
- `TenantLogo` component in header (replaces hardcoded Nomad logo for tenants)
|
||||
- Tenant-aware title using `branding.site_title`
|
||||
- Conditional rendering: `TenantJobFlow` for tenants, `GuidedJobFlow` for consumers
|
||||
- Card titles/descriptions adapted per mode
|
||||
- Feedback banner hidden for tenants
|
||||
- 4 component tests in `tenant-job-flow.test.tsx` — all pass (520/520 total)
|
||||
|
||||
### Phase 3 — Config (Complete)
|
||||
- Updated `gs://karaoke-gen-storage-nomadkaraoke/tenants/vocalstar/config.json`:
|
||||
- `distribution_mode`: "download_only" → "cloud_only"
|
||||
- `dropbox_upload`/`gdrive_upload`: false → true
|
||||
- Added `dropbox_path`: "/MediaUnsynced/Karaoke/Tracks-VocalStar"
|
||||
- Added `gdrive_folder_id`: "15pKDJSh9uQSAJFbKlHsiiRLmFCUkYZPc"
|
||||
- Verified: `vocalstar` theme exists with style_params.json + 6 assets (font, backgrounds)
|
||||
- Verified: logo.jpg accessible via API asset endpoint (85KB, 200 OK)
|
||||
|
||||
### Phase 4 — E2E (Complete)
|
||||
- Created `tenant-job-submission.spec.ts` with 3 tests:
|
||||
1. Tenant portal shows simplified form (not consumer wizard)
|
||||
2. Full track submission flow
|
||||
3. Consumer portal still works normally
|
||||
@@ -0,0 +1,70 @@
|
||||
# Visibility Step & Customize Rework
|
||||
|
||||
**Date:** 2026-03-04
|
||||
**Branch:** feat/sess-20260304-1700-visibility-step-customize
|
||||
|
||||
## Overview
|
||||
|
||||
Rework the guided job creation flow to add a separate "Visibility" step before "Customize & Create", dedicated to deciding whether the created video should be published or private. Then rework the "Customize & Create" step based on the chosen visibility.
|
||||
|
||||
## New "Visibility" Step
|
||||
|
||||
On this step, we simply let the user choose between public or private, but we use it as an opportunity to ensure the user definitely understands what will happen.
|
||||
|
||||
### Published (Public)
|
||||
|
||||
Explain that "published" means:
|
||||
|
||||
- The resulting karaoke video will be automatically uploaded to the Nomad Karaoke YouTube channel (with a link to https://www.youtube.com/@nomadkaraoke/videos for them to check that out)
|
||||
- It will also be uploaded to a Google Drive which is shared with various karaoke venues, meaning the song will be available to sing at a variety of karaoke bars/venues around the world
|
||||
- The user will get all the source files and highest quality output formats via a Dropbox folder link too, which they can download for their safekeeping
|
||||
- We should encourage the user to choose this option as it's the most convenient way to make their song available to sing (via YouTube) and they'll be helping out other fans of the same song, bringing joy to people all over the world who love that song
|
||||
|
||||
### Private
|
||||
|
||||
Explain that "private" means:
|
||||
|
||||
- The resulting karaoke video will NOT be uploaded to YouTube or Google Drive, and will only be provided via a Dropbox folder / via this site, for the user to download and use however they see fit
|
||||
- If the user wants to perform the track at a venue, they'll be responsible for providing the files to the host at that venue
|
||||
- If the user wants to upload the video to their own YouTube channel they can do so, but they likely won't be able to monetise it (the song licenses/copyrights are still owned by record labels in most cases)
|
||||
- If the user wants to customise the video styles (e.g. background image, colors), they can do this if they choose private delivery
|
||||
|
||||
## Reworked "Customize & Create" Step
|
||||
|
||||
Once we have the new "Visibility" step in the flow, we also need to rework the "Customize & Create" flow:
|
||||
|
||||
### Remove Private Checkbox
|
||||
|
||||
The "private" checkbox on the current Customize & Create step is replaced by the new Visibility step.
|
||||
|
||||
### Conditional Options Based on Visibility
|
||||
|
||||
Since we'll now know already whether the video is private or public, we can show only the options which are allowed:
|
||||
|
||||
- **For public videos**: Only the title card artist/title should be customisable
|
||||
- **For private videos**: Allow customising almost anything
|
||||
|
||||
### Side-by-Side Preview Canvases
|
||||
|
||||
Show the two preview canvases (title screen, main karaoke) side by side in this part of the flow, not below each other, so the user doesn't need to scroll down.
|
||||
|
||||
### Remove Redundant Thumbnails
|
||||
|
||||
Uploaded images for custom backgrounds don't need thumbnails - that's redundant since they're shown on the preview canvas(es).
|
||||
|
||||
### Improved Karaoke Preview Canvas
|
||||
|
||||
The text in the karaoke preview canvas needs to be centered in the thumbnail and show 4 lines so it's more similar to how the actual karaoke videos get rendered (see reference screenshot of actual video output).
|
||||
|
||||
### New Style Customisation Options
|
||||
|
||||
There should be a way to change more aspects of the styles:
|
||||
|
||||
- Change the text color and/or highlight color of the karaoke lyrics
|
||||
- Use a solid color background (rather than an image) for either the title screen or karaoke video (or both with different colors)
|
||||
- Add a few preset color buttons for both of these, including one which is the "green screen" color
|
||||
|
||||
## Reference Screenshots
|
||||
|
||||
- Current "Customize & Create" UI: see attached screenshot showing the existing layout with private checkbox, stacked canvases, and current style options
|
||||
- Actual karaoke video output: see attached screenshot showing how lyrics appear in real videos (4 centered lines with highlight color)
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Tests for the TenantJobFlow component.
|
||||
*
|
||||
* Key invariants verified:
|
||||
* - api.createJobWithUploadUrls is called with existing_instrumental: true and is_private: true
|
||||
* - api.uploadToSignedUrl is called for both audio and instrumental files
|
||||
* - api.completeJobUpload is called with correct file types
|
||||
* - Submit button is disabled until all 4 fields are filled
|
||||
* - Success and error states render correctly
|
||||
*/
|
||||
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// Mock api module
|
||||
jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
createJobWithUploadUrls: jest.fn(),
|
||||
uploadToSignedUrl: jest.fn(),
|
||||
completeJobUpload: jest.fn(),
|
||||
},
|
||||
ApiError: class ApiError extends Error {
|
||||
status: number
|
||||
constructor(message: string, status: number) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/tenant', () => ({
|
||||
useTenant: jest.fn(() => ({
|
||||
branding: {
|
||||
site_title: 'Test Tenant',
|
||||
primary_color: '#ff0000',
|
||||
secondary_color: '#0000ff',
|
||||
},
|
||||
features: {},
|
||||
isDefault: false,
|
||||
tenant: { id: 'test-tenant' },
|
||||
})),
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/auth', () => ({
|
||||
useAuth: jest.fn(() => ({ user: null })),
|
||||
}))
|
||||
|
||||
const mockApi = api as jest.Mocked<typeof api>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API contract tests — verifies correct API calls for tenant upload flow
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('TenantJobFlow — API contract', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('createJobWithUploadUrls is called with existing_instrumental and is_private flags', async () => {
|
||||
mockApi.createJobWithUploadUrls.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'tenant-job-123',
|
||||
message: 'Created',
|
||||
upload_urls: [
|
||||
{ file_type: 'audio', gcs_path: 'path/audio.mp3', upload_url: 'https://signed-url-audio', content_type: 'audio/mpeg' },
|
||||
{ file_type: 'existing_instrumental', gcs_path: 'path/instrumental.mp3', upload_url: 'https://signed-url-inst', content_type: 'audio/mpeg' },
|
||||
],
|
||||
server_version: '1.0',
|
||||
})
|
||||
|
||||
// Simulate what TenantJobFlow.handleSubmit() does
|
||||
const files = [
|
||||
{ filename: 'song.mp3', content_type: 'audio/mpeg', file_type: 'audio' },
|
||||
{ filename: 'inst.mp3', content_type: 'audio/mpeg', file_type: 'existing_instrumental' },
|
||||
]
|
||||
|
||||
await api.createJobWithUploadUrls('Test Artist', 'Test Title', files, {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
|
||||
expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledWith(
|
||||
'Test Artist',
|
||||
'Test Title',
|
||||
files,
|
||||
{ is_private: true, existing_instrumental: true },
|
||||
)
|
||||
})
|
||||
|
||||
it('uploadToSignedUrl is called for both audio and instrumental', async () => {
|
||||
mockApi.uploadToSignedUrl.mockResolvedValue(undefined)
|
||||
|
||||
const audioFile = new File(['audio'], 'song.mp3', { type: 'audio/mpeg' })
|
||||
const instFile = new File(['inst'], 'inst.mp3', { type: 'audio/mpeg' })
|
||||
|
||||
// Upload audio
|
||||
await api.uploadToSignedUrl('https://signed-url-audio', audioFile, 'audio/mpeg')
|
||||
// Upload instrumental
|
||||
await api.uploadToSignedUrl('https://signed-url-inst', instFile, 'audio/mpeg')
|
||||
|
||||
expect(mockApi.uploadToSignedUrl).toHaveBeenCalledTimes(2)
|
||||
expect(mockApi.uploadToSignedUrl).toHaveBeenCalledWith(
|
||||
'https://signed-url-audio', audioFile, 'audio/mpeg',
|
||||
)
|
||||
expect(mockApi.uploadToSignedUrl).toHaveBeenCalledWith(
|
||||
'https://signed-url-inst', instFile, 'audio/mpeg',
|
||||
)
|
||||
})
|
||||
|
||||
it('completeJobUpload is called with both audio and existing_instrumental types', async () => {
|
||||
mockApi.completeJobUpload.mockResolvedValue({
|
||||
status: 'success',
|
||||
message: 'Processing started',
|
||||
})
|
||||
|
||||
await api.completeJobUpload('tenant-job-123', ['audio', 'existing_instrumental'])
|
||||
|
||||
expect(mockApi.completeJobUpload).toHaveBeenCalledWith(
|
||||
'tenant-job-123',
|
||||
['audio', 'existing_instrumental'],
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error handling tests — verifies error paths in handleSubmit
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('TenantJobFlow — error handling', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('ApiError message is surfaced when createJobWithUploadUrls fails', async () => {
|
||||
const { ApiError } = require('@/lib/api')
|
||||
mockApi.createJobWithUploadUrls.mockRejectedValue(
|
||||
new ApiError('Tenant file upload is not enabled', 403),
|
||||
)
|
||||
|
||||
// Simulate handleSubmit error path
|
||||
let errorMessage = ''
|
||||
try {
|
||||
await api.createJobWithUploadUrls('Artist', 'Title', [], {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
} catch (err: any) {
|
||||
errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'
|
||||
}
|
||||
|
||||
expect(errorMessage).toBe('Tenant file upload is not enabled')
|
||||
})
|
||||
|
||||
it('generic errors get fallback message', async () => {
|
||||
mockApi.createJobWithUploadUrls.mockRejectedValue(new TypeError('Network error'))
|
||||
|
||||
const { ApiError } = require('@/lib/api')
|
||||
let errorMessage = ''
|
||||
try {
|
||||
await api.createJobWithUploadUrls('Artist', 'Title', [], {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
} catch (err: any) {
|
||||
errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.'
|
||||
}
|
||||
|
||||
expect(errorMessage).toBe('Something went wrong. Please try again.')
|
||||
})
|
||||
|
||||
it('missing upload URL throws ApiError', async () => {
|
||||
mockApi.createJobWithUploadUrls.mockResolvedValue({
|
||||
status: 'success',
|
||||
job_id: 'job-123',
|
||||
message: 'Created',
|
||||
upload_urls: [
|
||||
// Missing 'audio' file type — only has instrumental
|
||||
{ file_type: 'existing_instrumental', gcs_path: 'p', upload_url: 'https://inst', content_type: 'audio/mpeg' },
|
||||
],
|
||||
server_version: '1.0',
|
||||
})
|
||||
|
||||
const response = await api.createJobWithUploadUrls('Artist', 'Title', [], {
|
||||
is_private: true,
|
||||
existing_instrumental: true,
|
||||
})
|
||||
|
||||
// The component checks: find(u => u.file_type === "audio")
|
||||
const audioUrl = response.upload_urls.find((u: any) => u.file_type === 'audio')
|
||||
expect(audioUrl).toBeUndefined()
|
||||
})
|
||||
|
||||
it('upload failure on instrumental after successful mixed upload is catchable', async () => {
|
||||
mockApi.uploadToSignedUrl
|
||||
.mockResolvedValueOnce(undefined) // mixed succeeds
|
||||
.mockRejectedValueOnce(new Error('Upload timeout')) // instrumental fails
|
||||
|
||||
const audioFile = new File(['audio'], 'song.mp3', { type: 'audio/mpeg' })
|
||||
const instFile = new File(['inst'], 'inst.mp3', { type: 'audio/mpeg' })
|
||||
|
||||
// First upload succeeds
|
||||
await api.uploadToSignedUrl('https://url-audio', audioFile, 'audio/mpeg')
|
||||
|
||||
// Second upload fails
|
||||
await expect(
|
||||
api.uploadToSignedUrl('https://url-inst', instFile, 'audio/mpeg'),
|
||||
).rejects.toThrow('Upload timeout')
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Form validation logic tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('TenantJobFlow — form validation', () => {
|
||||
it('canSubmit requires all 4 fields and idle phase', () => {
|
||||
// Replicate the canSubmit logic from TenantJobFlow
|
||||
const canSubmit = (artist: string, title: string, mixed: File | null, inst: File | null, phase: string) =>
|
||||
!!(artist.trim() && title.trim() && mixed && inst && phase === 'idle')
|
||||
|
||||
const file = new File(['data'], 'song.mp3', { type: 'audio/mpeg' })
|
||||
|
||||
// All fields filled + idle → true
|
||||
expect(canSubmit('Artist', 'Title', file, file, 'idle')).toBe(true)
|
||||
|
||||
// Missing artist → false
|
||||
expect(canSubmit('', 'Title', file, file, 'idle')).toBe(false)
|
||||
|
||||
// Whitespace-only artist → false
|
||||
expect(canSubmit(' ', 'Title', file, file, 'idle')).toBe(false)
|
||||
|
||||
// Missing title → false
|
||||
expect(canSubmit('Artist', '', file, file, 'idle')).toBe(false)
|
||||
|
||||
// Missing mixed file → false
|
||||
expect(canSubmit('Artist', 'Title', null, file, 'idle')).toBe(false)
|
||||
|
||||
// Missing instrumental file → false
|
||||
expect(canSubmit('Artist', 'Title', file, null, 'idle')).toBe(false)
|
||||
|
||||
// Submitting phase → false
|
||||
expect(canSubmit('Artist', 'Title', file, file, 'creating')).toBe(false)
|
||||
expect(canSubmit('Artist', 'Title', file, file, 'uploading-mixed')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Component interface tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('TenantJobFlow — component interface', () => {
|
||||
it('exports TenantJobFlow as a named export', async () => {
|
||||
const mod = await import('@/components/job/TenantJobFlow')
|
||||
expect(typeof mod.TenantJobFlow).toBe('function')
|
||||
})
|
||||
})
|
||||
@@ -20,12 +20,15 @@ import { sortJobsByDate, getDisplayJobs } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
import { TenantJobFlow } from "@/components/job/TenantJobFlow"
|
||||
import { TenantLogo } from "@/components/tenant-logo"
|
||||
import { AuthStatus } from "@/components/auth"
|
||||
import { AutoProcessor } from "@/components/AutoProcessor"
|
||||
import { VersionFooter } from "@/components/version-footer"
|
||||
import { PushNotificationPrompt } from "@/components/push-notification-prompt"
|
||||
import { FeedbackDialog } from "@/components/feedback/FeedbackDialog"
|
||||
import { useTheme } from "@/lib/theme"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
@@ -52,6 +55,7 @@ function AppPageContent() {
|
||||
const adminTokenHandled = useRef(false) // Track if admin_token was already processed
|
||||
const { isDarkMode, toggleTheme, mounted } = useTheme()
|
||||
const { user, fetchUser, verifyMagicLink } = useAuth()
|
||||
const { isDefault: isDefaultTenant, branding } = useTenant()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [jobLimit, setJobLimit] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 10
|
||||
@@ -201,9 +205,15 @@ function AppPageContent() {
|
||||
<header className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
|
||||
<div className="px-3 sm:px-4 py-2 sm:py-3 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 sm:gap-3 min-w-0">
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 sm:h-10 shrink-0" />
|
||||
{isDefaultTenant ? (
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 sm:h-10 shrink-0" />
|
||||
) : (
|
||||
<TenantLogo size="sm" />
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-base sm:text-xl font-bold truncate" style={{ color: 'var(--text)' }}>Karaoke Generator</h1>
|
||||
<h1 className="text-base sm:text-xl font-bold truncate" style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? "Karaoke Generator" : branding.site_title}
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
|
||||
@@ -311,8 +321,8 @@ function AppPageContent() {
|
||||
{/* Push notification prompt - shows once when appropriate */}
|
||||
<PushNotificationPrompt />
|
||||
|
||||
{/* Feedback-for-credits banner */}
|
||||
{user?.feedback_eligible && !feedbackBannerDismissed && (
|
||||
{/* Feedback-for-credits banner (consumer portal only) */}
|
||||
{isDefaultTenant && user?.feedback_eligible && !feedbackBannerDismissed && (
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border px-4 py-3"
|
||||
style={{
|
||||
borderColor: 'var(--accent)',
|
||||
@@ -352,13 +362,21 @@ function AppPageContent() {
|
||||
{/* Submit Job Card */}
|
||||
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
|
||||
<CardHeader>
|
||||
<CardTitle style={{ color: 'var(--text)' }}>Create Karaoke Video</CardTitle>
|
||||
<CardTitle style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? "Create Karaoke Video" : "Submit Track"}
|
||||
</CardTitle>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
Turn any song into a karaoke video with synced lyrics
|
||||
{isDefaultTenant
|
||||
? "Turn any song into a karaoke video with synced lyrics"
|
||||
: "Upload your mixed audio and instrumental"}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
{isDefaultTenant ? (
|
||||
<GuidedJobFlow onJobCreated={loadJobs} />
|
||||
) : (
|
||||
<TenantJobFlow onJobCreated={loadJobs} />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button"
|
||||
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
|
||||
import { SongInfoStep } from "./steps/SongInfoStep"
|
||||
import { AudioSourceStep } from "./steps/AudioSourceStep"
|
||||
import { VisibilityStep } from "./steps/VisibilityStep"
|
||||
import { CustomizeStep } from "./steps/CustomizeStep"
|
||||
import type { ColorOverrides } from "./steps/CustomizeStep"
|
||||
|
||||
@@ -16,9 +17,9 @@ interface GuidedJobFlowProps {
|
||||
onJobCreated: () => void
|
||||
}
|
||||
|
||||
type Step = 1 | 2 | 3
|
||||
type Step = 1 | 2 | 3 | 4
|
||||
|
||||
const STEP_LABELS = ["Song Info", "Choose Audio", "Customize & Create"]
|
||||
const STEP_LABELS = ["Song Info", "Choose Audio", "Visibility", "Customize & Create"]
|
||||
|
||||
/**
|
||||
* Upload custom style assets to an already-created job.
|
||||
@@ -75,7 +76,8 @@ async function uploadStyleAssets(
|
||||
|
||||
// Step 3: Finalize with uploaded file types + color overrides
|
||||
const uploadedFileTypes = filesToUpload.map((f) => f.file_type)
|
||||
const hasColorOverrides = colorOverrides.artist_color || colorOverrides.title_color
|
||||
const hasColorOverrides = colorOverrides.artist_color || colorOverrides.title_color ||
|
||||
colorOverrides.sung_lyrics_color || colorOverrides.unsung_lyrics_color
|
||||
await api.completeStyleUploads(
|
||||
jobId,
|
||||
uploadedFileTypes,
|
||||
@@ -163,7 +165,8 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
|
||||
// Upload style assets in the background (non-blocking)
|
||||
const hasStyleCustomizations = karaokeBackground || introBackground ||
|
||||
colorOverrides.artist_color || colorOverrides.title_color
|
||||
colorOverrides.artist_color || colorOverrides.title_color ||
|
||||
colorOverrides.sung_lyrics_color || colorOverrides.unsung_lyrics_color
|
||||
if (isPrivate && hasStyleCustomizations) {
|
||||
uploadStyleAssets(response.job_id, karaokeBackground, introBackground, colorOverrides)
|
||||
}
|
||||
@@ -435,6 +438,15 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<VisibilityStep
|
||||
isPrivate={isPrivate}
|
||||
onPrivateChange={setIsPrivate}
|
||||
onNext={() => setStep(4)}
|
||||
onBack={() => setStep(2)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 4 && (
|
||||
<CustomizeStep
|
||||
artist={artist}
|
||||
title={title}
|
||||
@@ -443,7 +455,6 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
onDisplayArtistChange={setDisplayArtist}
|
||||
onDisplayTitleChange={setDisplayTitle}
|
||||
isPrivate={isPrivate}
|
||||
onPrivateChange={setIsPrivate}
|
||||
karaokeBackground={karaokeBackground}
|
||||
onKaraokeBackgroundChange={setKaraokeBackground}
|
||||
introBackground={introBackground}
|
||||
@@ -451,7 +462,7 @@ export function GuidedJobFlow({ onJobCreated }: GuidedJobFlowProps) {
|
||||
colorOverrides={colorOverrides}
|
||||
onColorOverridesChange={setColorOverrides}
|
||||
onConfirm={handleConfirm}
|
||||
onBack={() => setStep(2)}
|
||||
onBack={() => setStep(3)}
|
||||
isSubmitting={isSubmitting}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -10,6 +10,7 @@ interface ImageUploadFieldProps {
|
||||
file: File | null
|
||||
onChange: (file: File | null) => void
|
||||
disabled?: boolean
|
||||
hidePreview?: boolean // Hide the image thumbnail (when a canvas preview is shown instead)
|
||||
}
|
||||
|
||||
const MAX_SIZE_BYTES = 10 * 1024 * 1024 // 10MB
|
||||
@@ -21,7 +22,7 @@ function formatFileSize(bytes: number): string {
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
export function ImageUploadField({ label, description, file, onChange, disabled }: ImageUploadFieldProps) {
|
||||
export function ImageUploadField({ label, description, file, onChange, disabled, hidePreview }: ImageUploadFieldProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const [dragOver, setDragOver] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -74,8 +75,8 @@ export function ImageUploadField({ label, description, file, onChange, disabled
|
||||
|
||||
{file ? (
|
||||
<div className="relative rounded-lg overflow-hidden border" style={{ borderColor: 'var(--card-border)' }}>
|
||||
{/* 16:9 preview thumbnail */}
|
||||
{previewUrl && (
|
||||
{/* 16:9 preview thumbnail (hidden when canvas preview is used instead) */}
|
||||
{!hidePreview && previewUrl && (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={previewUrl}
|
||||
|
||||
@@ -3,44 +3,65 @@
|
||||
import { useRef, useEffect, useCallback } from "react"
|
||||
|
||||
interface KaraokeBackgroundPreviewProps {
|
||||
backgroundUrl: string // Object URL from File
|
||||
backgroundUrl?: string // Object URL from File, or undefined for solid color
|
||||
backgroundColor?: string // Solid color hex (used when no backgroundUrl)
|
||||
sungColor?: string // Highlight color for sung lyrics
|
||||
unsungColor?: string // Color for unsung lyrics
|
||||
}
|
||||
|
||||
const CANVAS_W = 3840
|
||||
const CANVAS_H = 2160
|
||||
|
||||
// Sample lyrics to show how text looks over the background
|
||||
const SAMPLE_LINE_1 = "This is how your lyrics will look"
|
||||
const SAMPLE_LINE_2 = "over the background image"
|
||||
// 4 sample lines to match real karaoke video rendering
|
||||
const SAMPLE_LINES = [
|
||||
"Don't say that you don't understand",
|
||||
"This is California Babylon my man",
|
||||
"Don't say that you don't understand",
|
||||
"Don't say that you can't comprehend",
|
||||
]
|
||||
|
||||
// Default karaoke colors (matching Nomad theme)
|
||||
const SUNG_COLOR = "#7070F7"
|
||||
const UNSUNG_COLOR = "#ffffff"
|
||||
const DEFAULT_SUNG_COLOR = "#7070F7"
|
||||
const DEFAULT_UNSUNG_COLOR = "#ffffff"
|
||||
|
||||
export function KaraokeBackgroundPreview({ backgroundUrl }: KaraokeBackgroundPreviewProps) {
|
||||
export function KaraokeBackgroundPreview({
|
||||
backgroundUrl,
|
||||
backgroundColor,
|
||||
sungColor,
|
||||
unsungColor,
|
||||
}: KaraokeBackgroundPreviewProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
|
||||
const effectiveSungColor = sungColor || DEFAULT_SUNG_COLOR
|
||||
const effectiveUnsungColor = unsungColor || DEFAULT_UNSUNG_COLOR
|
||||
|
||||
const draw = useCallback(async () => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
|
||||
// Draw background
|
||||
try {
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const el = new Image()
|
||||
el.onload = () => resolve(el)
|
||||
el.onerror = reject
|
||||
el.src = backgroundUrl
|
||||
})
|
||||
ctx.drawImage(img, 0, 0, CANVAS_W, CANVAS_H)
|
||||
} catch {
|
||||
ctx.fillStyle = "#000000"
|
||||
// Draw background: custom image > solid color > default Nomad theme image
|
||||
const bgSrc = backgroundUrl || (backgroundColor ? null : "/karaoke-bg.png")
|
||||
if (bgSrc) {
|
||||
try {
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const el = new Image()
|
||||
el.onload = () => resolve(el)
|
||||
el.onerror = reject
|
||||
el.src = bgSrc
|
||||
})
|
||||
ctx.drawImage(img, 0, 0, CANVAS_W, CANVAS_H)
|
||||
} catch {
|
||||
ctx.fillStyle = backgroundColor || "#000000"
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
} else {
|
||||
ctx.fillStyle = backgroundColor || "#000000"
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
|
||||
// Draw sample lyrics in the lower third (where they typically appear)
|
||||
// Draw 4 lines of sample lyrics, vertically centered
|
||||
const fontSize = 120
|
||||
const fontFamily = "'Arial', 'Helvetica', sans-serif"
|
||||
ctx.font = `700 ${fontSize}px ${fontFamily}`
|
||||
@@ -48,34 +69,54 @@ export function KaraokeBackgroundPreview({ backgroundUrl }: KaraokeBackgroundPre
|
||||
ctx.textBaseline = "middle"
|
||||
|
||||
const centerX = CANVAS_W / 2
|
||||
const lineHeight = fontSize * 1.4
|
||||
const baseY = CANVAS_H * 0.75
|
||||
const lineHeight = fontSize * 1.5
|
||||
const totalHeight = lineHeight * SAMPLE_LINES.length
|
||||
const startY = (CANVAS_H - totalHeight) / 2 + lineHeight / 2
|
||||
|
||||
// Line 1: partially "sung" (first half highlighted)
|
||||
const words1 = SAMPLE_LINE_1.split(" ")
|
||||
const midPoint = Math.ceil(words1.length / 2)
|
||||
const sungPart = words1.slice(0, midPoint).join(" ")
|
||||
const unsungPart = " " + words1.slice(midPoint).join(" ")
|
||||
SAMPLE_LINES.forEach((line, i) => {
|
||||
const y = startY + i * lineHeight
|
||||
|
||||
// Measure widths for positioning
|
||||
const fullWidth1 = ctx.measureText(SAMPLE_LINE_1).width
|
||||
const sungWidth = ctx.measureText(sungPart).width
|
||||
const startX1 = centerX - fullWidth1 / 2
|
||||
if (i === 1) {
|
||||
// Line 2: partially "sung" — highlight first portion
|
||||
const words = line.split(" ")
|
||||
const midPoint = 3 // "This is Califor" split mid-word effect
|
||||
const sungText = words.slice(0, midPoint).join(" ")
|
||||
// Simulate mid-word highlight: "Califor" is partially sung
|
||||
const sungPart = sungText.slice(0, -2)
|
||||
const transitionChar = sungText.slice(-2)
|
||||
const unsungPart = words.slice(midPoint).join(" ")
|
||||
|
||||
// Draw sung portion
|
||||
ctx.fillStyle = SUNG_COLOR
|
||||
ctx.textAlign = "left"
|
||||
ctx.fillText(sungPart, startX1, baseY)
|
||||
const fullText = line
|
||||
const fullWidth = ctx.measureText(fullText).width
|
||||
const lineStartX = centerX - fullWidth / 2
|
||||
|
||||
// Draw unsung portion
|
||||
ctx.fillStyle = UNSUNG_COLOR
|
||||
ctx.fillText(unsungPart, startX1 + sungWidth, baseY)
|
||||
// Sung portion
|
||||
ctx.fillStyle = effectiveSungColor
|
||||
ctx.textAlign = "left"
|
||||
ctx.fillText(sungPart, lineStartX, y)
|
||||
|
||||
// Line 2: all unsung
|
||||
ctx.fillStyle = UNSUNG_COLOR
|
||||
ctx.textAlign = "center"
|
||||
ctx.fillText(SAMPLE_LINE_2, centerX, baseY + lineHeight)
|
||||
}, [backgroundUrl])
|
||||
// Transition characters (still sung color)
|
||||
const sungPartWidth = ctx.measureText(sungPart).width
|
||||
ctx.fillStyle = effectiveSungColor
|
||||
ctx.fillText(transitionChar, lineStartX + sungPartWidth, y)
|
||||
|
||||
// Unsung portion
|
||||
const transWidth = ctx.measureText(transitionChar).width
|
||||
ctx.fillStyle = effectiveUnsungColor
|
||||
ctx.fillText(" " + unsungPart, lineStartX + sungPartWidth + transWidth, y)
|
||||
|
||||
ctx.textAlign = "center"
|
||||
} else if (i === 0) {
|
||||
// Line 1: fully sung (already passed)
|
||||
ctx.fillStyle = effectiveSungColor
|
||||
ctx.fillText(line, centerX, y)
|
||||
} else {
|
||||
// Lines 3-4: unsung (upcoming)
|
||||
ctx.fillStyle = effectiveUnsungColor
|
||||
ctx.fillText(line, centerX, y)
|
||||
}
|
||||
})
|
||||
}, [backgroundUrl, backgroundColor, effectiveSungColor, effectiveUnsungColor])
|
||||
|
||||
useEffect(() => {
|
||||
draw()
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useRef, useCallback } from "react"
|
||||
import { api, ApiError } from "@/lib/api"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { CheckCircle2, Upload, Music, Loader2, AlertTriangle } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const ACCEPTED_AUDIO_TYPES = ".mp3,.wav,.flac,.m4a,.ogg,.aac"
|
||||
const ACCEPTED_AUDIO_MIMES = [
|
||||
"audio/mpeg", "audio/wav", "audio/x-wav", "audio/flac",
|
||||
"audio/mp4", "audio/m4a", "audio/ogg", "audio/aac",
|
||||
"application/octet-stream", // fallback for unrecognized
|
||||
]
|
||||
|
||||
interface TenantJobFlowProps {
|
||||
onJobCreated: () => void
|
||||
}
|
||||
|
||||
type SubmitPhase = "idle" | "creating" | "uploading-mixed" | "uploading-instrumental" | "completing" | "done"
|
||||
|
||||
export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) {
|
||||
const { branding } = useTenant()
|
||||
|
||||
// Form fields
|
||||
const [artist, setArtist] = useState("")
|
||||
const [title, setTitle] = useState("")
|
||||
const [mixedFile, setMixedFile] = useState<File | null>(null)
|
||||
const [instrumentalFile, setInstrumentalFile] = useState<File | null>(null)
|
||||
|
||||
// Submission state
|
||||
const [phase, setPhase] = useState<SubmitPhase>("idle")
|
||||
const [uploadProgress, setUploadProgress] = useState(0)
|
||||
const [error, setError] = useState("")
|
||||
const [jobId, setJobId] = useState<string | null>(null)
|
||||
|
||||
// Refs for file inputs
|
||||
const mixedInputRef = useRef<HTMLInputElement>(null)
|
||||
const instrumentalInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const canSubmit = artist.trim() && title.trim() && mixedFile && instrumentalFile && phase === "idle"
|
||||
|
||||
const resetFlow = useCallback(() => {
|
||||
setArtist("")
|
||||
setTitle("")
|
||||
setMixedFile(null)
|
||||
setInstrumentalFile(null)
|
||||
setPhase("idle")
|
||||
setUploadProgress(0)
|
||||
setError("")
|
||||
setJobId(null)
|
||||
// Clear file inputs
|
||||
if (mixedInputRef.current) mixedInputRef.current.value = ""
|
||||
if (instrumentalInputRef.current) instrumentalInputRef.current.value = ""
|
||||
}, [])
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!canSubmit || !mixedFile || !instrumentalFile) return
|
||||
|
||||
setError("")
|
||||
setPhase("creating")
|
||||
|
||||
try {
|
||||
// Step 1: Create job with upload URLs
|
||||
const files = [
|
||||
{
|
||||
filename: mixedFile.name,
|
||||
content_type: mixedFile.type || "application/octet-stream",
|
||||
file_type: "audio",
|
||||
},
|
||||
{
|
||||
filename: instrumentalFile.name,
|
||||
content_type: instrumentalFile.type || "application/octet-stream",
|
||||
file_type: "existing_instrumental",
|
||||
},
|
||||
]
|
||||
|
||||
const createResponse = await api.createJobWithUploadUrls(
|
||||
artist.trim(),
|
||||
title.trim(),
|
||||
files,
|
||||
{ is_private: true, existing_instrumental: true },
|
||||
)
|
||||
|
||||
setJobId(createResponse.job_id)
|
||||
|
||||
// Step 2: Upload mixed audio
|
||||
setPhase("uploading-mixed")
|
||||
const audioUrl = createResponse.upload_urls.find(u => u.file_type === "audio")
|
||||
if (!audioUrl) throw new ApiError("No upload URL for audio file", 500)
|
||||
|
||||
await api.uploadToSignedUrl(
|
||||
audioUrl.upload_url,
|
||||
mixedFile,
|
||||
audioUrl.content_type,
|
||||
(loaded, total) => setUploadProgress(Math.round((loaded / total) * 50)),
|
||||
)
|
||||
|
||||
// Step 3: Upload instrumental
|
||||
setPhase("uploading-instrumental")
|
||||
const instrumentalUrl = createResponse.upload_urls.find(u => u.file_type === "existing_instrumental")
|
||||
if (!instrumentalUrl) throw new ApiError("No upload URL for instrumental file", 500)
|
||||
|
||||
await api.uploadToSignedUrl(
|
||||
instrumentalUrl.upload_url,
|
||||
instrumentalFile,
|
||||
instrumentalUrl.content_type,
|
||||
(loaded, total) => setUploadProgress(50 + Math.round((loaded / total) * 50)),
|
||||
)
|
||||
|
||||
// Step 4: Complete upload
|
||||
setPhase("completing")
|
||||
await api.completeJobUpload(createResponse.job_id, ["audio", "existing_instrumental"])
|
||||
|
||||
setPhase("done")
|
||||
onJobCreated()
|
||||
} catch (err: any) {
|
||||
const message = err instanceof ApiError
|
||||
? err.message
|
||||
: "Something went wrong. Please try again."
|
||||
setError(message)
|
||||
setPhase("idle")
|
||||
setUploadProgress(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Success view
|
||||
if (phase === "done") {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex flex-col items-center text-center py-5 space-y-3">
|
||||
<div
|
||||
className="w-12 h-12 rounded-full flex items-center justify-center"
|
||||
style={{ backgroundColor: "rgba(34, 197, 94, 0.15)" }}
|
||||
>
|
||||
<CheckCircle2 className="w-7 h-7 text-green-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: "var(--text)" }}>
|
||||
Track Submitted
|
||||
</h2>
|
||||
<p className="text-sm mt-1" style={{ color: "var(--text-muted)" }}>
|
||||
<span className="font-medium" style={{ color: "var(--text)" }}>
|
||||
{artist} - {title}
|
||||
</span>
|
||||
</p>
|
||||
{jobId && (
|
||||
<p className="text-xs mt-0.5 font-mono" style={{ color: "var(--text-muted)" }} data-testid="created-job-id">
|
||||
ID: {jobId.slice(0, 8)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Timeline — simplified for tenant (no audio processing step) */}
|
||||
<p className="text-xs font-semibold uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>
|
||||
What happens next
|
||||
</p>
|
||||
<div className="space-y-0 mt-3">
|
||||
{/* Step 1: Lyrics transcription */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-blue-500/15">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-blue-400">
|
||||
<path d="M8 1.5a1.25 1.25 0 0 1 1.177.825l.573 1.608 1.608.573a1.25 1.25 0 0 1 0 2.354l-1.608.573-.573 1.608a1.25 1.25 0 0 1-2.354 0l-.573-1.608-1.608-.573a1.25 1.25 0 0 1 0-2.354l1.608-.573.573-1.608A1.25 1.25 0 0 1 8 1.5Z" fill="currentColor" opacity="0.85"/>
|
||||
<path d="M12 9a1 1 0 0 1 .94.66l.36 1.02 1.02.36a1 1 0 0 1 0 1.884l-1.02.36-.36 1.02a1 1 0 0 1-1.88 0l-.36-1.02-1.02-.36a1 1 0 0 1 0-1.884l1.02-.36.36-1.02A1 1 0 0 1 12 9Z" fill="currentColor" opacity="0.55"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: "var(--card-border)" }} />
|
||||
</div>
|
||||
<div className="pb-4 pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Lyrics transcription</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
|
||||
We transcribe and sync lyrics from your audio. <span className="font-medium" style={{ color: "var(--text)" }}>~5 minutes</span>
|
||||
</p>
|
||||
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-blue-500/15 text-blue-400">
|
||||
Automatic
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step 2: User review */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: "rgba(255, 122, 204, 0.15)" }}>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ color: "var(--brand-pink)" }}>
|
||||
<path d="M8 2a3 3 0 1 0 0 6 3 3 0 0 0 0-6ZM3.5 13.5c0-2.485 2.015-4.5 4.5-4.5s4.5 2.015 4.5 4.5a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5Z" fill="currentColor" opacity="0.85"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: "var(--card-border)" }} />
|
||||
</div>
|
||||
<div className="pb-4 pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Review lyrics</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
|
||||
Check the synced lyrics and fix any errors.
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
|
||||
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: "rgba(255, 122, 204, 0.15)", color: "var(--brand-pink)" }}>
|
||||
You
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-[10px]" style={{ color: "var(--text-muted)" }}>
|
||||
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
|
||||
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
|
||||
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
|
||||
</svg>
|
||||
Email when ready
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step 3: Video delivered */}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-green-500/15">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-green-400">
|
||||
<path d="M3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v11a.5.5 0 0 1-.765.424L8 11.28l-4.235 2.644A.5.5 0 0 1 3 13.5v-11Z" fill="currentColor" opacity="0.5"/>
|
||||
<path d="M6.354 7.854 7.5 9l2.146-2.146a.5.5 0 0 0-.708-.708L7.5 7.586l-.646-.647a.5.5 0 1 0-.708.708l.208.207Z" fill="currentColor"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pt-1">
|
||||
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Video delivered</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
|
||||
After approval, your karaoke video is rendered and delivered. <span className="font-medium" style={{ color: "var(--text)" }}>~10 minutes</span>
|
||||
</p>
|
||||
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-green-500/15 text-green-400">
|
||||
Automatic
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-[10px] text-center" style={{ color: "var(--text-muted)" }}>
|
||||
Track progress in the <span className="font-medium" style={{ color: "var(--text)" }}>Recent Jobs</span> list.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={resetFlow}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
style={{ borderColor: "var(--card-border)", color: "var(--text)" }}
|
||||
>
|
||||
<Music className="w-4 h-4 mr-2" />
|
||||
Submit Another Track
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const isSubmitting = phase !== "idle"
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Artist */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="tenant-artist" style={{ color: "var(--text)" }}>Artist</Label>
|
||||
<Input
|
||||
id="tenant-artist"
|
||||
placeholder="e.g. Adele"
|
||||
value={artist}
|
||||
onChange={e => setArtist(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
style={{ borderColor: "var(--card-border)", color: "var(--text)", backgroundColor: "var(--input)" }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="tenant-title" style={{ color: "var(--text)" }}>Title</Label>
|
||||
<Input
|
||||
id="tenant-title"
|
||||
placeholder="e.g. Someone Like You"
|
||||
value={title}
|
||||
onChange={e => setTitle(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
style={{ borderColor: "var(--card-border)", color: "var(--text)", backgroundColor: "var(--input)" }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Mixed Audio */}
|
||||
<FileDropZone
|
||||
id="tenant-mixed-audio"
|
||||
label="Mixed Audio"
|
||||
hint="The full song with vocals"
|
||||
file={mixedFile}
|
||||
onFileSelect={setMixedFile}
|
||||
inputRef={mixedInputRef}
|
||||
disabled={isSubmitting}
|
||||
accept={ACCEPTED_AUDIO_TYPES}
|
||||
/>
|
||||
|
||||
{/* Instrumental Audio */}
|
||||
<FileDropZone
|
||||
id="tenant-instrumental-audio"
|
||||
label="Instrumental Audio"
|
||||
hint="The instrumental (backing track)"
|
||||
file={instrumentalFile}
|
||||
onFileSelect={setInstrumentalFile}
|
||||
inputRef={instrumentalInputRef}
|
||||
disabled={isSubmitting}
|
||||
accept={ACCEPTED_AUDIO_TYPES}
|
||||
/>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="flex items-start gap-2 text-sm p-3 rounded-lg" style={{ backgroundColor: "rgba(239, 68, 68, 0.1)", color: "#ef4444" }}>
|
||||
<AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Progress */}
|
||||
{isSubmitting && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<span>
|
||||
{phase === "creating" && "Creating job..."}
|
||||
{phase === "uploading-mixed" && "Uploading mixed audio..."}
|
||||
{phase === "uploading-instrumental" && "Uploading instrumental..."}
|
||||
{phase === "completing" && "Finalizing..."}
|
||||
</span>
|
||||
</div>
|
||||
{(phase === "uploading-mixed" || phase === "uploading-instrumental") && (
|
||||
<div className="w-full h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: "var(--card-border)" }}>
|
||||
<div
|
||||
className="h-full rounded-full transition-all duration-300"
|
||||
style={{
|
||||
width: `${uploadProgress}%`,
|
||||
backgroundColor: "var(--tenant-primary, var(--brand-pink))",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Submit */}
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!canSubmit}
|
||||
className="w-full"
|
||||
style={{
|
||||
backgroundColor: canSubmit ? "var(--tenant-primary, var(--brand-pink))" : undefined,
|
||||
color: canSubmit ? "white" : undefined,
|
||||
}}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Submit Track
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// File drop zone sub-component
|
||||
// ============================================================================
|
||||
|
||||
interface FileDropZoneProps {
|
||||
id: string
|
||||
label: string
|
||||
hint: string
|
||||
file: File | null
|
||||
onFileSelect: (file: File | null) => void
|
||||
inputRef: React.RefObject<HTMLInputElement | null>
|
||||
disabled: boolean
|
||||
accept: string
|
||||
}
|
||||
|
||||
function FileDropZone({ id, label, hint, file, onFileSelect, inputRef, disabled, accept }: FileDropZoneProps) {
|
||||
const [isDragOver, setIsDragOver] = useState(false)
|
||||
|
||||
function handleDrop(e: React.DragEvent) {
|
||||
e.preventDefault()
|
||||
setIsDragOver(false)
|
||||
if (disabled) return
|
||||
const droppedFile = e.dataTransfer.files[0]
|
||||
if (droppedFile) onFileSelect(droppedFile)
|
||||
}
|
||||
|
||||
function handleDragOver(e: React.DragEvent) {
|
||||
e.preventDefault()
|
||||
if (!disabled) setIsDragOver(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={id} style={{ color: "var(--text)" }}>{label}</Label>
|
||||
<div
|
||||
className={`relative border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors ${
|
||||
disabled ? "opacity-50 cursor-not-allowed" : "hover:border-white/30"
|
||||
}`}
|
||||
style={{
|
||||
borderColor: isDragOver ? "var(--tenant-primary, var(--brand-pink))" : "var(--card-border)",
|
||||
backgroundColor: isDragOver ? "rgba(255, 255, 255, 0.03)" : "transparent",
|
||||
}}
|
||||
onClick={() => !disabled && inputRef.current?.click()}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={() => setIsDragOver(false)}
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
id={id}
|
||||
type="file"
|
||||
accept={accept}
|
||||
className="hidden"
|
||||
disabled={disabled}
|
||||
onChange={e => {
|
||||
const f = e.target.files?.[0]
|
||||
if (f) onFileSelect(f)
|
||||
}}
|
||||
/>
|
||||
{file ? (
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Music className="w-4 h-4 shrink-0" style={{ color: "var(--tenant-primary, var(--brand-pink))" }} />
|
||||
<span className="text-sm truncate" style={{ color: "var(--text)" }}>{file.name}</span>
|
||||
<span className="text-xs shrink-0" style={{ color: "var(--text-muted)" }}>
|
||||
({(file.size / (1024 * 1024)).toFixed(1)} MB)
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<Upload className="w-5 h-5 mx-auto mb-1" style={{ color: "var(--text-muted)" }} />
|
||||
<p className="text-sm" style={{ color: "var(--text-muted)" }}>
|
||||
Drop file here or <span style={{ color: "var(--tenant-primary, var(--brand-pink))" }}>browse</span>
|
||||
</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>{hint}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ interface TitleCardPreviewProps {
|
||||
artist: string
|
||||
title: string
|
||||
customBackgroundUrl?: string // Object URL from File for custom background
|
||||
backgroundColor?: string // Solid color hex (used when no customBackgroundUrl)
|
||||
titleColor?: string // Hex color override (default #ffffff)
|
||||
artistColor?: string // Hex color override (default #ffdf6b)
|
||||
}
|
||||
@@ -121,7 +122,7 @@ function drawTextBlock(
|
||||
}
|
||||
}
|
||||
|
||||
export function TitleCardPreview({ artist, title, customBackgroundUrl, titleColor, artistColor }: TitleCardPreviewProps) {
|
||||
export function TitleCardPreview({ artist, title, customBackgroundUrl, backgroundColor, titleColor, artistColor }: TitleCardPreviewProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
|
||||
const effectiveTitleColor = titleColor || TITLE_COLOR
|
||||
@@ -133,7 +134,7 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, titleColo
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
|
||||
// Draw background image (custom or default)
|
||||
// Draw background: custom image > solid color > default image
|
||||
try {
|
||||
if (customBackgroundUrl) {
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
@@ -143,12 +144,15 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, titleColo
|
||||
el.src = customBackgroundUrl
|
||||
})
|
||||
ctx.drawImage(img, 0, 0, CANVAS_W, CANVAS_H)
|
||||
} else if (backgroundColor) {
|
||||
ctx.fillStyle = backgroundColor
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
} else {
|
||||
const bgImg = await loadBgImage()
|
||||
ctx.drawImage(bgImg, 0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
} catch {
|
||||
ctx.fillStyle = "#000000"
|
||||
ctx.fillStyle = backgroundColor || "#000000"
|
||||
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
|
||||
}
|
||||
|
||||
@@ -188,7 +192,7 @@ export function TitleCardPreview({ artist, title, customBackgroundUrl, titleColo
|
||||
artist ? effectiveArtistColor : "rgba(255,223,107,0.25)",
|
||||
fontFamily,
|
||||
)
|
||||
}, [artist, title, customBackgroundUrl, effectiveTitleColor, effectiveArtistColor])
|
||||
}, [artist, title, customBackgroundUrl, backgroundColor, effectiveTitleColor, effectiveArtistColor])
|
||||
|
||||
useEffect(() => {
|
||||
draw()
|
||||
|
||||
@@ -3,39 +3,46 @@ import { CustomizeStep } from "../steps/CustomizeStep"
|
||||
|
||||
// Mock canvas-based components — they require browser APIs not available in jsdom
|
||||
jest.mock("../TitleCardPreview", () => ({
|
||||
TitleCardPreview: ({ artist, title, customBackgroundUrl, titleColor, artistColor }: any) => (
|
||||
TitleCardPreview: ({ artist, title, customBackgroundUrl, titleColor, artistColor, backgroundColor }: any) => (
|
||||
<div data-testid="title-card-preview"
|
||||
data-artist={artist}
|
||||
data-title={title}
|
||||
data-custom-bg={customBackgroundUrl || ""}
|
||||
data-title-color={titleColor || ""}
|
||||
data-artist-color={artistColor || ""}
|
||||
data-bg-color={backgroundColor || ""}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
|
||||
jest.mock("../KaraokeBackgroundPreview", () => ({
|
||||
KaraokeBackgroundPreview: ({ backgroundUrl }: any) => (
|
||||
<div data-testid="karaoke-bg-preview" data-url={backgroundUrl} />
|
||||
KaraokeBackgroundPreview: ({ backgroundUrl, backgroundColor, sungColor, unsungColor }: any) => (
|
||||
<div data-testid="karaoke-bg-preview"
|
||||
data-url={backgroundUrl || ""}
|
||||
data-bg-color={backgroundColor || ""}
|
||||
data-sung-color={sungColor || ""}
|
||||
data-unsung-color={unsungColor || ""}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
|
||||
jest.mock("../ImageUploadField", () => ({
|
||||
ImageUploadField: ({ label, file, onChange, disabled }: any) => (
|
||||
<div data-testid={`upload-${label.replace(/\s+/g, "-").toLowerCase()}`}>
|
||||
<span>{label}</span>
|
||||
ImageUploadField: ({ label, description, file, onChange, disabled, hidePreview }: any) => (
|
||||
<div data-testid={`upload-${(label || description || "field").replace(/\s+/g, "-").toLowerCase().slice(0, 30)}`}>
|
||||
{label && <span>{label}</span>}
|
||||
{description && <span>{description}</span>}
|
||||
{file && <span data-testid="file-name">{file.name}</span>}
|
||||
<button data-testid={`upload-btn-${label.replace(/\s+/g, "-").toLowerCase()}`}
|
||||
<button
|
||||
data-testid={`upload-btn`}
|
||||
onClick={() => onChange(new File(["data"], "test.png", { type: "image/png" }))}
|
||||
disabled={disabled}
|
||||
>
|
||||
Upload
|
||||
</button>
|
||||
<button data-testid={`clear-btn-${label.replace(/\s+/g, "-").toLowerCase()}`}
|
||||
onClick={() => onChange(null)}
|
||||
>
|
||||
<button data-testid={`clear-btn`} onClick={() => onChange(null)}>
|
||||
Clear
|
||||
</button>
|
||||
{hidePreview && <span data-testid="hide-preview" />}
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
@@ -48,7 +55,6 @@ const defaultProps = {
|
||||
onDisplayArtistChange: jest.fn(),
|
||||
onDisplayTitleChange: jest.fn(),
|
||||
isPrivate: false,
|
||||
onPrivateChange: jest.fn(),
|
||||
karaokeBackground: null as File | null,
|
||||
onKaraokeBackgroundChange: jest.fn(),
|
||||
introBackground: null as File | null,
|
||||
@@ -63,93 +69,139 @@ const defaultProps = {
|
||||
describe("CustomizeStep", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
// Mock URL.createObjectURL for the component's useMemo
|
||||
global.URL.createObjectURL = jest.fn(() => "blob:mock")
|
||||
global.URL.revokeObjectURL = jest.fn()
|
||||
})
|
||||
|
||||
it("renders title card preview with artist and title", () => {
|
||||
describe("public mode (isPrivate=false)", () => {
|
||||
it("shows title card preview and display fields, but no style options", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} />)
|
||||
|
||||
// Display override fields are shown
|
||||
expect(screen.getByLabelText(/Title Card Artist/)).toBeInTheDocument()
|
||||
expect(screen.getByLabelText(/Title Card Title/)).toBeInTheDocument()
|
||||
|
||||
// Title card preview is shown
|
||||
expect(screen.getByTestId("title-card-preview")).toBeInTheDocument()
|
||||
|
||||
// No style customization or karaoke preview
|
||||
expect(screen.queryByText("Custom Video Style")).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId("karaoke-bg-preview")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("calls onConfirm when create button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} />)
|
||||
|
||||
fireEvent.click(screen.getByText("Create Karaoke Video"))
|
||||
expect(defaultProps.onConfirm).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("shows loading state when isSubmitting", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} isSubmitting={true} />)
|
||||
expect(screen.getByText("Creating...")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe("private mode (isPrivate=true)", () => {
|
||||
it("shows custom video style section with side-by-side previews", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
expect(screen.getByText("Custom Video Style")).toBeInTheDocument()
|
||||
expect(screen.getByTestId("title-card-preview")).toBeInTheDocument()
|
||||
expect(screen.getByTestId("karaoke-bg-preview")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("renders title card preview with artist and title", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist")).toBe("Test Artist")
|
||||
expect(preview.getAttribute("data-title")).toBe("Test Song")
|
||||
})
|
||||
|
||||
it("uses displayArtist/displayTitle in preview when provided", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
displayArtist="Custom Artist"
|
||||
displayTitle="Custom Title"
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist")).toBe("Custom Artist")
|
||||
expect(preview.getAttribute("data-title")).toBe("Custom Title")
|
||||
})
|
||||
|
||||
it("shows color pickers for title card and lyrics", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
expect(screen.getByText("Artist Color")).toBeInTheDocument()
|
||||
expect(screen.getByText("Title Color")).toBeInTheDocument()
|
||||
expect(screen.getByText("Highlight Color")).toBeInTheDocument()
|
||||
expect(screen.getByText("Lyrics Color")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("passes color overrides to title card preview", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
colorOverrides={{ artist_color: "#ff0000", title_color: "#00ff00" }}
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist-color")).toBe("#ff0000")
|
||||
expect(preview.getAttribute("data-title-color")).toBe("#00ff00")
|
||||
})
|
||||
|
||||
it("passes lyrics color overrides to karaoke preview", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
colorOverrides={{ sung_lyrics_color: "#ff0000", unsung_lyrics_color: "#00ff00" }}
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("karaoke-bg-preview")
|
||||
expect(preview.getAttribute("data-sung-color")).toBe("#ff0000")
|
||||
expect(preview.getAttribute("data-unsung-color")).toBe("#00ff00")
|
||||
})
|
||||
|
||||
it("shows background mode toggles", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
// Two sets of Default/Image/Color toggles (one per canvas)
|
||||
const defaultBtns = screen.getAllByText("Default")
|
||||
const imageBtns = screen.getAllByText("Image")
|
||||
const colorBtns = screen.getAllByText("Color")
|
||||
|
||||
expect(defaultBtns).toHaveLength(2)
|
||||
expect(imageBtns).toHaveLength(2)
|
||||
expect(colorBtns).toHaveLength(2)
|
||||
})
|
||||
|
||||
it("calls onConfirm when create button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
fireEvent.click(screen.getByText("Create Karaoke Video"))
|
||||
expect(defaultProps.onConfirm).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("shows loading state when isSubmitting", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} isSubmitting={true} />)
|
||||
expect(screen.getByText("Creating...")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("calls onBack when back button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} />)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview).toBeInTheDocument()
|
||||
expect(preview.getAttribute("data-artist")).toBe("Test Artist")
|
||||
expect(preview.getAttribute("data-title")).toBe("Test Song")
|
||||
})
|
||||
|
||||
it("uses displayArtist/displayTitle in preview when provided", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
displayArtist="Custom Artist"
|
||||
displayTitle="Custom Title"
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist")).toBe("Custom Artist")
|
||||
expect(preview.getAttribute("data-title")).toBe("Custom Title")
|
||||
})
|
||||
|
||||
it("does NOT show custom video style section when isPrivate is false", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} />)
|
||||
|
||||
expect(screen.queryByText("Custom Video Style")).not.toBeInTheDocument()
|
||||
expect(screen.queryByText("Karaoke Background")).not.toBeInTheDocument()
|
||||
expect(screen.queryByText("Title Card Background")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows custom video style section when isPrivate is true", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
expect(screen.getByText("Custom Video Style")).toBeInTheDocument()
|
||||
expect(screen.getByText("Karaoke Background")).toBeInTheDocument()
|
||||
expect(screen.getByText("Title Card Background")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("shows color pickers when isPrivate is true", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={true} />)
|
||||
|
||||
expect(screen.getByText("Artist Color")).toBeInTheDocument()
|
||||
expect(screen.getByText("Title Color")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("passes color overrides to title card preview", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
colorOverrides={{ artist_color: "#ff0000", title_color: "#00ff00" }}
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
expect(preview.getAttribute("data-artist-color")).toBe("#ff0000")
|
||||
expect(preview.getAttribute("data-title-color")).toBe("#00ff00")
|
||||
})
|
||||
|
||||
it("toggles private checkbox and triggers onPrivateChange", () => {
|
||||
render(<CustomizeStep {...defaultProps} isPrivate={false} />)
|
||||
|
||||
const checkbox = screen.getByRole("checkbox")
|
||||
fireEvent.click(checkbox)
|
||||
|
||||
expect(defaultProps.onPrivateChange).toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it("calls onConfirm when create button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} />)
|
||||
|
||||
const button = screen.getByText("Create Karaoke Video")
|
||||
fireEvent.click(button)
|
||||
|
||||
expect(defaultProps.onConfirm).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("shows loading state when isSubmitting", () => {
|
||||
render(<CustomizeStep {...defaultProps} isSubmitting={true} />)
|
||||
|
||||
expect(screen.getByText("Creating...")).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByText("Back"))
|
||||
expect(defaultProps.onBack).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("disables form controls when isSubmitting", () => {
|
||||
@@ -158,55 +210,4 @@ describe("CustomizeStep", () => {
|
||||
const createBtn = screen.getByText("Creating...").closest("button")
|
||||
expect(createBtn).toBeDisabled()
|
||||
})
|
||||
|
||||
it("calls onBack when back button is clicked", () => {
|
||||
render(<CustomizeStep {...defaultProps} />)
|
||||
|
||||
const backBtn = screen.getByText("Back")
|
||||
fireEvent.click(backBtn)
|
||||
|
||||
expect(defaultProps.onBack).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("shows karaoke background preview when file is provided and isPrivate", () => {
|
||||
const file = new File(["data"], "karaoke-bg.png", { type: "image/png" })
|
||||
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
karaokeBackground={file}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByTestId("karaoke-bg-preview")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("does NOT show karaoke background preview when no file", () => {
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
karaokeBackground={null}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByTestId("karaoke-bg-preview")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("passes custom intro background to title card preview", () => {
|
||||
const file = new File(["data"], "intro-bg.png", { type: "image/png" })
|
||||
|
||||
render(
|
||||
<CustomizeStep
|
||||
{...defaultProps}
|
||||
isPrivate={true}
|
||||
introBackground={file}
|
||||
/>
|
||||
)
|
||||
|
||||
const preview = screen.getByTestId("title-card-preview")
|
||||
// Should have a blob URL for the custom background
|
||||
expect(preview.getAttribute("data-custom-bg")).toBe("blob:mock")
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useRef } from "react"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { ArrowLeft, Loader2, Palette } from "lucide-react"
|
||||
import { ArrowLeft, Loader2, Palette, Image as ImageIcon, Paintbrush } from "lucide-react"
|
||||
import { TitleCardPreview } from "../TitleCardPreview"
|
||||
import { KaraokeBackgroundPreview } from "../KaraokeBackgroundPreview"
|
||||
import { ImageUploadField } from "../ImageUploadField"
|
||||
@@ -12,6 +12,8 @@ import { ImageUploadField } from "../ImageUploadField"
|
||||
export interface ColorOverrides {
|
||||
artist_color?: string
|
||||
title_color?: string
|
||||
sung_lyrics_color?: string
|
||||
unsung_lyrics_color?: string
|
||||
}
|
||||
|
||||
interface CustomizeStepProps {
|
||||
@@ -22,7 +24,6 @@ interface CustomizeStepProps {
|
||||
onDisplayArtistChange: (value: string) => void
|
||||
onDisplayTitleChange: (value: string) => void
|
||||
isPrivate: boolean
|
||||
onPrivateChange: (value: boolean) => void
|
||||
karaokeBackground: File | null
|
||||
onKaraokeBackgroundChange: (file: File | null) => void
|
||||
introBackground: File | null
|
||||
@@ -35,6 +36,163 @@ interface CustomizeStepProps {
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
// Preset colors for solid backgrounds
|
||||
const BG_PRESETS = [
|
||||
{ label: "Black", color: "#000000" },
|
||||
{ label: "Dark Blue", color: "#1a1a2e" },
|
||||
{ label: "Dark Purple", color: "#16213e" },
|
||||
{ label: "Green Screen", color: "#00b140" },
|
||||
{ label: "White", color: "#ffffff" },
|
||||
]
|
||||
|
||||
type BgMode = "default" | "image" | "solid"
|
||||
|
||||
/**
|
||||
* Generate a tiny 4x4 solid color PNG blob for uploading as a background.
|
||||
* The backend expects an image file, so we create one client-side.
|
||||
*/
|
||||
function generateSolidColorBlob(hexColor: string): Promise<File> {
|
||||
return new Promise((resolve) => {
|
||||
const canvas = document.createElement("canvas")
|
||||
canvas.width = 4
|
||||
canvas.height = 4
|
||||
const ctx = canvas.getContext("2d")!
|
||||
ctx.fillStyle = hexColor
|
||||
ctx.fillRect(0, 0, 4, 4)
|
||||
canvas.toBlob((blob) => {
|
||||
resolve(new File([blob!], `solid-${hexColor.replace('#', '')}.png`, { type: "image/png" }))
|
||||
}, "image/png")
|
||||
})
|
||||
}
|
||||
|
||||
function ColorPickerField({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
defaultColor,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
id: string
|
||||
label: string
|
||||
value?: string
|
||||
defaultColor: string
|
||||
onChange: (val: string | undefined) => void
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={id} className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
{label}
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
id={id}
|
||||
value={value || defaultColor}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={disabled}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={value || ""}
|
||||
placeholder={defaultColor}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (val === "" || /^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
onChange(val || undefined)
|
||||
}
|
||||
}}
|
||||
disabled={disabled}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ColorPresetButtons({
|
||||
presets,
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
presets: typeof BG_PRESETS
|
||||
value?: string
|
||||
onChange: (color: string) => void
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{presets.map((preset) => (
|
||||
<button
|
||||
key={preset.color}
|
||||
type="button"
|
||||
onClick={() => onChange(preset.color)}
|
||||
disabled={disabled}
|
||||
className={`flex items-center gap-1.5 px-2 py-1 rounded-md border text-[10px] transition-colors ${
|
||||
value === preset.color
|
||||
? 'border-[var(--brand-pink)]'
|
||||
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
|
||||
}`}
|
||||
style={{ backgroundColor: 'var(--secondary)' }}
|
||||
title={preset.label}
|
||||
>
|
||||
<span
|
||||
className="w-3 h-3 rounded-sm border shrink-0"
|
||||
style={{
|
||||
backgroundColor: preset.color,
|
||||
borderColor: preset.color === "#000000" ? 'var(--card-border)' : preset.color,
|
||||
}}
|
||||
/>
|
||||
<span style={{ color: 'var(--text-muted)' }}>{preset.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BgModeToggle({
|
||||
mode,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
mode: BgMode
|
||||
onChange: (mode: BgMode) => void
|
||||
disabled?: boolean
|
||||
}) {
|
||||
const options: { value: BgMode; label: string; icon: React.ReactNode }[] = [
|
||||
{ value: "default", label: "Default", icon: null },
|
||||
{ value: "image", label: "Image", icon: <ImageIcon className="w-3 h-3" /> },
|
||||
{ value: "solid", label: "Color", icon: <Paintbrush className="w-3 h-3" /> },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex rounded-md border overflow-hidden" style={{ borderColor: 'var(--card-border)' }}>
|
||||
{options.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => onChange(opt.value)}
|
||||
disabled={disabled}
|
||||
className={`flex items-center gap-1 px-2.5 py-1 text-[10px] font-medium transition-colors ${
|
||||
mode === opt.value ? 'text-white' : ''
|
||||
}`}
|
||||
style={{
|
||||
backgroundColor: mode === opt.value ? 'var(--brand-pink)' : 'var(--secondary)',
|
||||
color: mode === opt.value ? 'white' : 'var(--text-muted)',
|
||||
}}
|
||||
>
|
||||
{opt.icon}
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CustomizeStep({
|
||||
artist,
|
||||
title,
|
||||
@@ -43,7 +201,6 @@ export function CustomizeStep({
|
||||
onDisplayArtistChange,
|
||||
onDisplayTitleChange,
|
||||
isPrivate,
|
||||
onPrivateChange,
|
||||
karaokeBackground,
|
||||
onKaraokeBackgroundChange,
|
||||
introBackground,
|
||||
@@ -55,13 +212,22 @@ export function CustomizeStep({
|
||||
isSubmitting,
|
||||
disabled,
|
||||
}: CustomizeStepProps) {
|
||||
// The displayed artist/title on the title card
|
||||
const previewArtist = displayArtist.trim() || artist
|
||||
const previewTitle = displayTitle.trim() || title
|
||||
|
||||
// Background mode state (private only)
|
||||
const [karaokeBgMode, setKaraokeBgMode] = useState<BgMode>(
|
||||
karaokeBackground ? "image" : "default"
|
||||
)
|
||||
const [introBgMode, setIntroBgMode] = useState<BgMode>(
|
||||
introBackground ? "image" : "default"
|
||||
)
|
||||
const [karaokeSolidColor, setKaraokeSolidColor] = useState("#000000")
|
||||
const [introSolidColor, setIntroSolidColor] = useState("#000000")
|
||||
|
||||
// Create stable object URLs for previews and revoke on cleanup
|
||||
const prevKaraokeBlobUrl = useRef<string>()
|
||||
const prevIntroBlobUrl = useRef<string>()
|
||||
const prevKaraokeBlobUrl = useRef<string | undefined>(undefined)
|
||||
const prevIntroBlobUrl = useRef<string | undefined>(undefined)
|
||||
|
||||
const karaokeBackgroundUrl = useMemo(
|
||||
() => karaokeBackground ? URL.createObjectURL(karaokeBackground) : undefined,
|
||||
@@ -88,6 +254,129 @@ export function CustomizeStep({
|
||||
return () => { if (introBackgroundUrl) URL.revokeObjectURL(introBackgroundUrl) }
|
||||
}, [introBackgroundUrl])
|
||||
|
||||
// When switching background modes, update the file state accordingly
|
||||
function handleKaraokeBgModeChange(mode: BgMode) {
|
||||
setKaraokeBgMode(mode)
|
||||
if (mode === "default" || mode === "solid") {
|
||||
onKaraokeBackgroundChange(null)
|
||||
}
|
||||
if (mode === "solid") {
|
||||
// Generate solid color blob
|
||||
generateSolidColorBlob(karaokeSolidColor).then(onKaraokeBackgroundChange)
|
||||
}
|
||||
}
|
||||
|
||||
function handleIntroBgModeChange(mode: BgMode) {
|
||||
setIntroBgMode(mode)
|
||||
if (mode === "default" || mode === "solid") {
|
||||
onIntroBackgroundChange(null)
|
||||
}
|
||||
if (mode === "solid") {
|
||||
generateSolidColorBlob(introSolidColor).then(onIntroBackgroundChange)
|
||||
}
|
||||
}
|
||||
|
||||
function handleKaraokeSolidColorChange(color: string) {
|
||||
setKaraokeSolidColor(color)
|
||||
generateSolidColorBlob(color).then(onKaraokeBackgroundChange)
|
||||
}
|
||||
|
||||
function handleIntroSolidColorChange(color: string) {
|
||||
setIntroSolidColor(color)
|
||||
generateSolidColorBlob(color).then(onIntroBackgroundChange)
|
||||
}
|
||||
|
||||
// === PUBLIC MODE: Simple layout ===
|
||||
if (!isPrivate) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Customize & Create
|
||||
</h2>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Confirm the artist and title for your title card.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
disabled={disabled || isSubmitting}
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Title card preview */}
|
||||
<div className="mx-auto w-full sm:w-2/3">
|
||||
<TitleCardPreview
|
||||
artist={previewArtist}
|
||||
title={previewTitle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Display override fields */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="guided-display-artist" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Card Artist
|
||||
{!displayArtist.trim() && artist.trim() && (
|
||||
<span className="ml-1 opacity-50">(same as above)</span>
|
||||
)}
|
||||
</Label>
|
||||
<Input
|
||||
id="guided-display-artist"
|
||||
placeholder={artist || "Artist on title card"}
|
||||
value={displayArtist}
|
||||
onChange={(e) => onDisplayArtistChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="guided-display-title" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Card Title
|
||||
{!displayTitle.trim() && title.trim() && (
|
||||
<span className="ml-1 opacity-50">(same as above)</span>
|
||||
)}
|
||||
</Label>
|
||||
<Input
|
||||
id="guided-display-title"
|
||||
placeholder={title || "Title on title card"}
|
||||
value={displayTitle}
|
||||
onChange={(e) => onDisplayTitleChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
These default to your search values. Override for soundtracks, covers, or alternate formatting.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shadow-[0_0_15px_rgba(255,122,204,0.3)] hover:shadow-[0_0_20px_rgba(255,122,204,0.5)] h-11 text-base"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
"Create Karaoke Video"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// === PRIVATE MODE: Full customization ===
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -96,7 +385,7 @@ export function CustomizeStep({
|
||||
Customize & Create
|
||||
</h2>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Preview your title card and confirm your settings.
|
||||
Customize your private video's appearance.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
@@ -111,20 +400,6 @@ export function CustomizeStep({
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Title card preview - half width, centered */}
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs" style={{ color: 'var(--text-muted)' }}>Title Card Preview</Label>
|
||||
<div className="mx-auto w-full sm:w-1/2">
|
||||
<TitleCardPreview
|
||||
artist={previewArtist}
|
||||
title={previewTitle}
|
||||
customBackgroundUrl={introBackgroundUrl}
|
||||
titleColor={colorOverrides.title_color}
|
||||
artistColor={colorOverrides.artist_color}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Display override fields */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
@@ -164,137 +439,197 @@ export function CustomizeStep({
|
||||
These default to your search values. Override for soundtracks, covers, or alternate formatting.
|
||||
</p>
|
||||
|
||||
{/* Privacy toggle */}
|
||||
<div className="space-y-2 pt-2 border-t" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="flex items-start gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="guided-private"
|
||||
checked={isPrivate}
|
||||
onChange={(e) => onPrivateChange(e.target.checked)}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="mt-1 w-4 h-4 rounded border-border bg-secondary accent-[var(--brand-pink)] focus:ring-[var(--brand-pink)] focus:ring-offset-background"
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="guided-private" className="cursor-pointer" style={{ color: 'var(--text)' }}>
|
||||
Private (no YouTube upload)
|
||||
</Label>
|
||||
<p className="text-xs mt-1" style={{ color: 'var(--text-muted)' }}>
|
||||
Files delivered via Dropbox only. No YouTube or Google Drive upload.
|
||||
</p>
|
||||
</div>
|
||||
{/* Custom Video Style section */}
|
||||
<div
|
||||
className="space-y-4 rounded-lg border p-4"
|
||||
style={{ borderColor: 'var(--card-border)', backgroundColor: 'rgba(255,255,255,0.02)' }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Palette className="w-4 h-4" style={{ color: 'var(--brand-pink)' }} />
|
||||
<h3 className="text-sm font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Custom Video Style
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Custom Video Style section - only shown for private delivery */}
|
||||
{isPrivate && (
|
||||
<div
|
||||
className="space-y-4 rounded-lg border p-4"
|
||||
style={{ borderColor: 'var(--card-border)', backgroundColor: 'rgba(255,255,255,0.02)' }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Palette className="w-4 h-4" style={{ color: 'var(--brand-pink)' }} />
|
||||
<h3 className="text-sm font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Custom Video Style
|
||||
</h3>
|
||||
</div>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Upload custom backgrounds and choose colors for your branded karaoke video.
|
||||
</p>
|
||||
{/* Side-by-side preview canvases */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
{/* Title Card Preview + Controls */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-medium" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Card
|
||||
</Label>
|
||||
<BgModeToggle
|
||||
mode={introBgMode}
|
||||
onChange={handleIntroBgModeChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Karaoke Background */}
|
||||
<div className="space-y-2">
|
||||
<ImageUploadField
|
||||
label="Karaoke Background"
|
||||
description="Replaces the starfield behind lyrics during the song."
|
||||
file={karaokeBackground}
|
||||
onChange={onKaraokeBackgroundChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
<TitleCardPreview
|
||||
artist={previewArtist}
|
||||
title={previewTitle}
|
||||
customBackgroundUrl={introBackgroundUrl}
|
||||
backgroundColor={introBgMode === "solid" ? introSolidColor : undefined}
|
||||
titleColor={colorOverrides.title_color}
|
||||
artistColor={colorOverrides.artist_color}
|
||||
/>
|
||||
{karaokeBackgroundUrl && (
|
||||
<div className="mx-auto w-full sm:w-2/3">
|
||||
<KaraokeBackgroundPreview backgroundUrl={karaokeBackgroundUrl} />
|
||||
|
||||
{introBgMode === "image" && (
|
||||
<ImageUploadField
|
||||
label=""
|
||||
description="PNG or JPG background for the title card."
|
||||
file={introBackground}
|
||||
onChange={onIntroBackgroundChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
hidePreview
|
||||
/>
|
||||
)}
|
||||
|
||||
{introBgMode === "solid" && (
|
||||
<div className="space-y-2">
|
||||
<ColorPresetButtons
|
||||
presets={BG_PRESETS}
|
||||
value={introSolidColor}
|
||||
onChange={handleIntroSolidColorChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={introSolidColor}
|
||||
onChange={(e) => handleIntroSolidColorChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={introSolidColor}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (/^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
handleIntroSolidColorChange(val)
|
||||
}
|
||||
}}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Title card text colors */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<ColorPickerField
|
||||
id="artist-color"
|
||||
label="Artist Color"
|
||||
value={colorOverrides.artist_color}
|
||||
defaultColor="#ffdf6b"
|
||||
onChange={(val) => onColorOverridesChange({ ...colorOverrides, artist_color: val })}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
<ColorPickerField
|
||||
id="title-color"
|
||||
label="Title Color"
|
||||
value={colorOverrides.title_color}
|
||||
defaultColor="#ffffff"
|
||||
onChange={(val) => onColorOverridesChange({ ...colorOverrides, title_color: val })}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Title Card Background */}
|
||||
<div className="space-y-2">
|
||||
<ImageUploadField
|
||||
label="Title Card Background"
|
||||
description="Background image for the intro/title card shown before the song starts."
|
||||
file={introBackground}
|
||||
onChange={onIntroBackgroundChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
{/* Karaoke Preview + Controls */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-medium" style={{ color: 'var(--text-muted)' }}>
|
||||
Karaoke Video
|
||||
</Label>
|
||||
<BgModeToggle
|
||||
mode={karaokeBgMode}
|
||||
onChange={handleKaraokeBgModeChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<KaraokeBackgroundPreview
|
||||
backgroundUrl={karaokeBackgroundUrl}
|
||||
backgroundColor={karaokeBgMode === "solid" ? karaokeSolidColor : undefined}
|
||||
sungColor={colorOverrides.sung_lyrics_color}
|
||||
unsungColor={colorOverrides.unsung_lyrics_color}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Color overrides */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="artist-color" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Artist Color
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
id="artist-color"
|
||||
value={colorOverrides.artist_color || "#ffdf6b"}
|
||||
onChange={(e) => onColorOverridesChange({ ...colorOverrides, artist_color: e.target.value })}
|
||||
{karaokeBgMode === "image" && (
|
||||
<ImageUploadField
|
||||
label=""
|
||||
description="PNG or JPG background behind lyrics during the song."
|
||||
file={karaokeBackground}
|
||||
onChange={onKaraokeBackgroundChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
hidePreview
|
||||
/>
|
||||
)}
|
||||
|
||||
{karaokeBgMode === "solid" && (
|
||||
<div className="space-y-2">
|
||||
<ColorPresetButtons
|
||||
presets={BG_PRESETS}
|
||||
value={karaokeSolidColor}
|
||||
onChange={handleKaraokeSolidColorChange}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={colorOverrides.artist_color || ""}
|
||||
placeholder="#ffdf6b"
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (val === "" || /^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
onColorOverridesChange({ ...colorOverrides, artist_color: val || undefined })
|
||||
}
|
||||
}}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="title-color" className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
Title Color
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
id="title-color"
|
||||
value={colorOverrides.title_color || "#ffffff"}
|
||||
onChange={(e) => onColorOverridesChange({ ...colorOverrides, title_color: e.target.value })}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={colorOverrides.title_color || ""}
|
||||
placeholder="#ffffff"
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (val === "" || /^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
onColorOverridesChange({ ...colorOverrides, title_color: val || undefined })
|
||||
}
|
||||
}}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={karaokeSolidColor}
|
||||
onChange={(e) => handleKaraokeSolidColorChange(e.target.value)}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="w-8 h-8 rounded border cursor-pointer"
|
||||
style={{ borderColor: 'var(--card-border)' }}
|
||||
/>
|
||||
<Input
|
||||
value={karaokeSolidColor}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
if (/^#[0-9A-Fa-f]{0,6}$/.test(val)) {
|
||||
handleKaraokeSolidColorChange(val)
|
||||
}
|
||||
}}
|
||||
disabled={disabled || isSubmitting}
|
||||
className="font-mono text-xs h-8"
|
||||
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lyrics colors */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<ColorPickerField
|
||||
id="sung-lyrics-color"
|
||||
label="Highlight Color"
|
||||
value={colorOverrides.sung_lyrics_color}
|
||||
defaultColor="#7070F7"
|
||||
onChange={(val) => onColorOverridesChange({ ...colorOverrides, sung_lyrics_color: val })}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
<ColorPickerField
|
||||
id="unsung-lyrics-color"
|
||||
label="Lyrics Color"
|
||||
value={colorOverrides.unsung_lyrics_color}
|
||||
defaultColor="#ffffff"
|
||||
onChange={(val) => onColorOverridesChange({ ...colorOverrides, unsung_lyrics_color: val })}
|
||||
disabled={disabled || isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
Leave blank to use default Nomad theme colors.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
|
||||
Leave colors blank to use default Nomad theme. Previews are approximate — final rendering may differ slightly.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Create button */}
|
||||
<Button
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"use client"
|
||||
|
||||
import { ArrowLeft, Globe, Lock, ExternalLink, Sparkles } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
interface VisibilityStepProps {
|
||||
isPrivate: boolean
|
||||
onPrivateChange: (value: boolean) => void
|
||||
onNext: () => void
|
||||
onBack: () => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function VisibilityStep({
|
||||
isPrivate,
|
||||
onPrivateChange,
|
||||
onNext,
|
||||
onBack,
|
||||
disabled,
|
||||
}: VisibilityStepProps) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold" style={{ color: 'var(--text)' }}>
|
||||
How should your video be shared?
|
||||
</h2>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
Choose how your finished karaoke video will be delivered.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
disabled={disabled}
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4 mr-1" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Published option */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPrivateChange(false)}
|
||||
disabled={disabled}
|
||||
className={`w-full text-left rounded-lg border-2 p-4 transition-all ${
|
||||
!isPrivate
|
||||
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
|
||||
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
|
||||
}`}
|
||||
style={{ backgroundColor: !isPrivate ? 'rgba(255,122,204,0.05)' : 'transparent' }}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Radio circle */}
|
||||
<div
|
||||
className={`mt-0.5 w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-colors ${
|
||||
!isPrivate ? 'border-[var(--brand-pink)]' : 'border-[var(--text-muted)]'
|
||||
}`}
|
||||
>
|
||||
{!isPrivate && (
|
||||
<div className="w-2.5 h-2.5 rounded-full bg-[var(--brand-pink)]" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="w-4 h-4" style={{ color: !isPrivate ? 'var(--brand-pink)' : 'var(--text-muted)' }} />
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Published
|
||||
</span>
|
||||
<span
|
||||
className="text-[10px] px-1.5 py-0.5 rounded-full font-medium"
|
||||
style={{ backgroundColor: 'rgba(255,122,204,0.15)', color: 'var(--brand-pink)' }}
|
||||
>
|
||||
Recommended
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
<p>Your karaoke video will be <span className="font-semibold" style={{ color: '#f59e0b' }}>shared with the world</span>:</p>
|
||||
|
||||
<ul className="space-y-2 ml-1">
|
||||
<li className="flex items-start gap-2">
|
||||
<Sparkles className="w-3.5 h-3.5 mt-0.5 shrink-0" style={{ color: 'var(--brand-pink)' }} />
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Uploaded to YouTube</strong> on the{" "}
|
||||
<a
|
||||
href="https://www.youtube.com/@nomadkaraoke/videos"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-0.5 underline"
|
||||
style={{ color: 'var(--brand-pink)' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Nomad Karaoke channel
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
{" "}— the easiest way for you (and anyone else) to sing this song anytime
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<Sparkles className="w-3.5 h-3.5 mt-0.5 shrink-0" style={{ color: 'var(--brand-pink)' }} />
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Shared with karaoke venues</strong> via Google Drive — your song will be available to sing at bars and venues around the world
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<Sparkles className="w-3.5 h-3.5 mt-0.5 shrink-0" style={{ color: 'var(--brand-pink)' }} />
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Source files delivered to you</strong> via Dropbox — all stems, highest quality formats, ready to download
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div
|
||||
className="rounded-md p-2.5 mt-1 text-xs"
|
||||
style={{ backgroundColor: 'rgba(255,122,204,0.08)', color: 'var(--text)' }}
|
||||
>
|
||||
By publishing, you're helping other fans of this song discover and enjoy it at karaoke nights everywhere. Share the joy!
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Private option */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPrivateChange(true)}
|
||||
disabled={disabled}
|
||||
className={`w-full text-left rounded-lg border-2 p-4 transition-all ${
|
||||
isPrivate
|
||||
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
|
||||
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
|
||||
}`}
|
||||
style={{ backgroundColor: isPrivate ? 'rgba(255,122,204,0.05)' : 'transparent' }}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Radio circle */}
|
||||
<div
|
||||
className={`mt-0.5 w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-colors ${
|
||||
isPrivate ? 'border-[var(--brand-pink)]' : 'border-[var(--text-muted)]'
|
||||
}`}
|
||||
>
|
||||
{isPrivate && (
|
||||
<div className="w-2.5 h-2.5 rounded-full bg-[var(--brand-pink)]" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Lock className="w-4 h-4" style={{ color: isPrivate ? 'var(--brand-pink)' : 'var(--text-muted)' }} />
|
||||
<span className="font-semibold" style={{ color: 'var(--text)' }}>
|
||||
Private
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
<p>Your karaoke video stays just with you:</p>
|
||||
|
||||
<ul className="space-y-2 ml-1">
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="w-3.5 h-3.5 mt-0.5 shrink-0 flex items-center justify-center text-[10px]">•</span>
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Delivered via Dropbox only</strong> — no YouTube upload, no Google Drive sharing. Download and use however you see fit.
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="w-3.5 h-3.5 mt-0.5 shrink-0 flex items-center justify-center text-[10px]">•</span>
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Venue use is up to you</strong> — if you want to perform this track at a venue, you'll need to provide the files to the host yourself.
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="w-3.5 h-3.5 mt-0.5 shrink-0 flex items-center justify-center text-[10px]">•</span>
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>YouTube self-upload</strong> — you can upload to your own channel, but monetization is unlikely as song copyrights are typically held by record labels.
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="w-3.5 h-3.5 mt-0.5 shrink-0 flex items-center justify-center text-[10px]">•</span>
|
||||
<span>
|
||||
<strong style={{ color: 'var(--text)' }}>Custom styling available</strong> — choose your own background images, colors, and text styles on the next step.
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Continue button */}
|
||||
<Button
|
||||
onClick={onNext}
|
||||
disabled={disabled}
|
||||
className="w-full bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shadow-[0_0_15px_rgba(255,122,204,0.3)] hover:shadow-[0_0_20px_rgba(255,122,204,0.5)] h-11 text-base"
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { test, expect, Page } from "@playwright/test";
|
||||
import * as path from "path";
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
|
||||
/**
|
||||
* Tenant Portal Job Submission - Production E2E Test
|
||||
*
|
||||
* Tests the full tenant portal flow:
|
||||
* 1. Navigate to tenant portal with admin auth
|
||||
* 2. Verify tenant branding (logo, title, simplified form)
|
||||
* 3. Submit a track (mixed + instrumental audio)
|
||||
* 4. Wait for job processing
|
||||
* 5. Verify job metadata (is_private, tenant_id, brand_prefix)
|
||||
*
|
||||
* Run with:
|
||||
* KARAOKE_ADMIN_TOKEN=xxx npx playwright test e2e/production/tenant-job-submission.spec.ts \
|
||||
* --config=playwright.production.config.ts --reporter=list
|
||||
*
|
||||
* Environment variables:
|
||||
* KARAOKE_ADMIN_TOKEN - Admin token for authentication (required)
|
||||
* TENANT_PORTAL_URL - Override tenant portal URL (default: https://vocalstar.nomadkaraoke.com)
|
||||
*/
|
||||
|
||||
const TENANT_PORTAL_URL = process.env.TENANT_PORTAL_URL || "https://vocalstar.nomadkaraoke.com";
|
||||
const API_URL = "https://api.nomadkaraoke.com";
|
||||
const CONSUMER_PORTAL_URL = "https://gen.nomadkaraoke.com";
|
||||
|
||||
const TIMEOUTS = {
|
||||
action: 30_000,
|
||||
expect: 60_000,
|
||||
apiCall: 120_000,
|
||||
jobProcessing: 600_000,
|
||||
fullTest: 1_200_000, // 20 minutes
|
||||
};
|
||||
|
||||
function getAdminToken(): string | null {
|
||||
return process.env.KARAOKE_ADMIN_TOKEN || process.env.KARAOKE_ACCESS_TOKEN || null;
|
||||
}
|
||||
|
||||
async function authenticatePage(page: Page, token: string): Promise<void> {
|
||||
await page.addInitScript((t) => {
|
||||
localStorage.setItem("karaoke_access_token", t);
|
||||
}, token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a minimal WAV file for testing uploads.
|
||||
* Returns the path to the temporary file.
|
||||
*/
|
||||
function createTestAudioFile(name: string): string {
|
||||
const tmpDir = os.tmpdir();
|
||||
const filePath = path.join(tmpDir, name);
|
||||
|
||||
// Minimal WAV header (44 bytes) + 1 second of silence at 8kHz mono 8-bit
|
||||
const sampleRate = 8000;
|
||||
const numSamples = sampleRate; // 1 second
|
||||
const dataSize = numSamples;
|
||||
const fileSize = 36 + dataSize;
|
||||
|
||||
const buffer = Buffer.alloc(44 + dataSize);
|
||||
|
||||
// RIFF header
|
||||
buffer.write("RIFF", 0);
|
||||
buffer.writeUInt32LE(fileSize, 4);
|
||||
buffer.write("WAVE", 8);
|
||||
|
||||
// fmt chunk
|
||||
buffer.write("fmt ", 12);
|
||||
buffer.writeUInt32LE(16, 16); // chunk size
|
||||
buffer.writeUInt16LE(1, 20); // PCM format
|
||||
buffer.writeUInt16LE(1, 22); // mono
|
||||
buffer.writeUInt32LE(sampleRate, 24);
|
||||
buffer.writeUInt32LE(sampleRate, 28); // byte rate
|
||||
buffer.writeUInt16LE(1, 32); // block align
|
||||
buffer.writeUInt16LE(8, 34); // bits per sample
|
||||
|
||||
// data chunk
|
||||
buffer.write("data", 36);
|
||||
buffer.writeUInt32LE(dataSize, 40);
|
||||
// Silence: fill with 128 (center value for 8-bit PCM)
|
||||
buffer.fill(128, 44);
|
||||
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
async function getJobDetails(token: string, jobId: string): Promise<any> {
|
||||
const response = await fetch(`${API_URL}/api/jobs/${jobId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get job ${jobId}: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
test.describe("Tenant Portal Job Submission", () => {
|
||||
test.describe.configure({ retries: 0 });
|
||||
|
||||
let adminToken: string = "";
|
||||
let testAudioPath: string;
|
||||
let testInstrumentalPath: string;
|
||||
let createdJobId: string | null = null;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
const token = getAdminToken();
|
||||
if (token) {
|
||||
adminToken = token;
|
||||
}
|
||||
|
||||
// Create test audio files
|
||||
testAudioPath = createTestAudioFile("test-mixed-audio.wav");
|
||||
testInstrumentalPath = createTestAudioFile("test-instrumental.wav");
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
// Clean up temp files
|
||||
for (const f of [testAudioPath, testInstrumentalPath]) {
|
||||
if (f && fs.existsSync(f)) {
|
||||
fs.unlinkSync(f);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up test job if created
|
||||
if (createdJobId && adminToken) {
|
||||
try {
|
||||
await fetch(`${API_URL}/api/admin/jobs/${createdJobId}`, {
|
||||
method: "DELETE",
|
||||
headers: { "X-Admin-Token": adminToken },
|
||||
});
|
||||
console.log(`Cleaned up test job ${createdJobId}`);
|
||||
} catch {
|
||||
console.warn(`Failed to clean up test job ${createdJobId}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("Tenant portal shows simplified form, not consumer wizard", async ({ page }) => {
|
||||
test.skip(!adminToken, "KARAOKE_ADMIN_TOKEN not set");
|
||||
test.setTimeout(TIMEOUTS.expect);
|
||||
|
||||
await authenticatePage(page, adminToken);
|
||||
await page.goto(`${TENANT_PORTAL_URL}/app`, { waitUntil: "networkidle", timeout: TIMEOUTS.action });
|
||||
|
||||
// Should NOT show the consumer wizard step indicators
|
||||
await expect(page.getByText("Choose Audio")).not.toBeVisible({ timeout: 5_000 });
|
||||
|
||||
// Should show tenant-specific card title
|
||||
await expect(page.getByText("Submit Track")).toBeVisible({ timeout: TIMEOUTS.expect });
|
||||
await expect(page.getByText("Upload your mixed audio and instrumental")).toBeVisible();
|
||||
|
||||
// Should show 4 form fields
|
||||
await expect(page.getByLabel("Artist")).toBeVisible();
|
||||
await expect(page.getByLabel("Title")).toBeVisible();
|
||||
await expect(page.getByText("Mixed Audio")).toBeVisible();
|
||||
await expect(page.getByText("Instrumental Audio")).toBeVisible();
|
||||
});
|
||||
|
||||
test("Submit track through tenant portal", async ({ page }) => {
|
||||
test.skip(!adminToken, "KARAOKE_ADMIN_TOKEN not set");
|
||||
test.setTimeout(TIMEOUTS.fullTest);
|
||||
|
||||
await authenticatePage(page, adminToken);
|
||||
await page.goto(`${TENANT_PORTAL_URL}/app`, { waitUntil: "networkidle", timeout: TIMEOUTS.action });
|
||||
|
||||
// Fill form
|
||||
await page.getByLabel("Artist").fill("E2E Test Artist");
|
||||
await page.getByLabel("Title").fill("E2E Test Tenant Track");
|
||||
|
||||
// Upload mixed audio
|
||||
const mixedInput = page.locator("#tenant-mixed-audio");
|
||||
await mixedInput.setInputFiles(testAudioPath);
|
||||
|
||||
// Upload instrumental
|
||||
const instrumentalInput = page.locator("#tenant-instrumental-audio");
|
||||
await instrumentalInput.setInputFiles(testInstrumentalPath);
|
||||
|
||||
// Submit
|
||||
await page.getByRole("button", { name: /Submit Track/i }).click();
|
||||
|
||||
// Wait for success
|
||||
await expect(page.getByText("Track Submitted")).toBeVisible({ timeout: TIMEOUTS.apiCall });
|
||||
|
||||
// Extract job ID from success view
|
||||
const jobIdElement = page.locator('[data-testid="created-job-id"]');
|
||||
const jobIdText = await jobIdElement.textContent();
|
||||
const shortId = jobIdText?.replace("ID: ", "").trim();
|
||||
expect(shortId).toBeTruthy();
|
||||
if (shortId) createdJobId = shortId;
|
||||
console.log(`Created tenant job with short ID: ${shortId}`);
|
||||
|
||||
// Verify success timeline shows tenant-specific steps (no "Audio processing" step)
|
||||
await expect(page.getByText("Lyrics transcription")).toBeVisible();
|
||||
await expect(page.getByText("Review lyrics")).toBeVisible();
|
||||
await expect(page.getByText("Video delivered")).toBeVisible();
|
||||
|
||||
// The timeline should NOT mention "Audio processing" or "Download" (consumer flow terms)
|
||||
const bodyText = await page.locator("body").textContent();
|
||||
expect(bodyText).not.toContain("Audio processing");
|
||||
expect(bodyText).not.toContain("separate vocals");
|
||||
});
|
||||
|
||||
test("Consumer portal still works normally", async ({ page }) => {
|
||||
test.skip(!adminToken, "KARAOKE_ADMIN_TOKEN not set");
|
||||
test.setTimeout(TIMEOUTS.expect);
|
||||
|
||||
await authenticatePage(page, adminToken);
|
||||
await page.goto(`${CONSUMER_PORTAL_URL}/app`, { waitUntil: "networkidle", timeout: TIMEOUTS.action });
|
||||
|
||||
// Consumer portal should show the full wizard
|
||||
await expect(page.getByText("Create Karaoke Video")).toBeVisible({ timeout: TIMEOUTS.expect });
|
||||
await expect(page.getByText("Turn any song into a karaoke video")).toBeVisible();
|
||||
|
||||
// Should NOT show tenant-specific text
|
||||
const bodyText = await page.locator("body").textContent();
|
||||
expect(bodyText).not.toContain("Submit Track");
|
||||
expect(bodyText).not.toContain("Upload your mixed audio and instrumental");
|
||||
});
|
||||
});
|
||||
@@ -432,10 +432,12 @@ export const api = {
|
||||
files: Array<{ filename: string; content_type: string; file_type: string }>,
|
||||
options?: {
|
||||
is_private?: boolean;
|
||||
existing_instrumental?: boolean;
|
||||
}
|
||||
): Promise<CreateJobWithUploadUrlsResponse> {
|
||||
const body: Record<string, any> = { artist, title, files };
|
||||
if (options?.is_private !== undefined) body.is_private = options.is_private;
|
||||
if (options?.existing_instrumental !== undefined) body.existing_instrumental = options.existing_instrumental;
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/api/jobs/create-with-upload-urls`, {
|
||||
method: 'POST',
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.7 MiB |
@@ -2,9 +2,51 @@ import os
|
||||
import logging
|
||||
import importlib.resources as pkg_resources
|
||||
import shutil
|
||||
import subprocess
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
def _find_cjk_font() -> str | None:
|
||||
"""Find a system CJK font using fontconfig (fc-match)."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["fc-match", "--format=%{file}", ":lang=zh"],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
)
|
||||
if result.returncode == 0 and result.stdout and os.path.exists(result.stdout):
|
||||
return result.stdout
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
# Fallback: common paths for Noto Sans CJK
|
||||
for path in [
|
||||
"/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc",
|
||||
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
||||
"/usr/share/fonts/noto-cjk/NotoSansCJK-Bold.ttc",
|
||||
]:
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def _text_needs_cjk_font(text: str) -> bool:
|
||||
"""Check if text contains CJK characters that need a CJK-capable font."""
|
||||
if not text:
|
||||
return False
|
||||
for ch in text:
|
||||
cp = ord(ch)
|
||||
# CJK Unified Ideographs, CJK Extension A/B, CJK Compatibility
|
||||
# Hangul Syllables, Katakana, Hiragana
|
||||
if (0x4E00 <= cp <= 0x9FFF or # CJK Unified Ideographs
|
||||
0x3400 <= cp <= 0x4DBF or # CJK Extension A
|
||||
0x20000 <= cp <= 0x2A6DF or # CJK Extension B
|
||||
0xAC00 <= cp <= 0xD7AF or # Hangul Syllables
|
||||
0x3040 <= cp <= 0x309F or # Hiragana
|
||||
0x30A0 <= cp <= 0x30FF or # Katakana
|
||||
0xF900 <= cp <= 0xFAFF): # CJK Compatibility Ideographs
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# Placeholder class or functions for video/image generation
|
||||
class VideoGenerator:
|
||||
def __init__(self, logger, ffmpeg_base_command, render_bounding_boxes, output_png, output_jpg):
|
||||
@@ -13,6 +55,7 @@ class VideoGenerator:
|
||||
self.render_bounding_boxes = render_bounding_boxes
|
||||
self.output_png = output_png
|
||||
self.output_jpg = output_jpg
|
||||
self._cjk_font_path = None # Lazy-loaded
|
||||
|
||||
def parse_region(self, region_str):
|
||||
if region_str:
|
||||
@@ -322,31 +365,60 @@ class VideoGenerator:
|
||||
|
||||
return background.resize(resolution)
|
||||
|
||||
def _get_font_path_for_text(self, font_path, text):
|
||||
"""Return an appropriate font path for the given text.
|
||||
|
||||
If the text contains CJK characters and the current font is a bundled
|
||||
Latin-only font, switch to a system CJK font so glyphs render correctly.
|
||||
"""
|
||||
if not text or not _text_needs_cjk_font(text):
|
||||
return font_path
|
||||
|
||||
# If font_path is already a CJK-capable system font, keep it
|
||||
if font_path and ("noto" in font_path.lower() or "cjk" in font_path.lower()):
|
||||
return font_path
|
||||
|
||||
# Lazy-load CJK font path
|
||||
if self._cjk_font_path is None:
|
||||
self._cjk_font_path = _find_cjk_font() or ""
|
||||
if self._cjk_font_path:
|
||||
self.logger.info(f"Found CJK fallback font: {self._cjk_font_path}")
|
||||
else:
|
||||
self.logger.warning("No CJK font found on system - CJK characters may not render correctly")
|
||||
|
||||
if self._cjk_font_path:
|
||||
self.logger.info(f"Using CJK font for text with CJK characters: {text[:30]}...")
|
||||
return self._cjk_font_path
|
||||
return font_path
|
||||
|
||||
def _render_all_text(self, draw, font_path, title_text, artist_text, format, render_bounding_boxes):
|
||||
"""Render all text elements on the image."""
|
||||
# Render title
|
||||
if format["title_region"]:
|
||||
title_font_path = self._get_font_path_for_text(font_path, title_text)
|
||||
region_parsed = self.parse_region(format["title_region"])
|
||||
region = self._render_text_in_region(
|
||||
draw, title_text, font_path, region_parsed, format["title_color"], gradient=format.get("title_gradient")
|
||||
draw, title_text, title_font_path, region_parsed, format["title_color"], gradient=format.get("title_gradient")
|
||||
)
|
||||
if render_bounding_boxes:
|
||||
self._draw_bounding_box(draw, region, format["title_color"])
|
||||
|
||||
# Render artist
|
||||
if format["artist_region"]:
|
||||
artist_font_path = self._get_font_path_for_text(font_path, artist_text)
|
||||
region_parsed = self.parse_region(format["artist_region"])
|
||||
region = self._render_text_in_region(
|
||||
draw, artist_text, font_path, region_parsed, format["artist_color"], gradient=format.get("artist_gradient")
|
||||
draw, artist_text, artist_font_path, region_parsed, format["artist_color"], gradient=format.get("artist_gradient")
|
||||
)
|
||||
if render_bounding_boxes:
|
||||
self._draw_bounding_box(draw, region, format["artist_color"])
|
||||
|
||||
# Render extra text if provided
|
||||
if format["extra_text"]:
|
||||
extra_font_path = self._get_font_path_for_text(font_path, format["extra_text"])
|
||||
region_parsed = self.parse_region(format["extra_text_region"])
|
||||
region = self._render_text_in_region(
|
||||
draw, format["extra_text"], font_path, region_parsed, format["extra_text_color"], gradient=format.get("extra_text_gradient")
|
||||
draw, format["extra_text"], extra_font_path, region_parsed, format["extra_text_color"], gradient=format.get("extra_text_gradient")
|
||||
)
|
||||
if render_bounding_boxes:
|
||||
self._draw_bounding_box(draw, region, format["extra_text_color"])
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.131.0"
|
||||
version = "0.133.1"
|
||||
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"
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Unit tests for VideoGenerator CJK font fallback.
|
||||
|
||||
Tests the fix for job f8a36b60 where Chinese characters in the title card
|
||||
rendered as question marks because Montserrat-Bold.ttf lacks CJK glyphs.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from karaoke_gen.video_generator import VideoGenerator, _text_needs_cjk_font, _find_cjk_font
|
||||
|
||||
|
||||
class TestTextNeedsCjkFont:
|
||||
"""Test the _text_needs_cjk_font helper function."""
|
||||
|
||||
def test_ascii_text(self):
|
||||
assert _text_needs_cjk_font("Hello World") is False
|
||||
|
||||
def test_empty_string(self):
|
||||
assert _text_needs_cjk_font("") is False
|
||||
|
||||
def test_none(self):
|
||||
assert _text_needs_cjk_font(None) is False
|
||||
|
||||
def test_chinese_simplified(self):
|
||||
assert _text_needs_cjk_font("青花瓷") is True
|
||||
|
||||
def test_chinese_traditional(self):
|
||||
assert _text_needs_cjk_font("周杰倫") is True
|
||||
|
||||
def test_japanese_kanji(self):
|
||||
assert _text_needs_cjk_font("宇多田ヒカル") is True
|
||||
|
||||
def test_japanese_hiragana(self):
|
||||
assert _text_needs_cjk_font("あいうえお") is True
|
||||
|
||||
def test_japanese_katakana(self):
|
||||
assert _text_needs_cjk_font("カラオケ") is True
|
||||
|
||||
def test_korean(self):
|
||||
assert _text_needs_cjk_font("방탄소년단") is True
|
||||
|
||||
def test_mixed_ascii_and_cjk(self):
|
||||
assert _text_needs_cjk_font("Artist - 青花瓷") is True
|
||||
|
||||
def test_accented_latin(self):
|
||||
assert _text_needs_cjk_font("Café del Mar") is False
|
||||
|
||||
def test_cyrillic(self):
|
||||
assert _text_needs_cjk_font("Тату") is False
|
||||
|
||||
def test_arabic(self):
|
||||
assert _text_needs_cjk_font("فيروز") is False
|
||||
|
||||
def test_emoji(self):
|
||||
assert _text_needs_cjk_font("🎵 Music") is False
|
||||
|
||||
|
||||
class TestGetFontPathForText:
|
||||
"""Test the CJK font fallback logic in VideoGenerator."""
|
||||
|
||||
@pytest.fixture
|
||||
def generator(self):
|
||||
return VideoGenerator(
|
||||
logger=MagicMock(),
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
render_bounding_boxes=False,
|
||||
output_png=True,
|
||||
output_jpg=True,
|
||||
)
|
||||
|
||||
def test_ascii_text_keeps_original_font(self, generator):
|
||||
result = generator._get_font_path_for_text("/path/to/Montserrat-Bold.ttf", "Hello World")
|
||||
assert result == "/path/to/Montserrat-Bold.ttf"
|
||||
|
||||
def test_none_text_keeps_original_font(self, generator):
|
||||
result = generator._get_font_path_for_text("/path/to/Montserrat-Bold.ttf", None)
|
||||
assert result == "/path/to/Montserrat-Bold.ttf"
|
||||
|
||||
@patch("karaoke_gen.video_generator._find_cjk_font", return_value="/usr/share/fonts/noto/NotoSansCJK-Bold.ttc")
|
||||
def test_cjk_text_uses_fallback_font(self, mock_find, generator):
|
||||
result = generator._get_font_path_for_text("/path/to/Montserrat-Bold.ttf", "周杰倫")
|
||||
assert result == "/usr/share/fonts/noto/NotoSansCJK-Bold.ttc"
|
||||
|
||||
@patch("karaoke_gen.video_generator._find_cjk_font", return_value="")
|
||||
def test_cjk_text_falls_back_to_original_when_no_cjk_font(self, mock_find, generator):
|
||||
result = generator._get_font_path_for_text("/path/to/Montserrat-Bold.ttf", "周杰倫")
|
||||
assert result == "/path/to/Montserrat-Bold.ttf"
|
||||
|
||||
def test_noto_font_not_overridden(self, generator):
|
||||
"""If the configured font is already a Noto/CJK font, don't override."""
|
||||
result = generator._get_font_path_for_text(
|
||||
"/usr/share/fonts/noto/NotoSansCJK-Bold.ttc", "周杰倫"
|
||||
)
|
||||
assert result == "/usr/share/fonts/noto/NotoSansCJK-Bold.ttc"
|
||||
|
||||
@patch("karaoke_gen.video_generator._find_cjk_font", return_value="/usr/share/fonts/noto/NotoSansCJK-Bold.ttc")
|
||||
def test_cjk_font_cached_across_calls(self, mock_find, generator):
|
||||
generator._get_font_path_for_text("/path/to/font.ttf", "周杰倫")
|
||||
generator._get_font_path_for_text("/path/to/font.ttf", "方大同")
|
||||
# _find_cjk_font should only be called once due to caching
|
||||
mock_find.assert_called_once()
|
||||
|
||||
|
||||
class TestRenderAllTextFontFallback:
|
||||
"""Test that _render_all_text uses CJK font fallback per text element."""
|
||||
|
||||
@pytest.fixture
|
||||
def generator(self):
|
||||
gen = VideoGenerator(
|
||||
logger=MagicMock(),
|
||||
ffmpeg_base_command="ffmpeg",
|
||||
render_bounding_boxes=False,
|
||||
output_png=True,
|
||||
output_jpg=True,
|
||||
)
|
||||
gen._cjk_font_path = "/usr/share/fonts/noto/NotoSansCJK-Bold.ttc"
|
||||
return gen
|
||||
|
||||
@patch.object(VideoGenerator, "_render_text_in_region")
|
||||
def test_cjk_title_gets_cjk_font_while_ascii_artist_keeps_original(self, mock_render, generator):
|
||||
"""When title is CJK but artist is ASCII, each gets the right font."""
|
||||
draw = MagicMock()
|
||||
format_config = {
|
||||
"font": "Montserrat-Bold.ttf",
|
||||
"title_region": "370, 200, 3100, 480",
|
||||
"title_color": "#ffffff",
|
||||
"title_gradient": None,
|
||||
"artist_region": "370, 700, 3100, 480",
|
||||
"artist_color": "#ffdf6b",
|
||||
"artist_gradient": None,
|
||||
"extra_text": None,
|
||||
}
|
||||
|
||||
generator._render_all_text(
|
||||
draw, "/path/Montserrat-Bold.ttf", "青花瓷", "Jay Chou", format_config, False
|
||||
)
|
||||
|
||||
# Should have 2 calls: title and artist
|
||||
assert mock_render.call_count == 2
|
||||
title_call = mock_render.call_args_list[0]
|
||||
artist_call = mock_render.call_args_list[1]
|
||||
|
||||
# Title (CJK) should use CJK font
|
||||
assert title_call[0][2] == "/usr/share/fonts/noto/NotoSansCJK-Bold.ttc"
|
||||
# Artist (ASCII) should use original font
|
||||
assert artist_call[0][2] == "/path/Montserrat-Bold.ttf"
|
||||
|
||||
@patch.object(VideoGenerator, "_render_text_in_region")
|
||||
def test_both_cjk_both_get_cjk_font(self, mock_render, generator):
|
||||
"""When both title and artist are CJK, both get CJK font."""
|
||||
draw = MagicMock()
|
||||
format_config = {
|
||||
"title_region": "370, 200, 3100, 480",
|
||||
"title_color": "#ffffff",
|
||||
"title_gradient": None,
|
||||
"artist_region": "370, 700, 3100, 480",
|
||||
"artist_color": "#ffdf6b",
|
||||
"artist_gradient": None,
|
||||
"extra_text": None,
|
||||
}
|
||||
|
||||
generator._render_all_text(
|
||||
draw, "/path/Montserrat-Bold.ttf", "青花瓷", "周杰倫", format_config, False
|
||||
)
|
||||
|
||||
assert mock_render.call_count == 2
|
||||
for call in mock_render.call_args_list:
|
||||
assert call[0][2] == "/usr/share/fonts/noto/NotoSansCJK-Bold.ttc"
|
||||
Reference in new issue
Block a user