Compare commits

...
2 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 9c1e951fd0 feat(i18n): localize email bodies + non-locale route redirects (#663)
## Summary
- **P1**: Replace 5 duplicate non-locale route pages (`/app`,
`/app/jobs`, `/auth/verify`, `/payment/success`, `/order/success`) with
thin `LocaleRedirect` component — detects locale from
localStorage/navigator and redirects to `/{locale}/...`
- **P2**: Localize all user-facing email bodies (7 inline types + 4
template defaults + shared footer). Adds ~80 translation keys to
en/es/de.json. Template service now tries locale-specific GCS paths
before falling back to localized defaults.
- Fix admin dropdown link using locale-aware Link (should use NextLink
since `/admin` is outside locale routing)

### Email types localized
Magic link, welcome, credits added, review reminder, review expired,
made-for-you order confirmation, credit denied, action reminder alert,
job completion/action needed/YouTube upload template defaults, shared
footer

### Not localized (intentionally)
Admin-only: feedback notification, credit review, admin order
notification

## Test plan
- [x] Backend: 2668 tests pass (139 skipped)
- [x] Frontend: `next build` succeeds with all locale directories
- [x] CodeRabbit: 1 finding fixed (admin dropdown link)
- [ ] Post-deploy: verify Spanish user receives localized email body
(magic link flow)
- [ ] Post-deploy: verify `/app` redirects to `/{locale}/app`

<!-- @coderabbitai ignore -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 02:28:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 648a26d462 fix(i18n): locale-aware navigation for internal links (#662)
## Summary
- Replace `next/navigation` and `next/link` imports with
`@/i18n/routing` equivalents in 13 user-facing components and pages so
`router.push()` and `<Link>` automatically include the locale prefix
(`/es/`, `/de/`)
- Without this fix, users on Spanish/German routes were kicked back to
non-locale paths on every internal navigation click
- Admin navigation (`/admin`) correctly excluded from locale routing
(uses `next/link` / `window.location`)
- Fix Jest ESM transform for `next-intl` transitive deps and add global
`@/i18n/routing` mock

## Test plan
- [x] `next build` succeeds — all 3 locale directories generated
(`/en/`, `/es/`, `/de/`)
- [x] 39 Jest test suites / 707 tests pass
- [x] CodeRabbit review: clean, no findings
- [ ] Post-deploy: verify `/es/app` links navigate to `/es/` prefixed
routes
- [ ] Post-deploy: verify admin link from header goes to `/admin` (no
locale prefix)

<!-- @coderabbitai ignore -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 01:34:57 -04:00
30 changed files with 774 additions and 1702 deletions

No files matched your search

+122 -129
View File
@@ -283,38 +283,38 @@ class EmailService:
"""
content = f"""
<p>Hi there,</p>
<p>{t(locale, "emails.magicLink.greeting")}</p>
<p>Click the button below to sign in to {html.escape(brand_name)}:</p>
<p>{t(locale, "emails.magicLink.signInPrompt", brand_name=html.escape(brand_name))}</p>
<p style="text-align: center;">
<a href="{magic_link_url}" class="button">Sign In</a>
<a href="{magic_link_url}" class="button">{t(locale, "emails.magicLink.signInButton")}</a>
</p>
<div class="warning">
⏰ This link expires in 15 minutes and can only be used once.
⏰ {t(locale, "emails.magicLink.expiryWarning")}
</div>
<p>If the button doesn't work, copy and paste this link into your browser:</p>
<p>{t(locale, "emails.magicLink.fallbackLink")}</p>
<p style="word-break: break-all; font-size: 14px; color: #666;">
{magic_link_url}
</p>
<p>If you didn't request this email, you can safely ignore it.</p>
<p>{t(locale, "emails.magicLink.ignoreNote")}</p>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = f"""
Sign in to {brand_name}
{t(locale, "emails.magicLink.signInButton")}
========================
Click this link to sign in:
{t(locale, "emails.magicLink.signInPrompt", brand_name=brand_name)}
{magic_link_url}
This link expires in 15 minutes and can only be used once.
{t(locale, "emails.magicLink.expiryWarning")}
If you didn't request this email, you can safely ignore it.
{t(locale, "emails.magicLink.ignoreNote")}
---
© {self._get_year()} {brand_name}
@@ -355,39 +355,39 @@ If you didn't request this email, you can safely ignore it.
"""
content = f"""
<p>Great news!</p>
<p>{t(locale, "emails.creditsAdded.greatNews")}</p>
<p><strong>{credits} credits</strong> have been added to your account.</p>
<p><strong>{t(locale, "emails.creditsAdded.creditsAddedMessage", credits=credits)}</strong></p>
<div class="credits-box">
<div>Your balance:</div>
<div>{t(locale, "emails.creditsAdded.yourBalance")}</div>
<div class="credits-number">{total_credits}</div>
<div>credits</div>
<div>{t(locale, "emails.creditsAdded.credits")}</div>
</div>
<p>Each credit lets you create one professional karaoke video with:</p>
<p>{t(locale, "emails.creditsAdded.eachCreditLets")}</p>
<ul>
<li>AI-powered vocal/instrumental separation</li>
<li>Synchronized lyrics with word-level timing</li>
<li>4K video output</li>
<li>YouTube upload</li>
<li>{t(locale, "emails.creditsAdded.featureVocalSeparation")}</li>
<li>{t(locale, "emails.creditsAdded.featureLyrics")}</li>
<li>{t(locale, "emails.creditsAdded.feature4k")}</li>
<li>{t(locale, "emails.creditsAdded.featureYoutube")}</li>
</ul>
<p style="text-align: center;">
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">Create Karaoke Now</a>
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">{t(locale, "emails.creditsAdded.createButton")}</a>
</p>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = f"""
{credits} credits added to your Nomad Karaoke account!
{t(locale, "emails.creditsAdded.creditsAddedMessage", credits=credits)}
Your new balance: {total_credits} credits
{t(locale, "emails.creditsAdded.yourBalance")} {total_credits} {t(locale, "emails.creditsAdded.credits")}
Each credit lets you create one professional karaoke video.
{t(locale, "emails.creditsAdded.eachCreditLets")}
Start creating: {self.frontend_url}{get_locale_prefix(locale)}
{self.frontend_url}{get_locale_prefix(locale)}
---
© {self._get_year()} Nomad Karaoke
@@ -449,87 +449,87 @@ Start creating: {self.frontend_url}{get_locale_prefix(locale)}
credits_box = f"""
<div class="credits-box">
<div class="credits-number">{credits}</div>
<div class="credits-label">Free Credits</div>
<div class="credits-note">Each credit creates one professional karaoke video</div>
<div class="credits-label">{t(locale, "emails.welcome.freeCreditsLabel")}</div>
<div class="credits-note">{t(locale, "emails.welcome.freeCreditsNote")}</div>
</div>
"""
content = f"""
<p>Welcome to Nomad Karaoke!</p>
<p>{t(locale, "emails.welcome.welcomeGreeting")}</p>
<p>Turn any song into a professional karaoke video in minutes.</p>
<p>{t(locale, "emails.welcome.turnAnySong")}</p>
{credits_box}
<p><strong>Here's how it works:</strong></p>
<p><strong>{t(locale, "emails.welcome.howItWorks")}</strong></p>
<div class="feature">
<span class="feature-icon">🎵</span>
<div>
<strong>1. Search for a song</strong><br>
Enter the artist and title, and we'll find high-quality audio.
<strong>{t(locale, "emails.welcome.step1Title")}</strong><br>
{t(locale, "emails.welcome.step1Desc")}
</div>
</div>
<div class="feature">
<span class="feature-icon">✨</span>
<div>
<strong>2. Our system works its magic</strong><br>
We separate vocals, transcribe lyrics, and sync everything perfectly.
<strong>{t(locale, "emails.welcome.step2Title")}</strong><br>
{t(locale, "emails.welcome.step2Desc")}
</div>
</div>
<div class="feature">
<span class="feature-icon">✏️</span>
<div>
<strong>3. Review & customize</strong><br>
Fine-tune the lyrics if needed, choose your instrumental.
<strong>{t(locale, "emails.welcome.step3Title")}</strong><br>
{t(locale, "emails.welcome.step3Desc")}
</div>
</div>
<div class="feature">
<span class="feature-icon">🎬</span>
<div>
<strong>4. Get your video</strong><br>
Download your 4K karaoke video or upload directly to YouTube.
<strong>{t(locale, "emails.welcome.step4Title")}</strong><br>
{t(locale, "emails.welcome.step4Desc")}
</div>
</div>
<p style="text-align: center; font-size: 14px; color: #999; margin-top: 20px;">
Complete 2 videos and earn 2 more free credits by sharing your feedback!
{t(locale, "emails.welcome.feedbackBonus")}
</p>
<p style="text-align: center;">
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">Get Started</a>
<a href="{self.frontend_url}{get_locale_prefix(locale)}" class="button">{t(locale, "emails.welcome.getStartedButton")}</a>
</p>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
credits_text = f"\nYou have {credits} free credits to get started!\nEach credit creates one professional karaoke video.\n" if credits > 0 else ""
credits_text = f"\n{t(locale, 'emails.welcome.freeCreditsNote')}: {credits}\n" if credits > 0 else ""
text_content = f"""
Welcome to Nomad Karaoke!
{t(locale, "emails.welcome.welcomeGreeting")}
Turn any song into a professional karaoke video in minutes.
{t(locale, "emails.welcome.turnAnySong")}
{credits_text}
Here's how it works:
{t(locale, "emails.welcome.howItWorks")}
1. Search for a song
Enter the artist and title, and we'll find high-quality audio.
{t(locale, "emails.welcome.step1Title")}
{t(locale, "emails.welcome.step1Desc")}
2. Our system works its magic
We separate vocals, transcribe lyrics, and sync everything perfectly.
{t(locale, "emails.welcome.step2Title")}
{t(locale, "emails.welcome.step2Desc")}
3. Review & customize
Fine-tune the lyrics if needed, choose your instrumental.
{t(locale, "emails.welcome.step3Title")}
{t(locale, "emails.welcome.step3Desc")}
4. Get your video
Download your 4K karaoke video or upload directly to YouTube.
{t(locale, "emails.welcome.step4Title")}
{t(locale, "emails.welcome.step4Desc")}
Complete 2 videos and earn 2 more free credits by sharing your feedback!
{t(locale, "emails.welcome.feedbackBonus")}
Get started: {self.frontend_url}{get_locale_prefix(locale)}
{self.frontend_url}{get_locale_prefix(locale)}
---
© {self._get_year()} Nomad Karaoke
@@ -555,10 +555,10 @@ Get started: {self.frontend_url}{get_locale_prefix(locale)}
</div>
"""
def _get_email_footer(self) -> str:
def _get_email_footer(self, locale: str = "en") -> str:
"""Get the standard email footer with support message and signature."""
return f"""
<p style="margin-top: 30px; font-style: italic; color: #666;">If anything isn't perfect, just reply to this email and I'll fix it!</p>
<p style="margin-top: 30px; font-style: italic; color: #666;">{t(locale, "emails.shared.footerHelp")}</p>
<div class="signature">
{self._get_email_signature()}
@@ -601,13 +601,14 @@ Get started: {self.frontend_url}{get_locale_prefix(locale)}
}}
"""
def _build_email_html(self, content: str, extra_styles: str = "", extra_header_content: str = "") -> str:
def _build_email_html(self, content: str, extra_styles: str = "", extra_header_content: str = "", locale: str = "en") -> str:
"""Build a complete HTML email with standard header, footer, and styles.
Args:
content: The main body content of the email
extra_styles: Additional CSS styles specific to this email type
extra_header_content: Optional extra content to add in header (e.g., beta badge)
locale: Locale for footer localization
Returns:
Complete HTML email string
@@ -626,7 +627,7 @@ Get started: {self.frontend_url}{get_locale_prefix(locale)}
{content}
{self._get_email_footer()}
{self._get_email_footer(locale)}
</body>
</html>
"""
@@ -910,7 +911,7 @@ Get started: {self.frontend_url}{get_locale_prefix(locale)}
<div class="content">{html.escape(message_content)}</div>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
cc_emails = ["gen@nomadkaraoke.com"] if cc_admin else None
@@ -983,13 +984,13 @@ Get started: {self.frontend_url}{get_locale_prefix(locale)}
content = f"""
<div class="alert">
⏰ Your karaoke video needs input from you!
⏰ {t(locale, "emails.actionReminder.alertHeading")}
</div>
<div class="content">{html.escape(message_content)}</div>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
return self.provider.send_email(
to_email=to_email,
@@ -1060,36 +1061,35 @@ Get started: {self.frontend_url}{get_locale_prefix(locale)}
"""
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
song_name_text = f" for {artist} - {title}" if artist and title else ""
content = f"""
<div class="alert">
⏰ Your karaoke video is waiting for you!
⏰ {t(locale, "emails.reviewReminder.alertHeading")}
</div>
<p>Hi there! Just a friendly reminder that your karaoke video{song_name} is ready for review.</p>
<p>{t(locale, "emails.reviewReminder.reminderIntro", song_name=song_name)}</p>
<p style="text-align: center;">
<a href="{html.escape(review_url)}" class="review-btn">Review Your Video</a>
<a href="{html.escape(review_url)}" class="review-btn">{t(locale, "emails.reviewReminder.reviewButton")}</a>
</p>
<p>During the review, you can check the lyrics are correct and choose your preferred instrumental track. It usually only takes a few minutes!</p>
<p>{t(locale, "emails.reviewReminder.reviewInstructions")}</p>
<p>If you're having any trouble with the review process, just reply to this email and I'll be happy to help you out.</p>
<p>{t(locale, "emails.reviewReminder.helpOffer")}</p>
<div class="expiry-warning">
⚠️ Please note: if the review isn't completed within the next <strong>24 hours</strong>,
the job will automatically expire and your credit will be refunded.
⚠️ {t(locale, "emails.reviewReminder.expiryWarning")}
</div>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = (
f"Reminder: Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} is ready for review.\n\n"
f"Review it here: {review_url}\n\n"
"If you're having trouble with the review process, just reply to this email and I'll help you out.\n\n"
"Please note: if the review isn't completed within the next 24 hours, "
"the job will automatically expire and your credit will be refunded."
f"{t(locale, 'emails.reviewReminder.reminderIntro', song_name=song_name_text)}\n\n"
f"{t(locale, 'emails.reviewReminder.reviewButton')}: {review_url}\n\n"
f"{t(locale, 'emails.reviewReminder.helpOffer')}\n\n"
f"{t(locale, 'emails.reviewReminder.expiryWarning')}"
)
return self.provider.send_email(
@@ -1157,33 +1157,32 @@ Get started: {self.frontend_url}{get_locale_prefix(locale)}
"""
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
song_name_text = f" for {artist} - {title}" if artist and title else ""
credits_word = t(locale, "emails.reviewExpired.creditSingular") if credits_balance == 1 else t(locale, "emails.reviewExpired.creditPlural")
content = f"""
<div class="info-box">
Your karaoke video{song_name} has been automatically cancelled because the review
wasn't completed within 48 hours.
{t(locale, "emails.reviewExpired.cancelNotice", song_name=song_name)}
</div>
<p>Don't worry — your credit has been refunded! Your current balance is
<span class="credit-badge">{credits_balance} credit{'s' if credits_balance != 1 else ''}</span>.</p>
<p>{t(locale, "emails.reviewExpired.refundNotice", credits_balance=credits_balance, credits_word=credits_word)}</p>
<p>You can create a new karaoke video anytime using your credits:</p>
<p>{t(locale, "emails.reviewExpired.createNewPrompt")}</p>
<p style="text-align: center;">
<a href="{html.escape(self.frontend_url)}{get_locale_prefix(locale)}/app" class="create-btn">Create New Video</a>
<a href="{html.escape(self.frontend_url)}{get_locale_prefix(locale)}/app" class="create-btn">{t(locale, "emails.reviewExpired.createButton")}</a>
</p>
<p>If you had any trouble with the review process or need help, just reply to this email — I'd love to help!</p>
<p>{t(locale, "emails.reviewExpired.helpOffer")}</p>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = (
f"Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} has been "
"automatically cancelled because the review wasn't completed within 48 hours.\n\n"
f"Your credit has been refunded. Current balance: {credits_balance} credit{'s' if credits_balance != 1 else ''}.\n\n"
f"Create a new video anytime: {self.frontend_url}{get_locale_prefix(locale)}/app\n\n"
"If you had any trouble or need help, just reply to this email."
f"{t(locale, 'emails.reviewExpired.cancelNotice', song_name=song_name_text)}\n\n"
f"{t(locale, 'emails.reviewExpired.refundNotice', credits_balance=credits_balance, credits_word=credits_word)}\n\n"
f"{self.frontend_url}{get_locale_prefix(locale)}/app\n\n"
f"{t(locale, 'emails.reviewExpired.helpOffer')}"
)
return self.provider.send_email(
@@ -1234,7 +1233,7 @@ Get started: {self.frontend_url}{get_locale_prefix(locale)}
<div class="content">{html.escape(message_content)}</div>
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
return self.provider.send_email(
to_email=to_email,
@@ -1292,42 +1291,42 @@ Get started: {self.frontend_url}{get_locale_prefix(locale)}
notes_html = ""
notes_text = ""
if notes:
notes_html = f"<p><strong>Your Notes:</strong> {html.escape(notes)}</p>"
notes_text = f"\nYour Notes: {notes}"
notes_html = f"<p><strong>{t(locale, 'emails.madeForYouConfirmation.yourNotes')}</strong> {html.escape(notes)}</p>"
notes_text = f"\n{t(locale, 'emails.madeForYouConfirmation.yourNotes')} {notes}"
content = f"""
<h2>Thank You for Your Order!</h2>
<h2>{t(locale, "emails.madeForYouConfirmation.thankYou")}</h2>
<div class="order-details">
<h3>Order Details</h3>
<p><strong>Order ID:</strong> {html.escape(job_id)}</p>
<p><strong>Artist:</strong> {html.escape(artist)}</p>
<p><strong>Title:</strong> {html.escape(title)}</p>
<h3>{t(locale, "emails.madeForYouConfirmation.orderDetails")}</h3>
<p><strong>{t(locale, "emails.madeForYouConfirmation.orderId")}</strong> {html.escape(job_id)}</p>
<p><strong>{t(locale, "emails.madeForYouConfirmation.artist")}</strong> {html.escape(artist)}</p>
<p><strong>{t(locale, "emails.madeForYouConfirmation.title")}</strong> {html.escape(title)}</p>
{notes_html}
</div>
<p>Our team will create your custom karaoke video within <span class="highlight">24 hours</span>.</p>
<p>{t(locale, "emails.madeForYouConfirmation.deliveryTime", hours=24)}</p>
<p>You'll receive an email with download links as soon as your video is ready.</p>
<p>{t(locale, "emails.madeForYouConfirmation.deliveryNotice")}</p>
<p><strong>No action needed</strong> - sit back and we'll take care of everything!</p>
<p><strong>{t(locale, "emails.madeForYouConfirmation.noAction")}</strong></p>
"""
text_content = f"""Thank You for Your Order!
text_content = f"""{t(locale, "emails.madeForYouConfirmation.thankYou")}
Order Details:
Order ID: {job_id}
Artist: {artist}
Title: {title}{notes_text}
{t(locale, "emails.madeForYouConfirmation.orderDetails")}:
{t(locale, "emails.madeForYouConfirmation.orderId")} {job_id}
{t(locale, "emails.madeForYouConfirmation.artist")} {artist}
{t(locale, "emails.madeForYouConfirmation.title")} {title}{notes_text}
Our team will create your custom karaoke video within 24 hours.
{t(locale, "emails.madeForYouConfirmation.deliveryTime", hours=24)}
You'll receive an email with download links as soon as your video is ready.
{t(locale, "emails.madeForYouConfirmation.deliveryNotice")}
No action needed - sit back and we'll take care of everything!
{t(locale, "emails.madeForYouConfirmation.noAction")}
"""
html_content = self._build_email_html(content, extra_styles)
html_content = self._build_email_html(content, extra_styles, locale=locale)
return self.provider.send_email(
to_email=to_email,
@@ -1697,50 +1696,44 @@ If the user looks legitimate, grant them credits from their admin page.
"""
subject = t(locale, "emails.creditDenied.subject")
credit_type = "welcome credits" if grant_type == "welcome" else "feedback bonus credits"
credit_type = t(locale, "emails.creditDenied.welcomeCredits") if grant_type == "welcome" else t(locale, "emails.creditDenied.feedbackCredits")
content = f"""
<p>Hi there,</p>
<p>{t(locale, "emails.creditDenied.greeting")}</p>
<p>Thanks for signing up for Nomad Karaoke!</p>
<p>{t(locale, "emails.creditDenied.thankYou")}</p>
<p>Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected
patterns that suggest this may not be your first account with us, and each karaoke generation job
costs us real money in cloud computing and API fees.</p>
<p>{t(locale, "emails.creditDenied.deniedMessage", credit_type=credit_type)}</p>
<p>We totally understand if this is a mistake! If you're a genuine new user, please just
<strong>reply to this email</strong> and let Andrew (the founder) know. He built this service and is
happy to grant you some free credits to try it out — he just asks that you provide honest feedback
on the experience in return.</p>
<p>{t(locale, "emails.creditDenied.mistakeNote")}</p>
<p>If you'd like to get started right away, you can also purchase credits:</p>
<p>{t(locale, "emails.creditDenied.buyPrompt")}</p>
<p style="text-align: center;">
<a href="{self.buy_url}" class="button">Buy Credits</a>
<a href="{self.buy_url}" class="button">{t(locale, "emails.creditDenied.buyButton")}</a>
</p>
<p style="color: #999; font-size: 14px;">We keep costs low so we can offer the service affordably,
which means we need to be careful about free credit abuse. Thanks for understanding!</p>
<p style="color: #999; font-size: 14px;">{t(locale, "emails.creditDenied.costNote")}</p>
{self._get_email_signature()}
"""
text_content = f"""Hi there,
text_content = f"""{t(locale, "emails.creditDenied.greeting")}
Thanks for signing up for Nomad Karaoke!
{t(locale, "emails.creditDenied.thankYou")}
Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected patterns that suggest this may not be your first account with us, and each karaoke generation job costs us real money in cloud computing and API fees.
{t(locale, "emails.creditDenied.deniedMessage", credit_type=credit_type)}
We totally understand if this is a mistake! If you're a genuine new user, please just reply to this email and let Andrew (the founder) know. He built this service and is happy to grant you some free credits to try it out - he just asks that you provide honest feedback on the experience in return.
{t(locale, "emails.creditDenied.mistakeNote")}
If you'd like to get started right away, you can also purchase credits:
{t(locale, "emails.creditDenied.buyPrompt")}
{self.buy_url}
---
© {self._get_year()} Nomad Karaoke
"""
html_content = self._build_email_html(content)
html_content = self._build_email_html(content, locale=locale)
return self.provider.send_email(
to_email=email,
@@ -132,6 +132,7 @@ class JobNotificationService:
feedback_url=FEEDBACK_FORM_URL,
is_private=is_private,
youtube_queued=youtube_queued,
locale=user_locale,
)
# Send the email with CC to admin
@@ -195,6 +196,7 @@ class JobNotificationService:
artist=artist,
title=title,
youtube_url=youtube_url,
locale=user_locale,
)
success = self.email_service.send_youtube_upload_complete(
@@ -269,6 +271,7 @@ class JobNotificationService:
artist=artist,
title=title,
review_url=review_url,
locale=user_locale,
)
elif action_type == "instrumental":
instrumental_url = self._build_instrumental_url(job_id, instrumental_token, locale=user_locale)
@@ -277,6 +280,7 @@ class JobNotificationService:
artist=artist,
title=title,
instrumental_url=instrumental_url,
locale=user_locale,
)
elif action_type == "audio_edit":
audio_edit_url = self._build_audio_edit_url(job_id, locale=user_locale)
@@ -286,6 +290,7 @@ class JobNotificationService:
artist=artist,
title=title,
review_url=audio_edit_url,
locale=user_locale,
)
else:
logger.error(f"Unknown action type: {action_type}")
+126 -20
View File
@@ -14,6 +14,7 @@ import re
from typing import Optional, Dict, Any
from backend.config import get_settings
from backend.i18n import t
logger = logging.getLogger(__name__)
@@ -154,29 +155,48 @@ class TemplateService:
logger.error(f"Failed to fetch template {blob_path}: {e}")
return None
def get_job_completion_template(self) -> str:
def get_job_completion_template(self, locale: str = "en") -> str:
"""Get the job completion email template."""
# Try locale-specific GCS template first, then default GCS, then localized default
if locale != "en":
template = self._fetch_template_from_gcs(f"{locale}/job-completion.txt")
if template is not None:
return template
template = self._fetch_template_from_gcs("job-completion.txt")
if template is None:
logger.info("Using default job completion template")
if template is not None:
return template
logger.info("Using default job completion template")
if locale == "en":
return DEFAULT_JOB_COMPLETION_TEMPLATE
return template
return self._build_localized_job_completion_template(locale)
def get_action_needed_lyrics_template(self) -> str:
def get_action_needed_lyrics_template(self, locale: str = "en") -> str:
"""Get the lyrics review reminder template."""
if locale != "en":
template = self._fetch_template_from_gcs(f"{locale}/action-needed-lyrics.txt")
if template is not None:
return template
template = self._fetch_template_from_gcs("action-needed-lyrics.txt")
if template is None:
logger.info("Using default lyrics reminder template")
if template is not None:
return template
logger.info("Using default lyrics reminder template")
if locale == "en":
return DEFAULT_ACTION_NEEDED_LYRICS_TEMPLATE
return template
return self._build_localized_action_lyrics_template(locale)
def get_action_needed_instrumental_template(self) -> str:
def get_action_needed_instrumental_template(self, locale: str = "en") -> str:
"""Get the instrumental selection reminder template."""
if locale != "en":
template = self._fetch_template_from_gcs(f"{locale}/action-needed-instrumental.txt")
if template is not None:
return template
template = self._fetch_template_from_gcs("action-needed-instrumental.txt")
if template is None:
logger.info("Using default instrumental reminder template")
if template is not None:
return template
logger.info("Using default instrumental reminder template")
if locale == "en":
return DEFAULT_ACTION_NEEDED_INSTRUMENTAL_TEMPLATE
return template
return self._build_localized_action_instrumental_template(locale)
def render_template(self, template: str, variables: Dict[str, Any]) -> str:
"""
@@ -215,6 +235,74 @@ class TemplateService:
return result.strip()
def _build_localized_job_completion_template(self, locale: str) -> str:
"""Build a localized job completion template from translation keys."""
ns = "emails.templates.jobCompletion"
return f"""{t(locale, f"{ns}.greeting")}
{t(locale, f"{ns}.thanks")}
{t(locale, f"{ns}.youtubeLink")}
{{youtube_url}}
{t(locale, f"{ns}.dropboxIntro")}
{t(locale, f"{ns}.fileList")}
{{dropbox_url}}
{t(locale, f"{ns}.fixOffer")}
{t(locale, f"{ns}.feedbackRequest")}
{{feedback_url}}
{t(locale, f"{ns}.signOff")}
"""
def _build_localized_action_lyrics_template(self, locale: str) -> str:
"""Build a localized action-needed lyrics template."""
ns = "emails.templates.actionLyrics"
return f"""{t(locale, f"{ns}.greeting")}
{t(locale, f"{ns}.ready")}
{t(locale, f"{ns}.instructions")}
{t(locale, f"{ns}.reviewPrompt")}
{{review_url}}
{t(locale, f"{ns}.duration")}
{t(locale, f"{ns}.signOff")}
"""
def _build_localized_action_instrumental_template(self, locale: str) -> str:
"""Build a localized action-needed instrumental template."""
ns = "emails.templates.actionInstrumental"
return f"""{t(locale, f"{ns}.greeting")}
{t(locale, f"{ns}.almostDone")}
{t(locale, f"{ns}.instructions")}
{t(locale, f"{ns}.selectPrompt")}
{{instrumental_url}}
{t(locale, f"{ns}.signOff")}
"""
def _build_localized_youtube_complete_template(self, locale: str) -> str:
"""Build a localized YouTube upload complete template."""
ns = "emails.templates.youtubeComplete"
return f"""{t(locale, f"{ns}.greeting")}
{t(locale, f"{ns}.greatNews")}
{{youtube_url}}
{t(locale, f"{ns}.delayNote")}
{t(locale, f"{ns}.signOff")}
"""
def render_job_completion(
self,
name: Optional[str] = None,
@@ -226,6 +314,7 @@ class TemplateService:
feedback_url: Optional[str] = None,
is_private: bool = False,
youtube_queued: bool = False,
locale: str = "en",
) -> str:
"""
Render the job completion email template.
@@ -244,7 +333,7 @@ class TemplateService:
Returns:
Rendered email content
"""
template = self.get_job_completion_template()
template = self.get_job_completion_template(locale)
# For private tracks, remove the YouTube section entirely
if is_private:
@@ -255,11 +344,18 @@ class TemplateService:
)
elif youtube_queued and not youtube_url:
# Replace YouTube URL with pending message
queued_msg = t(locale, "emails.templates.jobCompletion.youtubeQueued")
youtube_link_text = t(locale, "emails.templates.jobCompletion.youtubeLink")
template = template.replace(
"Here's the link for the karaoke video published to YouTube:\n{youtube_url}",
"Your YouTube upload is queued and will be processed automatically. "
"You'll receive a follow-up email with the link shortly."
f"{youtube_link_text}\n{{youtube_url}}",
queued_msg
)
# Also handle the English default template pattern
if "{youtube_url}" in template:
template = template.replace(
"Here's the link for the karaoke video published to YouTube:\n{youtube_url}",
queued_msg
)
variables = {
"name": name or "there",
@@ -278,6 +374,7 @@ class TemplateService:
artist: Optional[str] = None,
title: Optional[str] = None,
review_url: str = "",
locale: str = "en",
) -> str:
"""
Render the combined review reminder template.
@@ -294,7 +391,7 @@ class TemplateService:
Returns:
Rendered email content
"""
template = self.get_action_needed_lyrics_template()
template = self.get_action_needed_lyrics_template(locale)
variables = {
"name": name or "there",
"artist": artist or "Unknown Artist",
@@ -309,6 +406,7 @@ class TemplateService:
artist: Optional[str] = None,
title: Optional[str] = None,
instrumental_url: str = "",
locale: str = "en",
) -> str:
"""
Render the instrumental selection reminder template.
@@ -326,7 +424,7 @@ class TemplateService:
Returns:
Rendered email content
"""
template = self.get_action_needed_instrumental_template()
template = self.get_action_needed_instrumental_template(locale)
variables = {
"name": name or "there",
"artist": artist or "Unknown Artist",
@@ -341,6 +439,7 @@ class TemplateService:
artist: Optional[str] = None,
title: Optional[str] = None,
youtube_url: Optional[str] = None,
locale: str = "en",
) -> str:
"""
Render the YouTube upload complete follow-up email template.
@@ -356,9 +455,16 @@ class TemplateService:
Returns:
Rendered email content
"""
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
if locale != "en":
template = self._fetch_template_from_gcs(f"{locale}/youtube-upload-complete.txt")
if template is not None:
pass # Use locale-specific GCS template
else:
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
else:
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
if template is None:
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE if locale == "en" else self._build_localized_youtube_complete_template(locale)
variables = {
"name": name or "there",
+136 -36
View File
@@ -4,15 +4,15 @@
"invalidCredentials": "Die folgenden Dienste müssen neu autorisiert werden: {services}",
"validCredentials": "Alle angeforderten Anmeldeinformationen sind gültig",
"youtubeAuthInstructions": "Besuche {verification_url} und gib den Code ein: {user_code}",
"youtubeAuthStartFailed": "Starten der YouTube-Geräteauthentifizierung fehlgeschlagen: {error}",
"youtubeAuthStartFailed": "Fehler beim Starten der YouTube-Geräteauthentifizierung: {error}",
"gdriveLinkInstructions": "Besuche {verification_url} und gib den Code ein: {user_code}",
"gdriveAuthStartFailed": "Starten der Google Drive-Geräteauthentifizierung fehlgeschlagen: {error}",
"gdriveAuthStartFailed": "Fehler beim Starten der Google Drive-Geräteauthentifizierung: {error}",
"discordAlertNotConfigured": "Discord-Alert-Webhook nicht konfiguriert"
},
"jobs": {
"created": "Auftrag erfolgreich erstellt. Verarbeitung gestartet.",
"authError": "Authentifizierungsfehler: Keine Benutzeridentität verfügbar",
"noDefaultTheme": "Kein Standard-Theme konfiguriert. Bitte kontaktiere den Support oder gib eine theme_id an.",
"noDefaultTheme": "Kein Standard-Theme konfiguriert. Bitte wende dich an den Support oder gib eine theme_id an.",
"notFound": "Auftrag nicht gefunden",
"noPermissionAccess": "Du hast keine Berechtigung, auf diesen Auftrag zuzugreifen",
"noPermissionEdit": "Du hast keine Berechtigung, diesen Auftrag zu bearbeiten",
@@ -28,19 +28,19 @@
"deletionPreview": "Füge &confirm=true hinzu, um die Löschung auszuführen",
"deletionRequiresFilters": "Mindestens ein Filter (environment, client_id, status, created_before) ist erforderlich",
"bulkDeleteError": "Fehler beim massenhaften Löschen von Aufträgen: {error}",
"reviewNotReady": "Auftrag nicht bereit zur Überprüfung (aktueller Status: {status})",
"reviewNotReady": "Auftrag noch nicht bereit für die Überprüfung (aktueller Status: {status})",
"correctionsUnavailable": "Korrekturdaten nicht verfügbar",
"audioUnavailable": "Audio nicht zur Überprüfung verfügbar",
"audioUnavailable": "Audio für die Überprüfung nicht verfügbar",
"reviewCannotStart": "Überprüfung kann nicht gestartet werden",
"jobNotInReviewState": "Auftrag nicht im Überprüfungsstatus (aktueller Status: {status})",
"jobNotInReviewState": "Auftrag befindet sich nicht im Überprüfungsstatus (aktueller Status: {status})",
"correctionsProcessing": "Korrekturen gespeichert. Rufe /complete-review auf, wenn du fertig bist.",
"editLogSaveFailed": "Fehler beim Speichern des Bearbeitungsprotokolls für Auftrag {job_id}: {error}",
"stemsMissing": "Dem Auftrag fehlen erforderliche Stems (instrumental_clean und/oder backing_vocals)",
"customInstrumentalFailed": "Fehler beim Erstellen des benutzerdefinierten Instrumentals für Auftrag {job_id}: {error}",
"audioProcessingFailed": "Fehler beim Verarbeiten der Audiodatei: {error}",
"durationMismatch": "Dauer stimmt nicht überein: Hochgeladene Datei ist {upload_duration}s lang, aber das Original-Audio ist {original_duration}s lang. Das Instrumental muss genau {original_duration}s (±0.5s) lang sein.",
"reviewNotInState": "Auftrag nicht im Überprüfungsstatus (aktueller Status: {status})",
"noLyricsDetected": "Überprüfung kann nicht abgeschlossen werden: Es wurde kein Text im Audio erkannt. Dies kann passieren, wenn das Eingabe-Audio keinen Gesang enthält (z. B. ein Karaoke-Track oder Instrumental). Du kannst zurückgehen und den Text manuell mit 'Alle ersetzen' einfügen oder diesen Auftrag abbrechen und es erneut mit einer Audiodatei versuchen, die Gesang enthält.",
"reviewNotInState": "Auftrag befindet sich nicht im Überprüfungsstatus (aktueller Status: {status})",
"noLyricsDetected": "Überprüfung kann nicht abgeschlossen werden: Es wurde kein Text im Audio erkannt. Dies kann passieren, wenn das Eingabe-Audio keinen Gesang enthält (z. B. ein Karaoke-Track oder Instrumental). Du kannst zurückgehen und den Text manuell mit 'Alle ersetzen' einfügen oder diesen Auftrag abbrechen und es mit einer Audiodatei versuchen, die Gesang enthält.",
"reviewCompleteStartRendering": "Überprüfung abgeschlossen. Rendern des Videos gestartet.",
"reviewCompleteError": "Fehler beim Abschließen der Überprüfung für Auftrag {job_id}: {error}",
"instrumentalSelectionRequired": "instrumental_selection ist erforderlich. Muss 'clean' oder 'with_backing' sein.",
@@ -51,8 +51,8 @@
},
"review": {
"jobNotFound": "Auftrag nicht gefunden",
"reviewNotReady": "Auftrag nicht bereit zur Überprüfung (aktueller Status: {status})",
"correctionsNotFound": "Korrekturdaten nicht gefunden. Die Textverarbeitung ist möglicherweise nicht abgeschlossen.",
"reviewNotReady": "Auftrag noch nicht bereit für die Überprüfung (aktueller Status: {status})",
"correctionsNotFound": "Korrekturdaten nicht gefunden. Die Textverarbeitung ist möglicherweise noch nicht abgeschlossen.",
"correctionsLoadFailed": "Fehler beim Laden der Korrekturen: {error}",
"audioNotFound": "Audiodatei nicht gefunden",
"audioServeError": "Fehler beim Bereitstellen von Audio: {error}",
@@ -64,7 +64,7 @@
"lyricsAddInvalidRequest": "Ungültige Anfrage zum Hinzufügen von Text: {error}",
"lyricsSearchError": "Fehler bei der Textsuche: {error}",
"lyricsSearchInvalidRequest": "Ungültige Anfrage zur Textsuche: {error}",
"lyricsSearchNoResults": "Bei keinem Anbieter wurde ein passender Text gefunden",
"lyricsSearchNoResults": "Kein passender Text bei keinem Anbieter gefunden",
"previewVideoGenerationError": "Fehler beim Generieren des Vorschau-Videos: {error}",
"previewVideoNotFound": "Vorschau-Video nicht gefunden",
"previewVideoStreamError": "Fehler beim Streamen des Vorschau-Videos: {error}",
@@ -74,7 +74,7 @@
"sessionSaveError": "Korrekturdaten sind erforderlich"
},
"audioSearch": {
"notEnabled": "Die Audiosuche ist für diesen Mandanten nicht aktiviert",
"notEnabled": "Audiosuche ist für diesen Mandanten nicht aktiviert",
"disabled": "Audiosuche ist nicht verfügbar",
"downloadError": "Download für Auftrag {job_id} fehlgeschlagen: {error}",
"jobNotFound": "Auftrag {job_id} nicht gefunden",
@@ -107,7 +107,7 @@
"stripeSendError": "Fehler beim Senden des Stripe-Checkout-Links: {error}",
"stripeWebhookProcessingError": "Fehler bei der Verarbeitung des Stripe-Webhooks: {error}",
"feedbackSaveError": "Fehler beim Speichern des Feedbacks: {error}",
"feedbackNotEligible": "Benutzer nicht für Feedback berechtigt"
"feedbackNotEligible": "Benutzer ist nicht für Feedback berechtigt"
},
"fileUpload": {
"invalidTheme": "Theme nicht gefunden: {theme_id}. Verwende GET /api/themes, um verfügbare Themes aufzulisten.",
@@ -148,7 +148,7 @@
"push": {
"disabled": "Push-Benachrichtigungen sind nicht aktiviert",
"userEmailNotAvailable": "Benutzer-E-Mail nicht verfügbar",
"missingEncryptionKeys": "Fehlende erforderliche Schlüssel (p256dh, auth)",
"missingEncryptionKeys": "Erforderliche Schlüssel fehlen (p256dh, auth)",
"subscriptionSaveFailed": "Fehler beim Speichern des Abonnements",
"subscriptionRegistered": "Push-Abonnement erfolgreich registriert",
"subscriptionNotFound": "Abonnement entfernt (oder wurde nicht gefunden)",
@@ -156,31 +156,31 @@
"testNotificationSent": "Testbenachrichtigung an {sent_count} Gerät(e) gesendet"
},
"pushNotifications": {
"reviewLyricsTitle": "Text überprüfen",
"reviewLyricsTitle": "Textüberprüfung",
"reviewLyricsBody": "\"{title}\" von {artist} benötigt eine Textüberprüfung",
"selectInstrumentalTitle": "Instrumental auswählen",
"selectInstrumentalBody": "\"{title}\" von {artist} benötigt eine Instrumentalauswahl",
"videoReadyTitle": "Video fertig!",
"videoReadyBody": "Dein Karaoke-Video für \"{title}\" von {artist} ist bereit zum Herunterladen"
"videoReadyBody": "Dein Karaoke-Video für \"{title}\" von {artist} ist zum Download bereit"
},
"admin": {
"invalidDomainFormat": "Ungültiges Domain-Format",
"domainAddedToBl": "Domain '{domain}' zur Sperrliste für Wegwerf-Domains hinzugefügt",
"domainNotFoundInBl": "Domain nicht in der Sperrliste gefunden",
"domainRemovedFromBl": "Domain '{domain}' aus der Sperrliste für Wegwerf-Domains entfernt",
"domainAddedToAllowlist": "Domain '{domain}' zur Erlaubnisliste hinzugefügt",
"domainNotFoundInAllowlist": "Domain nicht in der Erlaubnisliste gefunden",
"domainRemovedFromAllowlist": "Domain '{domain}' aus der Erlaubnisliste entfernt",
"domainAddedToBl": "Domain '{domain}' zur Blockliste für Wegwerf-Domains hinzugefügt",
"domainNotFoundInBl": "Domain nicht in der Blockliste gefunden",
"domainRemovedFromBl": "Domain '{domain}' aus der Blockliste für Wegwerf-Domains entfernt",
"domainAddedToAllowlist": "Domain '{domain}' zur Allowlist hinzugefügt",
"domainNotFoundInAllowlist": "Domain nicht in der Allowlist gefunden",
"domainRemovedFromAllowlist": "Domain '{domain}' aus der Allowlist entfernt",
"syncComplete": "{external_count} externe Domains synchronisiert ({added} hinzugefügt, {removed} entfernt)",
"invalidEmailFormat": "Ungültiges E-Mail-Format",
"emailAddedToBl": "E-Mail '{email}' zur Liste blockierter E-Mails hinzugefügt",
"emailNotFoundInBl": "E-Mail nicht in der Sperrliste gefunden",
"emailNotFoundInBl": "E-Mail nicht in der Blockliste gefunden",
"emailRemovedFromBl": "E-Mail '{email}' aus der Liste blockierter E-Mails entfernt",
"invalidIPAddress": "Ungültige IP-Adresse",
"ipAddedToBl": "IP '{ip_address}' zur Liste blockierter IPs hinzugefügt",
"ipNotFoundInBl": "IP nicht in der Sperrliste gefunden",
"ipNotFoundInBl": "IP nicht in der Blockliste gefunden",
"ipRemovedFromBl": "IP '{ip_address}' aus der Liste blockierter IPs entfernt",
"youtubeUploadNotFound": "Upload nicht gefunden oder nicht in einem wiederholbaren Status für Auftrag {job_id}",
"youtubeUploadNotFound": "Upload für Auftrag {job_id} nicht gefunden oder nicht in einem wiederholbaren Status",
"youtubeUploadQueuedForRetry": "YouTube-Upload für Auftrag {job_id} für erneuten Versuch in die Warteschlange eingereiht",
"youtubeQueueProcessingStarted": "Verarbeitung der YouTube-Warteschlange im Hintergrund gestartet"
},
@@ -194,13 +194,44 @@
},
"emails": {
"magicLink": {
"subject": "Melde dich bei {brand_name} an"
"subject": "Melde dich bei {brand_name} an",
"greeting": "Hallo,",
"signInPrompt": "Klicke auf den Button unten, um dich bei {brand_name} anzumelden:",
"signInButton": "Anmelden",
"expiryWarning": "Dieser Link läuft in 15 Minuten ab und kann nur einmal verwendet werden.",
"fallbackLink": "Wenn der Button nicht funktioniert, kopiere diesen Link und füge ihn in deinen Browser ein:",
"ignoreNote": "Wenn du diese E-Mail nicht angefordert hast, kannst du sie getrost ignorieren."
},
"welcome": {
"subject": "Willkommen bei Nomad Karaoke!"
"subject": "Willkommen bei Nomad Karaoke!",
"welcomeGreeting": "Willkommen bei Nomad Karaoke!",
"turnAnySong": "Verwandle jeden Song in wenigen Minuten in ein professionelles Karaoke-Video.",
"freeCreditsLabel": "Kostenloses Guthaben",
"freeCreditsNote": "Jedes Guthaben reicht für ein professionelles Karaoke-Video",
"howItWorks": "So funktioniert's:",
"step1Title": "1. Suche nach einem Song",
"step1Desc": "Gib Künstler und Titel ein, und wir finden hochwertiges Audio.",
"step2Title": "2. Unser System zaubert",
"step2Desc": "Wir trennen den Gesang, transkribieren den Text und synchronisieren alles perfekt.",
"step3Title": "3. Überprüfen & anpassen",
"step3Desc": "Passe den Text bei Bedarf an und wähle dein Instrumental.",
"step4Title": "4. Hol dir dein Video",
"step4Desc": "Lade dein 4K-Karaoke-Video herunter oder lade es direkt auf YouTube hoch.",
"feedbackBonus": "Stelle 2 Videos fertig und erhalte 2 weitere kostenlose Guthaben, indem du dein Feedback teilst!",
"getStartedButton": "Loslegen"
},
"creditsAdded": {
"subject": "{credits} Guthaben zu deinem Nomad Karaoke-Konto hinzugefügt"
"subject": "{credits} Guthaben zu deinem Nomad Karaoke-Konto hinzugefügt",
"greatNews": "Tolle Neuigkeiten!",
"creditsAddedMessage": "{credits} Guthaben wurden deinem Konto hinzugefügt.",
"yourBalance": "Dein Kontostand:",
"credits": "Guthaben",
"eachCreditLets": "Mit jedem Guthaben kannst du ein professionelles Karaoke-Video erstellen mit:",
"featureVocalSeparation": "KI-gestützte Gesangs-/Instrumentaltrennung",
"featureLyrics": "Synchronisierter Text mit Timing auf Wortebene",
"feature4k": "4K-Videoausgabe",
"featureYoutube": "YouTube-Upload",
"createButton": "Jetzt Karaoke erstellen"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Dein Karaoke-Video ist fertig!)",
@@ -213,26 +244,95 @@
"subjectFallback": "Dein YouTube-Upload ist bereit!"
},
"actionReminder": {
"lyricsSubject": "Aktion erforderlich: Text für {artist} - {title} überprüfen",
"lyricsSubjectFallback": "Aktion erforderlich: Text überprüfen",
"instrumentalSubject": "Aktion erforderlich: Instrumental für {artist} - {title} auswählen",
"lyricsSubject": "Aktion erforderlich: Textüberprüfung für {artist} - {title}",
"lyricsSubjectFallback": "Aktion erforderlich: Textüberprüfung",
"instrumentalSubject": "Aktion erforderlich: Instrumental auswählen für {artist} - {title}",
"instrumentalSubjectFallback": "Aktion erforderlich: Instrumental auswählen",
"audioEditSubject": "Aktion erforderlich für {artist} - {title}",
"audioEditSubjectFallback": "Aktion erforderlich"
"audioEditSubjectFallback": "Aktion erforderlich",
"alertHeading": "Dein Karaoke-Video benötigt deine Eingabe!"
},
"reviewReminder": {
"subject": "Erinnerung: Dein Karaoke-Video wartet auf Überprüfung — {artist} - {title}",
"subjectFallback": "Erinnerung: Dein Karaoke-Video wartet auf Überprüfung"
"subjectFallback": "Erinnerung: Dein Karaoke-Video wartet auf Überprüfung",
"alertHeading": "Dein Karaoke-Video wartet auf dich!",
"reminderIntro": "Nur eine kurze Erinnerung, dass dein Karaoke-Video{song_name} zur Überprüfung bereit ist.",
"reviewButton": "Dein Video überprüfen",
"reviewInstructions": "Während der Überprüfung kannst du kontrollieren, ob der Text korrekt ist, und deine bevorzugte Instrumentalspur auswählen. Das dauert normalerweise nur wenige Minuten!",
"helpOffer": "Wenn du Probleme mit dem Überprüfungsprozess hast, antworte einfach auf diese E-Mail und ich helfe dir gerne weiter.",
"expiryWarning": "Bitte beachte: Wenn die Überprüfung nicht innerhalb der nächsten 24 Stunden abgeschlossen wird, läuft der Auftrag automatisch ab und dein Guthaben wird erstattet."
},
"reviewExpired": {
"subject": "Dein Karaoke-Video ist abgelaufen — {artist} - {title}",
"subjectFallback": "Dein Karaoke-Video ist abgelaufen"
"subjectFallback": "Dein Karaoke-Video ist abgelaufen",
"cancelNotice": "Dein Karaoke-Video{song_name} wurde automatisch abgebrochen, da die Überprüfung nicht innerhalb von 48 Stunden abgeschlossen wurde.",
"refundNotice": "Keine Sorge — dein Guthaben wurde erstattet! Dein aktueller Kontostand beträgt {credits_balance} {credits_word}.",
"creditSingular": "Guthaben",
"creditPlural": "Guthaben",
"createNewPrompt": "Du kannst jederzeit ein neues Karaoke-Video mit deinem Guthaben erstellen:",
"createButton": "Neues Video erstellen",
"helpOffer": "Wenn du Probleme mit dem Überprüfungsprozess hattest oder Hilfe benötigst, antworte einfach auf diese E-Mail — ich helfe dir gerne!"
},
"creditDenied": {
"subject": "Über dein kostenloses Nomad Karaoke-Guthaben"
"subject": "Über dein kostenloses Nomad Karaoke-Guthaben",
"greeting": "Hallo,",
"thankYou": "Danke für deine Anmeldung bei Nomad Karaoke!",
"deniedMessage": "Leider konnten wir dir dieses Mal dein kostenloses {credit_type} nicht gewähren. Unser System hat Muster erkannt, die darauf hindeuten, dass dies möglicherweise nicht dein erstes Konto bei uns ist, und jeder Karaoke-Generierungsauftrag kostet uns echtes Geld an Cloud-Computing- und API-Gebühren.",
"mistakeNote": "Wir verstehen vollkommen, wenn das ein Fehler ist! Wenn du ein echter neuer Benutzer bist, antworte einfach auf diese E-Mail und lass es Andrew (dem Gründer) wissen. Er hat diesen Dienst entwickelt und gibt dir gerne ein paar kostenlose Guthaben zum Ausprobieren — er bittet dich nur darum, im Gegenzug ehrliches Feedback zur Erfahrung zu geben.",
"buyPrompt": "Wenn du sofort loslegen möchtest, kannst du auch Guthaben kaufen:",
"buyButton": "Guthaben kaufen",
"costNote": "Wir halten die Kosten niedrig, damit wir den Dienst günstig anbieten können, was bedeutet, dass wir bei Missbrauch von kostenlosem Guthaben vorsichtig sein müssen. Danke für dein Verständnis!",
"welcomeCredits": "Willkommens-Guthaben",
"feedbackCredits": "Feedback-Bonus-Guthaben"
},
"madeForYouConfirmation": {
"subject": "Bestellung bestätigt: {artist} - {title} | Nomad Karaoke"
"subject": "Bestellung bestätigt: {artist} - {title} | Nomad Karaoke",
"thankYou": "Vielen Dank für deine Bestellung!",
"orderDetails": "Bestelldetails",
"orderId": "Bestell-ID:",
"artist": "Künstler:",
"title": "Titel:",
"yourNotes": "Deine Notizen:",
"deliveryTime": "Unser Team wird dein individuelles Karaoke-Video innerhalb von {hours} Stunden erstellen.",
"deliveryNotice": "Du erhältst eine E-Mail mit Download-Links, sobald dein Video fertig ist.",
"noAction": "Keine Aktion erforderlich — lehn dich zurück und wir kümmern uns um alles!"
},
"shared": {
"footerHelp": "Wenn etwas nicht perfekt ist, antworte einfach auf diese E-Mail und ich werde es beheben!"
},
"templates": {
"jobCompletion": {
"greeting": "Hallo {name},",
"thanks": "Danke für deine Bestellung!",
"youtubeLink": "Hier ist der Link für das auf YouTube veröffentlichte Karaoke-Video:",
"dropboxIntro": "Hier ist der Dropbox-Ordner mit allen fertigen Dateien und Quelldateien, einschließlich:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": kombiniertes Karaoke-Video in 4K H264 mit verlustfreiem FLAC-Audio\n- \"(Final Karaoke).mp4\": kombiniertes Karaoke-Video mit Titel-/Endbildschirm in 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": kombiniertes Karaoke-Video in 720p H264/AAC (kleinere Datei für ältere Systeme)\n- \"(With Vocals).mp4\": Video zum Mitsingen in 4K H264/AAC mit Originalgesang\n- \"(Karaoke).mov\": Karaoke-Videoausgabe von MidiCo (ohne Titel-/Endbildschirm)\n- \"(Title).mov\"/\"(End).mov\": Titelkarten- und Endbildschirm-Videos\n- \"(Final Karaoke CDG).zip\": CDG+MP3-Format für ältere/kommerzielle Karaoke-Systeme\n- \"(Final Karaoke TXT).zip\": TXT+MP3-Format für Power Karaoke\n- stems/*.flac: verschiedene getrennte Instrumental- und Gesangs-Audio-Stems im verlustfreien Format\n- lyrics/*.txt Songtexte aus verschiedenen Quellen im reinen Textformat",
"fixOffer": "Lass mich wissen, wenn etwas nicht perfekt ist. Ich passe es gerne an oder behebe es. Wenn du ein anderes Format benötigst, kann ich es wahrscheinlich für dich konvertieren!",
"feedbackRequest": "Wenn du einen Moment Zeit hast, würde ich mich sehr über dein Feedback freuen (dauert 2 Minuten):",
"signOff": "Nochmals vielen Dank und einen schönen Tag!\n-Andrew",
"youtubeQueued": "Dein YouTube-Upload ist in der Warteschlange und wird automatisch verarbeitet. Du erhältst in Kürze eine Folge-E-Mail mit dem Link."
},
"actionLyrics": {
"greeting": "Hallo {name},",
"ready": "Dein Karaoke-Video für \"{artist} - {title}\" ist zur Überprüfung bereit!",
"instructions": "Unser System hat den Text transkribiert und synchronisiert, aber er benötigt möglicherweise einige Korrekturen. Du kannst auch deine bevorzugte Instrumentalspur (mit oder ohne Hintergrundgesang) auswählen.",
"reviewPrompt": "Bitte überprüfe deinen Text und wähle ein Instrumental aus:",
"duration": "Das dauert normalerweise nur wenige Minuten.",
"signOff": "Danke!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hallo {name},",
"almostDone": "Dein Karaoke-Video für \"{artist} - {title}\" ist fast fertig!",
"instructions": "Wir haben das Audio in verschiedene Versionen getrennt. Bitte wähle aus, welche Instrumentalspur du für das endgültige Video verwenden möchtest.",
"selectPrompt": "Wähle hier dein Instrumental aus:",
"signOff": "Danke!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hallo {name},",
"greatNews": "Tolle Neuigkeiten! Dein Karaoke-Video für \"{artist} - {title}\" wurde auf YouTube hochgeladen:",
"delayNote": "Dieser Upload hat sich kurz verzögert, während unsere Systeme andere Uploads verarbeitet haben, aber jetzt ist alles bereit.",
"signOff": "Danke!\n-Andrew"
}
}
}
}
+108 -8
View File
@@ -194,13 +194,44 @@
},
"emails": {
"magicLink": {
"subject": "Sign in to {brand_name}"
"subject": "Sign in to {brand_name}",
"greeting": "Hi there,",
"signInPrompt": "Click the button below to sign in to {brand_name}:",
"signInButton": "Sign In",
"expiryWarning": "This link expires in 15 minutes and can only be used once.",
"fallbackLink": "If the button doesn't work, copy and paste this link into your browser:",
"ignoreNote": "If you didn't request this email, you can safely ignore it."
},
"welcome": {
"subject": "Welcome to Nomad Karaoke!"
"subject": "Welcome to Nomad Karaoke!",
"welcomeGreeting": "Welcome to Nomad Karaoke!",
"turnAnySong": "Turn any song into a professional karaoke video in minutes.",
"freeCreditsLabel": "Free Credits",
"freeCreditsNote": "Each credit creates one professional karaoke video",
"howItWorks": "Here's how it works:",
"step1Title": "1. Search for a song",
"step1Desc": "Enter the artist and title, and we'll find high-quality audio.",
"step2Title": "2. Our system works its magic",
"step2Desc": "We separate vocals, transcribe lyrics, and sync everything perfectly.",
"step3Title": "3. Review & customize",
"step3Desc": "Fine-tune the lyrics if needed, choose your instrumental.",
"step4Title": "4. Get your video",
"step4Desc": "Download your 4K karaoke video or upload directly to YouTube.",
"feedbackBonus": "Complete 2 videos and earn 2 more free credits by sharing your feedback!",
"getStartedButton": "Get Started"
},
"creditsAdded": {
"subject": "{credits} credits added to your Nomad Karaoke account"
"subject": "{credits} credits added to your Nomad Karaoke account",
"greatNews": "Great news!",
"creditsAddedMessage": "{credits} credits have been added to your account.",
"yourBalance": "Your balance:",
"credits": "credits",
"eachCreditLets": "Each credit lets you create one professional karaoke video with:",
"featureVocalSeparation": "AI-powered vocal/instrumental separation",
"featureLyrics": "Synchronized lyrics with word-level timing",
"feature4k": "4K video output",
"featureYoutube": "YouTube upload",
"createButton": "Create Karaoke Now"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (Your karaoke video is ready!)",
@@ -218,21 +249,90 @@
"instrumentalSubject": "Action needed: Select instrumental for {artist} - {title}",
"instrumentalSubjectFallback": "Action needed: Select instrumental",
"audioEditSubject": "Action needed for {artist} - {title}",
"audioEditSubjectFallback": "Action needed"
"audioEditSubjectFallback": "Action needed",
"alertHeading": "Your karaoke video needs input from you!"
},
"reviewReminder": {
"subject": "Reminder: Your karaoke video is waiting for review — {artist} - {title}",
"subjectFallback": "Reminder: Your karaoke video is waiting for review"
"subjectFallback": "Reminder: Your karaoke video is waiting for review",
"alertHeading": "Your karaoke video is waiting for you!",
"reminderIntro": "Just a friendly reminder that your karaoke video{song_name} is ready for review.",
"reviewButton": "Review Your Video",
"reviewInstructions": "During the review, you can check the lyrics are correct and choose your preferred instrumental track. It usually only takes a few minutes!",
"helpOffer": "If you're having any trouble with the review process, just reply to this email and I'll be happy to help you out.",
"expiryWarning": "Please note: if the review isn't completed within the next 24 hours, the job will automatically expire and your credit will be refunded."
},
"reviewExpired": {
"subject": "Your karaoke video has expired — {artist} - {title}",
"subjectFallback": "Your karaoke video has expired"
"subjectFallback": "Your karaoke video has expired",
"cancelNotice": "Your karaoke video{song_name} has been automatically cancelled because the review wasn't completed within 48 hours.",
"refundNotice": "Don't worry — your credit has been refunded! Your current balance is {credits_balance} {credits_word}.",
"creditSingular": "credit",
"creditPlural": "credits",
"createNewPrompt": "You can create a new karaoke video anytime using your credits:",
"createButton": "Create New Video",
"helpOffer": "If you had any trouble with the review process or need help, just reply to this email — I'd love to help!"
},
"creditDenied": {
"subject": "About your Nomad Karaoke free credits"
"subject": "About your Nomad Karaoke free credits",
"greeting": "Hi there,",
"thankYou": "Thanks for signing up for Nomad Karaoke!",
"deniedMessage": "Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected patterns that suggest this may not be your first account with us, and each karaoke generation job costs us real money in cloud computing and API fees.",
"mistakeNote": "We totally understand if this is a mistake! If you're a genuine new user, please just reply to this email and let Andrew (the founder) know. He built this service and is happy to grant you some free credits to try it out — he just asks that you provide honest feedback on the experience in return.",
"buyPrompt": "If you'd like to get started right away, you can also purchase credits:",
"buyButton": "Buy Credits",
"costNote": "We keep costs low so we can offer the service affordably, which means we need to be careful about free credit abuse. Thanks for understanding!",
"welcomeCredits": "welcome credits",
"feedbackCredits": "feedback bonus credits"
},
"madeForYouConfirmation": {
"subject": "Order Confirmed: {artist} - {title} | Nomad Karaoke"
"subject": "Order Confirmed: {artist} - {title} | Nomad Karaoke",
"thankYou": "Thank You for Your Order!",
"orderDetails": "Order Details",
"orderId": "Order ID:",
"artist": "Artist:",
"title": "Title:",
"yourNotes": "Your Notes:",
"deliveryTime": "Our team will create your custom karaoke video within {hours} hours.",
"deliveryNotice": "You'll receive an email with download links as soon as your video is ready.",
"noAction": "No action needed — sit back and we'll take care of everything!"
},
"shared": {
"footerHelp": "If anything isn't perfect, just reply to this email and I'll fix it!"
},
"templates": {
"jobCompletion": {
"greeting": "Hi {name},",
"thanks": "Thanks for your order!",
"youtubeLink": "Here's the link for the karaoke video published to YouTube:",
"dropboxIntro": "Here's the dropbox folder with all the finished files and source files, including:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": combined karaoke video in 4k H264 with lossless FLAC audio\n- \"(Final Karaoke).mp4\": combined karaoke video with title/end screen in 4k H264/AAC\n- \"(Final Karaoke 720p).mp4\": combined karaoke video in 720p H264/AAC (smaller file for older systems)\n- \"(With Vocals).mp4\": sing along video in 4k H264/AAC with original vocals\n- \"(Karaoke).mov\": karaoke video output from MidiCo (no title/end screen)\n- \"(Title).mov\"/\"(End).mov\": title card and end screen videos\n- \"(Final Karaoke CDG).zip\": CDG+MP3 format for older/commercial karaoke systems\n- \"(Final Karaoke TXT).zip\": TXT+MP3 format for Power Karaoke\n- stems/*.flac: various separated instrumental and vocal audio stems in lossless format\n- lyrics/*.txt song lyrics from various sources in plain text format",
"fixOffer": "Let me know if anything isn't perfect and I'll happily tweak / fix, or if you need it in any other format I can probably convert it for you!",
"feedbackRequest": "If you have a moment, I'd really appreciate your feedback (takes 2 minutes):",
"signOff": "Thanks again and have a great day!\n-Andrew",
"youtubeQueued": "Your YouTube upload is queued and will be processed automatically. You'll receive a follow-up email with the link shortly."
},
"actionLyrics": {
"greeting": "Hi {name},",
"ready": "Your karaoke video for \"{artist} - {title}\" is ready for review!",
"instructions": "Our system has transcribed and synchronized the lyrics, but they may need some corrections. You'll also be able to select your preferred instrumental track (with or without backing vocals).",
"reviewPrompt": "Please review your lyrics and select an instrumental:",
"duration": "This usually takes just a few minutes.",
"signOff": "Thanks!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hi {name},",
"almostDone": "Your karaoke video for \"{artist} - {title}\" is almost done!",
"instructions": "We've separated the audio into different versions. Please select which instrumental track you'd like to use for the final video.",
"selectPrompt": "Select your instrumental here:",
"signOff": "Thanks!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hi {name},",
"greatNews": "Great news! Your karaoke video for \"{artist} - {title}\" has been uploaded to YouTube:",
"delayNote": "This upload was briefly delayed while our systems processed other uploads, but everything is all set now.",
"signOff": "Thanks!\n-Andrew"
}
}
}
}
+155 -55
View File
@@ -1,16 +1,16 @@
{
"auth": {
"unknownService": "Servicio desconocido: {service}",
"invalidCredentials": "Los siguientes servicios necesitan volver a autorizarse: {services}",
"invalidCredentials": "Los siguientes servicios necesitan reautorización: {services}",
"validCredentials": "Todas las credenciales solicitadas son válidas",
"youtubeAuthInstructions": "Visita {verification_url} e ingresa el código: {user_code}",
"youtubeAuthStartFailed": "Error al iniciar la autorización del dispositivo de YouTube: {error}",
"youtubeAuthStartFailed": "Error al iniciar la autenticación del dispositivo en YouTube: {error}",
"gdriveLinkInstructions": "Visita {verification_url} e ingresa el código: {user_code}",
"gdriveAuthStartFailed": "Error al iniciar la autorización del dispositivo de Google Drive: {error}",
"discordAlertNotConfigured": "El webhook de alerta de Discord no está configurado"
"gdriveAuthStartFailed": "Error al iniciar la autenticación del dispositivo en Google Drive: {error}",
"discordAlertNotConfigured": "Webhook de alerta de Discord no configurado"
},
"jobs": {
"created": "Trabajo creado con éxito. El procesamiento ha comenzado.",
"created": "Trabajo creado con éxito. Se ha iniciado el procesamiento.",
"authError": "Error de autenticación: no hay identidad de usuario disponible",
"noDefaultTheme": "No hay un tema predeterminado configurado. Por favor, contacta a soporte o especifica un theme_id.",
"notFound": "Trabajo no encontrado",
@@ -19,43 +19,43 @@
"noPermissionDelete": "No tienes permiso para eliminar este trabajo",
"noPermissionModify": "No tienes permiso para modificar este trabajo",
"notCompleted": "Solo se pueden editar los trabajos completados. Estado actual: {status}",
"alreadyBeingEdited": "Este trabajo ya está siendo editado (los resultados ya fueron eliminados)",
"cleanupFailed": "La limpieza falló para {services}. El trabajo no fue modificado. Por favor, inténtalo de nuevo o contacta a soporte.",
"reopened": "Pista reabierta para edición. Los resultados anteriores han sido eliminados.",
"alreadyBeingEdited": "Este trabajo ya se está editando (los archivos de salida ya fueron eliminados)",
"cleanupFailed": "Error en la limpieza de {services}. El trabajo no fue modificado. Por favor, intenta de nuevo o contacta a soporte.",
"reopened": "Pista reabierta para edición. Los archivos de salida anteriores han sido eliminados.",
"invalidDatetimeFormat": "Formato de {field} inválido: {value}",
"listError": "Error al listar los trabajos: {error}",
"listError": "Error al listar trabajos: {error}",
"deleteError": "Error al eliminar el trabajo {job_id}: {error}",
"deletionPreview": "Agrega &confirm=true para ejecutar la eliminación",
"deletionRequiresFilters": "Se requiere al menos un filtro (environment, client_id, status, created_before)",
"bulkDeleteError": "Error al eliminar trabajos en masa: {error}",
"reviewNotReady": "El trabajo no está listo para revisión (estado actual: {status})",
"correctionsUnavailable": "Datos de correcciones no disponibles",
"correctionsUnavailable": "Datos de corrección no disponibles",
"audioUnavailable": "Audio no disponible para revisión",
"reviewCannotStart": "No se puede iniciar la revisión",
"jobNotInReviewState": "El trabajo no está en estado de revisión (estado actual: {status})",
"correctionsProcessing": "Correcciones guardadas. Llama a /complete-review cuando termines.",
"editLogSaveFailed": "Error al guardar el registro de edición para el trabajo {job_id}: {error}",
"stemsMissing": "Al trabajo le faltan pistas de audio requeridas (instrumental_clean y/o backing_vocals)",
"customInstrumentalFailed": "Error al crear instrumental personalizado para el trabajo {job_id}: {error}",
"customInstrumentalFailed": "Error al crear el instrumental personalizado para el trabajo {job_id}: {error}",
"audioProcessingFailed": "Error al procesar el archivo de audio: {error}",
"durationMismatch": "Diferencia de duración: el archivo subido dura {upload_duration}s pero el audio original dura {original_duration}s. El instrumental debe durar exactamente {original_duration}s (±0.5s).",
"durationMismatch": "Discrepancia de duración: el archivo subido dura {upload_duration}s pero el audio original dura {original_duration}s. El instrumental debe durar exactamente {original_duration}s (±0.5s).",
"reviewNotInState": "El trabajo no está en estado de revisión (estado actual: {status})",
"noLyricsDetected": "No se puede completar la revisión: no se detectaron letras en el audio. Esto puede suceder cuando el audio de entrada no tiene voces (por ejemplo, una pista de karaoke o instrumental). Puedes regresar y pegar las letras manualmente usando 'Reemplazar todo', o cancelar este trabajo e intentarlo de nuevo con un archivo de audio que contenga voces.",
"reviewCompleteStartRendering": "Revisión completa. El renderizado de video ha comenzado.",
"noLyricsDetected": "No se puede completar la revisión: no se detectaron letras en el audio. Esto puede suceder cuando el audio de entrada no tiene voces (ej. una pista de karaoke o instrumental). Puedes volver y pegar las letras manualmente usando 'Reemplazar todo', o cancelar este trabajo e intentar de nuevo con un archivo de audio que contenga voces.",
"reviewCompleteStartRendering": "Revisión completada. Se ha iniciado el renderizado de video.",
"reviewCompleteError": "Error al completar la revisión para el trabajo {job_id}: {error}",
"instrumentalSelectionRequired": "Se requiere instrumental_selection. Debe ser 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
"instrumentalSelected": "Instrumental seleccionado. La generación de video ha comenzado.",
"instrumentalSelectionError": "Error al seleccionar instrumental para el trabajo {job_id}: {error}",
"instrumentalSelected": "Instrumental seleccionado. Se ha iniciado la generación de video.",
"instrumentalSelectionError": "Error al seleccionar el instrumental para el trabajo {job_id}: {error}",
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}"
},
"review": {
"jobNotFound": "Trabajo no encontrado",
"reviewNotReady": "El trabajo no está listo para revisión (estado actual: {status})",
"correctionsNotFound": "Datos de correcciones no encontrados. El procesamiento de letras puede no estar completo.",
"correctionsNotFound": "Datos de corrección no encontrados. El procesamiento de letras puede no estar completo.",
"correctionsLoadFailed": "Error al cargar las correcciones: {error}",
"audioNotFound": "Archivo de audio no encontrado",
"audioServeError": "Error al cargar el audio: {error}",
"audioServeError": "Error al servir el audio: {error}",
"instrumentalSelectionRequired": "Se requiere instrumental_selection. Debe ser 'clean' o 'with_backing'.",
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
"reviewCompletedError": "Error al completar la revisión: {error}",
@@ -63,7 +63,7 @@
"lyricsAddError": "Error al agregar letras: {error}",
"lyricsAddInvalidRequest": "Solicitud para agregar letras inválida: {error}",
"lyricsSearchError": "Error al buscar letras: {error}",
"lyricsSearchInvalidRequest": "Solicitud para buscar letras inválida: {error}",
"lyricsSearchInvalidRequest": "Solicitud de búsqueda de letras inválida: {error}",
"lyricsSearchNoResults": "No se encontraron letras coincidentes en ningún proveedor",
"previewVideoGenerationError": "Error al generar el video de vista previa: {error}",
"previewVideoNotFound": "Video de vista previa no encontrado",
@@ -76,42 +76,42 @@
"audioSearch": {
"notEnabled": "La búsqueda de audio no está habilitada para este inquilino",
"disabled": "La búsqueda de audio no está disponible",
"downloadError": "La descarga falló para el trabajo {job_id}: {error}",
"downloadError": "Error de descarga para el trabajo {job_id}: {error}",
"jobNotFound": "Trabajo {job_id} no encontrado",
"noSearchResults": "No hay resultados de búsqueda disponibles",
"invalidSelectionIndex": "Índice de selección inválido {selection_index}. Rango válido: 0-{max}",
"selectionError": "Error durante la selección de audio para el trabajo {job_id}: {error}",
"youtubeDownloadError": "La descarga de YouTube falló: {error}",
"youtubeDownloadError": "Error en la descarga de YouTube: {error}",
"torrentDownloadError": "No se puede descargar de {source} sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No hay source_id o remote_search_id disponible para la descarga de {source}",
"remoteDownloadCompleteNoPath": "Descarga remota completada pero no se devolvió la ruta del archivo",
"spotifyDownloadError": "No se puede descargar de Spotify sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
"genericDownloadError": "Tipo de fuente desconocido: {source}, intentando descarga genérica",
"jobNotFoundDuringDownload": "Trabajo {job_id} no encontrado durante la descarga en segundo plano",
"selectAudioError": "Error al seleccionar audio para el trabajo {job_id}: {error}",
"selectAudioError": "Error al seleccionar el audio para el trabajo {job_id}: {error}",
"searchAudioError": "Error al buscar audio: {error}",
"searchCreatedSuccessfully": "Trabajo creado. Buscando audio...",
"autoDownloadStarted": "Mejor resultado seleccionado automáticamente. Iniciando descarga..."
},
"users": {
"disposableEmailBlocked": "disposable_email_not_allowed",
"magicLinkSent": "Si este correo electrónico está registrado, recibirás un enlace de inicio de sesión en breve.",
"magicLinkSent": "Si este correo está registrado, recibirás un enlace de inicio de sesión en breve.",
"emailServiceNotConfigured": "El servicio de correo electrónico no está disponible. Por favor, contacta a soporte.",
"emailDomainNotAllowed": "Dominio de correo electrónico no permitido para este inquilino",
"emailDomainNotAllowed": "Dominio de correo no permitido para este inquilino",
"invalidToken": "Token inválido",
"verifyError": "La verificación falló: {message}",
"magicLinkSuccess": "Has iniciado sesión con éxito",
"logoutSuccess": "Has cerrado sesión con éxito",
"verifyError": "Verificación fallida: {message}",
"magicLinkSuccess": "Sesión iniciada con éxito",
"logoutSuccess": "Sesión cerrada con éxito",
"userNotFound": "Usuario no encontrado",
"creditPackagesError": "Error al cargar los paquetes de créditos: {error}",
"stripeSendError": "Error al enviar el enlace de pago de Stripe: {error}",
"stripeWebhookProcessingError": "Error al procesar el webhook de Stripe: {error}",
"feedbackSaveError": "Error al guardar los comentarios: {error}",
"feedbackNotEligible": "El usuario no es elegible para dejar comentarios"
"feedbackNotEligible": "Usuario no elegible para dar comentarios"
},
"fileUpload": {
"invalidTheme": "Tema no encontrado: {theme_id}. Usa GET /api/themes para listar los temas disponibles.",
"uploadSuccess": "Archivo subido con éxito. El procesamiento ha comenzado.",
"uploadSuccess": "Archivo subido con éxito. Se ha iniciado el procesamiento.",
"uploadError": "Error al subir el archivo: {error}",
"urlDownloadError": "Error al descargar desde la URL: {error}",
"invalidContentType": "Tipo de contenido inválido: {content_type}",
@@ -121,17 +121,17 @@
"noAudioFileProvided": "No se proporcionó ningún archivo de audio",
"urlCreationSuccess": "Trabajo creado. URLs de subida generadas.",
"urlCreationError": "Error al crear el trabajo con URLs de subida: {error}",
"uploadsCompleteSuccess": "Subidas completadas. El procesamiento ha comenzado.",
"uploadsCompleteSuccess": "Subidas completadas. Se ha iniciado el procesamiento.",
"uploadsCompleteError": "Error al completar las subidas: {error}",
"noUploadedFiles": "No se especificaron archivos subidos",
"styleUploadUrlsSuccess": "URLs de subida de estilo generadas.",
"styleUploadsCompleteSuccess": "Archivos de estilo actualizados. El procesamiento se ha reiniciado.",
"styleUploadsCompleteSuccess": "Archivos de estilo actualizados. Se ha reiniciado el procesamiento.",
"styleUploadsCompleteError": "Error al completar las subidas de estilo: {error}"
},
"catalog": {
"rateLimitExceeded": "Límite de solicitudes excedido. Máximo {max_requests} solicitudes de catálogo por minuto.",
"rateLimitExceeded": "Límite de tasa excedido. Máximo {max_requests} solicitudes de catálogo por minuto.",
"catalogSearchError": "Error al buscar en el catálogo: {error}",
"communityCheckError": "Error al comprobar versiones de la comunidad: {error}"
"communityCheckError": "Error al comprobar las versiones de la comunidad: {error}"
},
"themes": {
"themesLoadError": "Error al cargar los temas",
@@ -147,7 +147,7 @@
},
"push": {
"disabled": "Las notificaciones push no están habilitadas",
"userEmailNotAvailable": "El correo electrónico del usuario no está disponible",
"userEmailNotAvailable": "Correo del usuario no disponible",
"missingEncryptionKeys": "Faltan claves requeridas (p256dh, auth)",
"subscriptionSaveFailed": "Error al guardar la suscripción",
"subscriptionRegistered": "Suscripción push registrada con éxito",
@@ -171,22 +171,22 @@
"domainAddedToAllowlist": "Dominio '{domain}' agregado a la lista de permitidos",
"domainNotFoundInAllowlist": "Dominio no encontrado en la lista de permitidos",
"domainRemovedFromAllowlist": "Dominio '{domain}' eliminado de la lista de permitidos",
"syncComplete": "Se sincronizaron {external_count} dominios externos ({added} agregados, {removed} eliminados)",
"invalidEmailFormat": "Formato de correo electrónico inválido",
"emailAddedToBl": "Correo electrónico '{email}' agregado a la lista de correos bloqueados",
"emailNotFoundInBl": "Correo electrónico no encontrado en la lista de bloqueo",
"emailRemovedFromBl": "Correo electrónico '{email}' eliminado de la lista de correos bloqueados",
"syncComplete": "Sincronizados {external_count} dominios externos ({added} agregados, {removed} eliminados)",
"invalidEmailFormat": "Formato de correo inválido",
"emailAddedToBl": "Correo '{email}' agregado a la lista de correos bloqueados",
"emailNotFoundInBl": "Correo no encontrado en la lista de bloqueo",
"emailRemovedFromBl": "Correo '{email}' eliminado de la lista de correos bloqueados",
"invalidIPAddress": "Dirección IP inválida",
"ipAddedToBl": "IP '{ip_address}' agregada a la lista de IPs bloqueadas",
"ipNotFoundInBl": "IP no encontrada en la lista de bloqueo",
"ipRemovedFromBl": "IP '{ip_address}' eliminada de la lista de IPs bloqueadas",
"youtubeUploadNotFound": "Subida no encontrada o no en estado de reintento para el trabajo {job_id}",
"youtubeUploadNotFound": "Subida no encontrada o no en estado reintentable para el trabajo {job_id}",
"youtubeUploadQueuedForRetry": "Subida a YouTube para el trabajo {job_id} en cola para reintento",
"youtubeQueueProcessingStarted": "Procesamiento de la cola de YouTube iniciado en segundo plano"
},
"rateLimits": {
"configNotFound": "Configuración de límite de solicitudes no encontrada: {config_id}",
"configUpdateError": "Error al actualizar la configuración de límite de solicitudes: {error}"
"configNotFound": "Configuración de límite de tasa no encontrada: {config_id}",
"configUpdateError": "Error al actualizar la configuración de límite de tasa: {error}"
},
"errors": {
"insufficientCredits": "Créditos insuficientes para esta operación",
@@ -194,13 +194,44 @@
},
"emails": {
"magicLink": {
"subject": "Inicia sesión en {brand_name}"
"subject": "Inicia sesión en {brand_name}",
"greeting": "Hola,",
"signInPrompt": "Haz clic en el botón de abajo para iniciar sesión en {brand_name}:",
"signInButton": "Iniciar sesión",
"expiryWarning": "Este enlace expira en 15 minutos y solo puede usarse una vez.",
"fallbackLink": "Si el botón no funciona, copia y pega este enlace en tu navegador:",
"ignoreNote": "Si no solicitaste este correo, puedes ignorarlo de forma segura."
},
"welcome": {
"subject": "¡Bienvenido a Nomad Karaoke!"
"subject": "¡Bienvenido a Nomad Karaoke!",
"welcomeGreeting": "¡Bienvenido a Nomad Karaoke!",
"turnAnySong": "Convierte cualquier canción en un video de karaoke profesional en minutos.",
"freeCreditsLabel": "Créditos gratis",
"freeCreditsNote": "Cada crédito crea un video de karaoke profesional",
"howItWorks": "Así es como funciona:",
"step1Title": "1. Busca una canción",
"step1Desc": "Ingresa el artista y el título, y encontraremos audio de alta calidad.",
"step2Title": "2. Nuestro sistema hace su magia",
"step2Desc": "Hacemos la separación vocal, transcribimos las letras y sincronizamos todo perfectamente.",
"step3Title": "3. Revisa y personaliza",
"step3Desc": "Ajusta las letras si es necesario, elige tu instrumental.",
"step4Title": "4. Obtén tu video",
"step4Desc": "Descarga tu video de karaoke en 4K o súbelo directamente a YouTube.",
"feedbackBonus": "¡Completa 2 videos y gana 2 créditos gratis más compartiendo tus comentarios!",
"getStartedButton": "Comenzar"
},
"creditsAdded": {
"subject": "{credits} créditos agregados a tu cuenta de Nomad Karaoke"
"subject": "{credits} créditos agregados a tu cuenta de Nomad Karaoke",
"greatNews": "¡Excelentes noticias!",
"creditsAddedMessage": "Se han agregado {credits} créditos a tu cuenta.",
"yourBalance": "Tu saldo:",
"credits": "créditos",
"eachCreditLets": "Cada crédito te permite crear un video de karaoke profesional con:",
"featureVocalSeparation": "Separación vocal/instrumental impulsada por IA",
"featureLyrics": "Letras sincronizadas con tiempo a nivel de palabra",
"feature4k": "Salida de video en 4K",
"featureYoutube": "Subida a YouTube",
"createButton": "Crear karaoke ahora"
},
"jobCompletion": {
"subjectWithBrand": "{brand_code}: {artist} - {title} (¡Tu video de karaoke está listo!)",
@@ -213,26 +244,95 @@
"subjectFallback": "¡Tu subida a YouTube está lista!"
},
"actionReminder": {
"lyricsSubject": "Acción necesaria: Revisar letras para {artist} - {title}",
"lyricsSubjectFallback": "Acción necesaria: Revisar letras",
"instrumentalSubject": "Acción necesaria: Seleccionar instrumental para {artist} - {title}",
"instrumentalSubjectFallback": "Acción necesaria: Seleccionar instrumental",
"audioEditSubject": "Acción necesaria para {artist} - {title}",
"audioEditSubjectFallback": "Acción necesaria"
"lyricsSubject": "Acción requerida: Revisión de letras para {artist} - {title}",
"lyricsSubjectFallback": "Acción requerida: Revisión de letras",
"instrumentalSubject": "Acción requerida: Seleccionar instrumental para {artist} - {title}",
"instrumentalSubjectFallback": "Acción requerida: Seleccionar instrumental",
"audioEditSubject": "Acción requerida para {artist} - {title}",
"audioEditSubjectFallback": "Acción requerida",
"alertHeading": "¡Tu video de karaoke necesita tu atención!"
},
"reviewReminder": {
"subject": "Recordatorio: Tu video de karaoke está esperando revisión — {artist} - {title}",
"subjectFallback": "Recordatorio: Tu video de karaoke está esperando revisión"
"subjectFallback": "Recordatorio: Tu video de karaoke está esperando revisión",
"alertHeading": "¡Tu video de karaoke te está esperando!",
"reminderIntro": "Solo un recordatorio amistoso de que tu video de karaoke{song_name} está listo para revisión.",
"reviewButton": "Revisar tu video",
"reviewInstructions": "Durante la revisión, puedes comprobar que las letras son correctas y elegir tu pista instrumental preferida. ¡Normalmente solo toma unos minutos!",
"helpOffer": "Si tienes algún problema con el proceso de revisión, solo responde a este correo y estaré encantado de ayudarte.",
"expiryWarning": "Ten en cuenta: si la revisión no se completa dentro de las próximas 24 horas, el trabajo expirará automáticamente y se te reembolsará tu crédito."
},
"reviewExpired": {
"subject": "Tu video de karaoke ha expirado — {artist} - {title}",
"subjectFallback": "Tu video de karaoke ha expirado"
"subjectFallback": "Tu video de karaoke ha expirado",
"cancelNotice": "Tu video de karaoke{song_name} ha sido cancelado automáticamente porque la revisión no se completó en 48 horas.",
"refundNotice": "No te preocupes — ¡tu crédito ha sido reembolsado! Tu saldo actual es de {credits_balance} {credits_word}.",
"creditSingular": "crédito",
"creditPlural": "créditos",
"createNewPrompt": "Puedes crear un nuevo video de karaoke en cualquier momento usando tus créditos:",
"createButton": "Crear nuevo video",
"helpOffer": "Si tuviste algún problema con el proceso de revisión o necesitas ayuda, solo responde a este correo — ¡me encantaría ayudar!"
},
"creditDenied": {
"subject": "Sobre tus créditos gratis de Nomad Karaoke"
"subject": "Sobre tus créditos gratis de Nomad Karaoke",
"greeting": "Hola,",
"thankYou": "¡Gracias por registrarte en Nomad Karaoke!",
"deniedMessage": "Lamentablemente, no pudimos otorgar tus {credit_type} gratis esta vez. Nuestro sistema detectó patrones que sugieren que esta podría no ser tu primera cuenta con nosotros, y cada trabajo de generación de karaoke nos cuesta dinero real en computación en la nube y tarifas de API.",
"mistakeNote": "¡Entendemos totalmente si esto es un error! Si eres un usuario nuevo genuino, por favor solo responde a este correo y házselo saber a Andrew (el fundador). Él construyó este servicio y estará feliz de otorgarte algunos créditos gratis para que lo pruebes — solo te pide que a cambio proporciones comentarios honestos sobre la experiencia.",
"buyPrompt": "Si deseas comenzar de inmediato, también puedes comprar créditos:",
"buyButton": "Comprar créditos",
"costNote": "Mantenemos los costos bajos para poder ofrecer el servicio de manera asequible, lo que significa que debemos tener cuidado con el abuso de créditos gratis. ¡Gracias por entender!",
"welcomeCredits": "créditos de bienvenida",
"feedbackCredits": "créditos de bonificación por comentarios"
},
"madeForYouConfirmation": {
"subject": "Pedido confirmado: {artist} - {title} | Nomad Karaoke"
"subject": "Pedido confirmado: {artist} - {title} | Nomad Karaoke",
"thankYou": "¡Gracias por tu pedido!",
"orderDetails": "Detalles del pedido",
"orderId": "ID del pedido:",
"artist": "Artista:",
"title": "Título:",
"yourNotes": "Tus notas:",
"deliveryTime": "Nuestro equipo creará tu video de karaoke personalizado en {hours} horas.",
"deliveryNotice": "Recibirás un correo con enlaces de descarga tan pronto como tu video esté listo.",
"noAction": "No se necesita ninguna acción — ¡relájate y nos encargaremos de todo!"
},
"shared": {
"footerHelp": "Si algo no es perfecto, ¡solo responde a este correo y lo arreglaré!"
},
"templates": {
"jobCompletion": {
"greeting": "Hola {name},",
"thanks": "¡Gracias por tu pedido!",
"youtubeLink": "Aquí tienes el enlace del video de karaoke publicado en YouTube:",
"dropboxIntro": "Aquí tienes la carpeta de Dropbox con todos los archivos terminados y archivos fuente, incluyendo:",
"fileList": "- \"(Final Karaoke Lossless).mkv\": video de karaoke combinado en 4K H264 con audio FLAC sin pérdida\n- \"(Final Karaoke).mp4\": video de karaoke combinado con pantalla de título/pantalla final en 4K H264/AAC\n- \"(Final Karaoke 720p).mp4\": video de karaoke combinado en 720p H264/AAC (archivo más pequeño para sistemas más antiguos)\n- \"(With Vocals).mp4\": video para cantar junto en 4K H264/AAC con voces originales\n- \"(Karaoke).mov\": salida de video de karaoke de MidiCo (sin pantalla de título/pantalla final)\n- \"(Title).mov\"/\"(End).mov\": videos de tarjeta de título y pantalla final\n- \"(Final Karaoke CDG).zip\": formato CDG+MP3 para sistemas de karaoke más antiguos/comerciales\n- \"(Final Karaoke TXT).zip\": formato TXT+MP3 para Power Karaoke\n- stems/*.flac: varias pistas de audio instrumentales y vocales separadas en formato sin pérdida\n- lyrics/*.txt letras de canciones de varias fuentes en formato de texto sin formato",
"fixOffer": "Avísame si algo no es perfecto y con gusto lo ajustaré / arreglaré, o si lo necesitas en cualquier otro formato, ¡probablemente pueda convertirlo para ti!",
"feedbackRequest": "Si tienes un momento, realmente apreciaría tus comentarios (toma 2 minutos):",
"signOff": "¡Gracias de nuevo y que tengas un gran día!\n-Andrew",
"youtubeQueued": "Tu subida a YouTube está en cola y se procesará automáticamente. Recibirás un correo de seguimiento con el enlace en breve."
},
"actionLyrics": {
"greeting": "Hola {name},",
"ready": "¡Tu video de karaoke para \"{artist} - {title}\" está listo para revisión!",
"instructions": "Nuestro sistema ha transcrito y sincronizado las letras, pero pueden necesitar algunas correcciones. También podrás seleccionar tu pista instrumental preferida (con o sin coros).",
"reviewPrompt": "Por favor revisa tus letras y selecciona un instrumental:",
"duration": "Esto normalmente toma solo unos minutos.",
"signOff": "¡Gracias!\n-Andrew"
},
"actionInstrumental": {
"greeting": "Hola {name},",
"almostDone": "¡Tu video de karaoke para \"{artist} - {title}\" está casi listo!",
"instructions": "Hemos separado el audio en diferentes versiones. Por favor selecciona qué pista instrumental te gustaría usar para el video final.",
"selectPrompt": "Selecciona tu instrumental aquí:",
"signOff": "¡Gracias!\n-Andrew"
},
"youtubeComplete": {
"greeting": "Hola {name},",
"greatNews": "¡Excelentes noticias! Tu video de karaoke para \"{artist} - {title}\" ha sido subido a YouTube:",
"delayNote": "Esta subida se retrasó brevemente mientras nuestros sistemas procesaban otras subidas, pero todo está listo ahora.",
"signOff": "¡Gracias!\n-Andrew"
}
}
}
}
@@ -6,7 +6,7 @@ import { api, Job, createLyricsReviewApiClient, lyricsReviewApi } from "@/lib/ap
import { Spinner } from "@/components/ui/spinner"
import { Button } from "@/components/ui/button"
import { ArrowLeft, AlertCircle } from "lucide-react"
import Link from "next/link"
import { Link } from "@/i18n/routing"
import { LyricsAnalyzer } from "@/components/lyrics-review"
import { InstrumentalSelector } from "@/components/instrumental-review"
import { AudioEditor } from "@/components/audio-editor/AudioEditor"
+2 -1
View File
@@ -1,7 +1,8 @@
"use client"
import { useState, useEffect, useCallback, useMemo, Suspense, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useRouter } from "@/i18n/routing"
import { useSearchParams } from "next/navigation"
import { api, Job, getAccessToken } from "@/lib/api"
import { useAuth } from "@/lib/auth"
import { useAdminSettings } from "@/lib/admin-settings"
+2 -1
View File
@@ -1,7 +1,8 @@
"use client"
import { Suspense, useEffect, useState, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useRouter } from "@/i18n/routing"
import { useSearchParams } from "next/navigation"
import { Loader2, CheckCircle, XCircle, Gift, ShoppingCart } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useAuth } from "@/lib/auth"
+1 -1
View File
@@ -1,7 +1,7 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useRouter } from '@/i18n/routing';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import {
@@ -1,7 +1,8 @@
"use client"
import { Suspense, useEffect, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useRouter } from "@/i18n/routing"
import { useSearchParams } from "next/navigation"
import { CheckCircle, Loader2, Coins } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useAuth } from "@/lib/auth"
@@ -1,446 +0,0 @@
"use client"
import { useEffect, useState, useCallback } from "react"
import { useAuth } from "@/lib/auth"
import { api, Job, createLyricsReviewApiClient, lyricsReviewApi } from "@/lib/api"
import { Spinner } from "@/components/ui/spinner"
import { Button } from "@/components/ui/button"
import { ArrowLeft, AlertCircle } from "lucide-react"
import Link from "next/link"
import { LyricsAnalyzer } from "@/components/lyrics-review"
import { InstrumentalSelector } from "@/components/instrumental-review"
import { AudioEditor } from "@/components/audio-editor/AudioEditor"
import { ThemeToggle } from "@/components/ThemeToggle"
import type { CorrectionData } from "@/lib/lyrics-review/types"
import { isLocalMode, createLocalModeJob } from "@/lib/local-mode"
type RouteType = "review" | "instrumental" | "audio-edit" | "unknown"
type AccessState =
| { status: "loading" }
| { status: "not_authenticated" }
| { status: "not_authorized"; reason: string }
| { status: "job_not_found" }
| { status: "wrong_state"; currentState: string; expectedStates: string[] }
| { status: "invalid_route" }
| { status: "authorized"; job: Job; routeType: RouteType }
| { status: "local_mode"; job: Job; routeType: RouteType }
// Parse route from window.location.pathname (used for local mode with path-based routing)
// For static exports, useParams() returns empty - we must parse the URL directly
function parseRouteFromPathname(pathname: string): { jobId: string | null; routeType: RouteType } {
if (!pathname) {
return { jobId: null, routeType: "unknown" }
}
// Expected format: /app/jobs/{jobId}/{action}
// e.g., /app/jobs/local/review or /app/jobs/local/instrumental
const match = pathname.match(/^\/app\/jobs\/([^/]+)\/(review|instrumental|audio-edit)\/?$/)
if (match) {
const [, jobId, action] = match
return { jobId, routeType: action as RouteType }
}
return { jobId: null, routeType: "unknown" }
}
// Parse route from URL hash (used for cloud mode)
// Expected format: #/{jobId}/review or #/{jobId}/instrumental
function parseRouteFromHash(hash: string): { jobId: string | null; routeType: RouteType } {
if (!hash || hash.length <= 1) {
return { jobId: null, routeType: "unknown" }
}
// Remove the leading '#' and parse
const hashPath = hash.substring(1)
// Support BOTH review and instrumental routes
const match = hashPath.match(/^\/?([^/]+)\/(review|instrumental|audio-edit)\/?$/)
if (match) {
const [, jobId, action] = match
return { jobId, routeType: action as RouteType }
}
return { jobId: null, routeType: "unknown" }
}
function getExpectedStates(routeType: RouteType): string[] {
switch (routeType) {
case "review":
return ["awaiting_review", "in_review"]
case "instrumental":
return ["awaiting_review", "in_review"] // Same states for now
case "audio-edit":
return ["awaiting_audio_edit", "in_audio_edit"]
default:
return []
}
}
export function JobRouterClient() {
// For static exports, useParams() returns empty object
// We need to parse the URL path directly instead
const [pathname, setPathname] = useState(() =>
typeof window !== 'undefined' ? window.location.pathname : ''
)
// Track hash for re-renders when hash changes (cloud mode)
const [hash, setHash] = useState(() =>
typeof window !== 'undefined' ? window.location.hash : ''
)
// Listen for hash changes
useEffect(() => {
const handleHashChange = () => {
setHash(window.location.hash)
}
window.addEventListener('hashchange', handleHashChange)
return () => window.removeEventListener('hashchange', handleHashChange)
}, [])
// Update pathname on mount (needed for SSR hydration)
useEffect(() => {
setPathname(window.location.pathname)
}, [])
// Determine routing mode and parse route
// - Local mode: Use path-based routing parsed from window.location.pathname
// - Cloud mode: Use hash-based routing (e.g., /app/jobs/#/{jobId}/review)
const inLocalMode = isLocalMode()
const { jobId, routeType } = inLocalMode
? parseRouteFromPathname(pathname)
: parseRouteFromHash(hash)
const { user, isLoading: authLoading, hasHydrated } = useAuth()
const [accessState, setAccessState] = useState<AccessState>({ status: "loading" })
useEffect(() => {
async function checkAccess() {
// Handle local mode (skip all auth checks)
if (inLocalMode) {
// In local mode, always use review (combined lyrics + instrumental)
const localRouteType: RouteType = routeType === "unknown" ? "review" : routeType
// Create mock job for local mode
const localJob = createLocalModeJob({ routeType: localRouteType }) as Job
setAccessState({ status: "local_mode", job: localJob, routeType: localRouteType })
return
}
// Cloud mode: Check hash-based route
if (!jobId || routeType === "unknown") {
setAccessState({ status: "invalid_route" })
return
}
// Wait for auth to finish loading and hydration to complete
// This prevents a flash of "Sign in required" before auth state is restored from localStorage
if (authLoading || !hasHydrated) return
// Must be authenticated
if (!user) {
setAccessState({ status: "not_authenticated" })
return
}
try {
// Fetch job details
const job = await api.getJob(jobId)
// Check ownership: user must own the job or be admin
const isOwner = job.user_email === user.email
const isAdmin = user.role === "admin"
if (!isOwner && !isAdmin) {
setAccessState({
status: "not_authorized",
reason: "You don't have permission to access this job"
})
return
}
// Check job is in correct state
const expectedStates = getExpectedStates(routeType)
if (!expectedStates.includes(job.status)) {
setAccessState({
status: "wrong_state",
currentState: job.status,
expectedStates
})
return
}
// All checks passed
setAccessState({ status: "authorized", job, routeType })
} catch (error: unknown) {
// Job not found or API error
if (error && typeof error === "object" && "status" in error && error.status === 404) {
setAccessState({ status: "job_not_found" })
} else {
setAccessState({
status: "not_authorized",
reason: "Failed to load job details"
})
}
}
}
checkAccess()
}, [inLocalMode, jobId, routeType, user, authLoading, hasHydrated])
// Loading state
if (accessState.status === "loading") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<Spinner className="w-8 h-8 mx-auto mb-4" />
<p className="text-muted-foreground">Loading...</p>
</div>
</div>
)
}
// Invalid route
if (accessState.status === "invalid_route") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
<h1 className="text-xl font-semibold mb-2">Page not found</h1>
<p className="text-muted-foreground mb-4">
The page you&apos;re looking for doesn&apos;t exist.
</p>
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
</div>
</div>
)
}
// Not authenticated
if (accessState.status === "not_authenticated") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-amber-500" />
<h1 className="text-xl font-semibold mb-2">Sign in required</h1>
<p className="text-muted-foreground mb-4">
You need to sign in to access this page.
</p>
<Button asChild>
<Link href="/app">Sign in</Link>
</Button>
</div>
</div>
)
}
// Not authorized
if (accessState.status === "not_authorized") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
<h1 className="text-xl font-semibold mb-2">Access denied</h1>
<p className="text-muted-foreground mb-4">{accessState.reason}</p>
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
</div>
</div>
)
}
// Job not found
if (accessState.status === "job_not_found") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
<h1 className="text-xl font-semibold mb-2">Job not found</h1>
<p className="text-muted-foreground mb-4">
The job you&apos;re looking for doesn&apos;t exist or has been deleted.
</p>
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
</div>
</div>
)
}
// Wrong state
if (accessState.status === "wrong_state") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-amber-500" />
<h1 className="text-xl font-semibold mb-2">Not available</h1>
<p className="text-muted-foreground mb-4">
This job is currently in &quot;{accessState.currentState}&quot; state and is not ready for review.
</p>
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
</div>
</div>
)
}
// Authorized or local mode - render the appropriate UI
const { job } = accessState
// Get route type from access state (which validated and stored it during checkAccess)
const currentRouteType = accessState.status === "authorized" || accessState.status === "local_mode"
? accessState.routeType
: "review" // Fallback (shouldn't happen since we return early for other statuses)
if (currentRouteType === "audio-edit") {
return <AudioEditor job={job} />
}
if (currentRouteType === "instrumental") {
return <InstrumentalReviewWrapper job={job} isLocalMode={inLocalMode} />
}
return <LyricsReviewWrapper job={job} isLocalMode={inLocalMode} />
}
// Lyrics Review Component Wrapper
function LyricsReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMode?: boolean }) {
const [correctionData, setCorrectionData] = useState<CorrectionData | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
// Create the API client for this job
const apiClient = createLyricsReviewApiClient(job.job_id)
// Load correction data
useEffect(() => {
async function loadData() {
try {
setIsLoading(true)
setError(null)
const data = await lyricsReviewApi.getCorrectionData(job.job_id)
setCorrectionData(data)
} catch (err) {
console.error("Failed to load correction data:", err)
setError(err instanceof Error ? err.message : "Failed to load lyrics data")
} finally {
setIsLoading(false)
}
}
loadData()
}, [job.job_id])
// File load handler (opens file picker for local file)
const handleFileLoad = useCallback(() => {
// For now, this is a no-op since we load from API
// Could be extended to allow loading from local files
console.log("File load requested")
}, [])
// Metadata handler
const handleShowMetadata = useCallback(() => {
// Could show a modal with job metadata
console.log("Show metadata requested", job)
}, [job])
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<Spinner className="w-8 h-8 mx-auto mb-4" />
<p className="text-muted-foreground">Loading lyrics data...</p>
</div>
</div>
)
}
if (error || !correctionData) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center max-w-md p-6">
<AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
<h1 className="text-xl font-semibold mb-2">Failed to load lyrics</h1>
<p className="text-muted-foreground mb-4">
{error || "Could not load lyrics data for this job."}
</p>
{!isLocalMode && (
<Button variant="outline" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to dashboard
</Link>
</Button>
)}
</div>
</div>
)
}
return (
<div className="min-h-screen bg-background">
{/* App Header - matches old frontend's AppHeader */}
<header className="border-b bg-card/80 backdrop-blur-sm sticky top-0 z-50 px-4 py-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{!isLocalMode && (
<Button variant="ghost" size="sm" asChild>
<Link href="/app">
<ArrowLeft className="w-4 h-4 mr-2" />
Back
</Link>
</Button>
)}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/nomad-karaoke-logo.svg"
alt="Nomad Karaoke"
style={{ height: 40 }}
/>
<h1 className="text-lg font-bold">Lyrics Transcription Review</h1>
</div>
<ThemeToggle />
</div>
</header>
<main className="px-4 py-2">
<LyricsAnalyzer
data={correctionData}
onFileLoad={handleFileLoad}
onShowMetadata={handleShowMetadata}
apiClient={apiClient}
isReadOnly={false}
audioHash={correctionData.metadata?.audio_hash || job.audio_hash || job.job_id}
isLocalMode={isLocalMode}
jobId={job.job_id}
hasExistingInstrumental={!!job.existing_instrumental_gcs_path}
/>
</main>
</div>
)
}
// Instrumental Review Component Wrapper
// The InstrumentalSelector component handles its own data fetching and submission
// It uses the appropriate API based on isLocalMode
function InstrumentalReviewWrapper({ job, isLocalMode = false }: { job: Job; isLocalMode?: boolean }) {
return (
<InstrumentalSelector job={job} isLocalMode={isLocalMode} />
)
}
+7 -9
View File
@@ -1,16 +1,14 @@
import { JobRouterClient } from "./client"
import { LocaleRedirect } from "@/components/LocaleRedirect"
// Required for static export with catch-all routes
// Returns params array for paths to pre-render at build time
// Preserve static params for local mode CLI paths
export async function generateStaticParams(): Promise<{ slug?: string[] }[]> {
return [
{ slug: undefined }, // /app/jobs/
// Local mode paths - pre-rendered for karaoke-gen CLI local review
{ slug: ['local', 'review'] }, // /app/jobs/local/review
{ slug: ['local', 'instrumental'] }, // /app/jobs/local/instrumental
{ slug: undefined },
{ slug: ['local', 'review'] },
{ slug: ['local', 'instrumental'] },
]
}
export default function JobsPage() {
return <JobRouterClient />
export default function JobsRedirect() {
return <LocaleRedirect />
}
+3 -507
View File
@@ -1,509 +1,5 @@
"use client"
import { LocaleRedirect } from "@/components/LocaleRedirect"
import { useState, useEffect, useCallback, useMemo, Suspense, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { api, Job, getAccessToken } from "@/lib/api"
import { useAuth } from "@/lib/auth"
import { useAdminSettings } from "@/lib/admin-settings"
import { useJobNotifications, useVisibilityRefresh } from "@/hooks/use-notifications"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Music2, RefreshCw, Loader2, Moon, Sun, Search, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone } from "lucide-react"
import { sortJobsByDate } 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,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
function AppPageContent() {
const router = useRouter()
const searchParams = useSearchParams()
const [allJobs, setAllJobs] = useState<Job[]>([])
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
const [isInitialLoad, setIsInitialLoad] = useState(true)
const [hasFetchedSuccessfully, setHasFetchedSuccessfully] = useState(false)
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
const [isVerifyingToken, setIsVerifyingToken] = useState(false)
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
const saved = localStorage.getItem("nomad-karaoke-job-limit")
return saved ? Number(saved) : 10
})
const [statusFilter, setStatusFilter] = useState<string>(() => {
if (typeof window === "undefined") return "all"
return localStorage.getItem("nomad-karaoke-status-filter") || "all"
})
const [searchInput, setSearchInput] = useState("")
const [searchQuery, setSearchQuery] = useState("")
const [showAdminControls, setShowAdminControls] = useState<boolean>(() => {
if (typeof window === "undefined") return false
return localStorage.getItem("nomad-karaoke-admin-controls") === "true"
})
const [feedbackBannerDismissed, setFeedbackBannerDismissed] = useState(() => {
if (typeof window === "undefined") return false
return localStorage.getItem("nomad-feedback-banner-dismissed") === "true"
})
const [showFeedbackDialog, setShowFeedbackDialog] = useState(false)
// Check if user is admin (for exclude_test parameter)
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
// Filter out in-progress search jobs (managed by the guided flow, not standalone cards)
const jobs = useMemo(
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
[allJobs]
)
// Debounce search input — only update the query (which triggers API calls) after 300ms
useEffect(() => {
const timer = setTimeout(() => setSearchQuery(searchInput), 300)
return () => clearTimeout(timer)
}, [searchInput])
// Memoize loadJobs for use with visibility refresh
const loadJobs = useCallback(async () => {
if (!getAccessToken()) {
setIsLoadingJobs(false)
setIsInitialLoad(false)
return
}
try {
const data = await api.listJobs({
limit: jobLimit,
exclude_test: isAdmin ? !showTestData : undefined,
fields: 'summary',
status: statusFilter !== 'all' && statusFilter !== 'active' ? statusFilter : undefined,
hide_completed: statusFilter === 'active' ? true : undefined,
search: searchQuery || undefined,
})
setAllJobs(sortJobsByDate(data))
} catch (err: any) {
if (err?.status !== 401) {
console.error("Failed to load jobs:", err)
}
} finally {
setIsLoadingJobs(false)
setIsInitialLoad(false)
setHasFetchedSuccessfully(true)
}
}, [isAdmin, showTestData, jobLimit, statusFilter, searchQuery])
// Enable notifications for job status changes (sound + title animation)
useJobNotifications(allJobs)
// Refresh jobs immediately when tab becomes visible (after returning from review UIs)
useVisibilityRefresh(loadJobs, isAuthenticated === true)
// Handle admin_token URL parameter for one-click login from email
useEffect(() => {
const adminToken = searchParams.get("admin_token")
// Only process admin_token once (use ref to prevent repeated calls)
if (adminToken && !adminTokenHandled.current) {
adminTokenHandled.current = true
setIsVerifyingToken(true)
verifyMagicLink(adminToken).then((success) => {
// Clean URL by removing the token
window.history.replaceState({}, '', '/app')
setIsVerifyingToken(false)
if (success) {
setIsAuthenticated(true)
} else {
router.replace('/')
}
})
return
}
// Normal auth check (skip if admin_token is being processed)
if (adminToken || isVerifyingToken) return
const token = getAccessToken()
if (!token) {
// Redirect to landing page if not authenticated
router.replace('/')
return
}
setIsAuthenticated(true)
}, [router, searchParams, verifyMagicLink, isVerifyingToken])
// Ensure user data is loaded after authentication
// This handles the case where user navigates via client-side navigation
// (e.g., after beta enrollment) and the module-level fetchUser() didn't run
useEffect(() => {
const token = getAccessToken()
if (token && !user) {
fetchUser()
}
}, [user, fetchUser])
// Load jobs on mount (only if authenticated)
useEffect(() => {
if (isAuthenticated !== true) {
setIsLoadingJobs(false)
return
}
loadJobs()
// Poll for updates every 10 seconds
const interval = setInterval(loadJobs, 10000)
return () => clearInterval(interval)
}, [isAuthenticated, loadJobs])
// Show nothing while checking auth or verifying admin token (prevents flash)
if (isAuthenticated === null || isVerifyingToken) {
return (
<div className="min-h-screen flex items-center justify-center animated-gradient">
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--text-muted)' }} />
</div>
)
}
// Show warming up loader during initial job load (cold start scenario)
if (isInitialLoad && isLoadingJobs) {
return (
<div className="min-h-screen flex items-center justify-center animated-gradient">
<WarmingUpLoader spinnerClassName="w-10 h-10" />
</div>
)
}
return (
<div className="min-h-screen animated-gradient">
{/* AutoProcessor - handles non-interactive mode for jobs with that flag */}
<AutoProcessor jobs={allJobs} onJobsChanged={loadJobs} />
{/* Header */}
<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">
{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)' }}>
{isDefaultTenant ? "Karaoke Generator" : branding.site_title}
</h1>
</div>
</div>
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
<Button
variant="ghost"
size="sm"
onClick={loadJobs}
disabled={isLoadingJobs || !isAuthenticated}
className="min-h-[40px] px-2 sm:px-3"
style={{ color: 'var(--text-muted)' }}
>
<RefreshCw className={`w-4 h-4 sm:mr-2 ${isLoadingJobs ? 'animate-spin' : ''}`} />
<span className="hidden sm:inline">Refresh</span>
</Button>
{isAdmin && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
onClick={() => {
const next = !showAdminControls
setShowAdminControls(next)
localStorage.setItem("nomad-karaoke-admin-controls", String(next))
}}
className={`min-h-[40px] px-2 sm:px-3 ${showAdminControls ? 'text-amber-400' : ''}`}
style={showAdminControls ? undefined : { color: 'var(--text-muted)' }}
>
{showAdminControls ? <Shield className="w-4 h-4" /> : <ShieldOff className="w-4 h-4" />}
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">
<p>{showAdminControls ? "Hide admin controls" : "Show admin controls"}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="min-h-[40px] px-2 sm:px-3"
style={{ color: 'var(--text-muted)' }}
>
<HelpCircle className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<DropdownMenuLabel className="text-sm font-normal">
Something confusing or not working? Reach out anytime!
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<a href="mailto:andrew@nomadkaraoke.com">
<Mail className="w-4 h-4 mr-2" />
andrew@nomadkaraoke.com
</a>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<a href="tel:+18036363267">
<Phone className="w-4 h-4 mr-2" />
+1 (803) 636-3267
</a>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<AuthStatus />
{mounted && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
onClick={toggleTheme}
className="min-h-[40px] px-2 sm:px-3"
style={{ color: 'var(--text-muted)' }}
>
{isDarkMode ? (
<Sun className="w-4 h-4" />
) : (
<Moon className="w-4 h-4" />
)}
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">
<p>{isDarkMode ? "Switch to light mode" : "Switch to dark mode"}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
</div>
</header>
{/* Feedback dialog */}
<FeedbackDialog
open={showFeedbackDialog}
onClose={() => setShowFeedbackDialog(false)}
/>
<main className="px-4 pt-24 pb-8 space-y-6">
{/* Push notification prompt - shows once when appropriate */}
<PushNotificationPrompt />
{/* 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)',
backgroundColor: 'rgba(34, 197, 94, 0.05)',
}}
>
<div className="flex items-center gap-3 min-w-0">
<Gift className="w-5 h-5 text-green-500 shrink-0" />
<p className="text-sm" style={{ color: 'var(--text)' }}>
<strong>Earn 1 free credit!</strong>{' '}
<span style={{ color: 'var(--text-muted)' }}>
Share your feedback on the karaoke creation experience.
</span>
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<Button
size="sm"
variant="outline"
onClick={() => setShowFeedbackDialog(true)}
className="text-green-500 border-green-500/30 hover:bg-green-500/10"
>
Give Feedback
</Button>
<button
onClick={() => {
localStorage.setItem("nomad-feedback-banner-dismissed", "true")
setFeedbackBannerDismissed(true)
}}
className="p-1 rounded hover:bg-secondary transition-colors"
style={{ color: 'var(--text-muted)' }}
>
<X className="w-4 h-4" />
</button>
</div>
</div>
)}
<div className="grid lg:grid-cols-2 gap-8">
{/* Submit Job Card */}
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--text)' }}>
{isDefaultTenant ? "Create Karaoke Video" : "Submit Track"}
</CardTitle>
<CardDescription style={{ color: 'var(--text-muted)' }}>
{isDefaultTenant
? "Turn any song into a karaoke video with synced lyrics"
: "Upload your mixed audio and instrumental"}
</CardDescription>
</CardHeader>
<CardContent>
{isDefaultTenant ? (
<GuidedJobFlow onJobCreated={loadJobs} />
) : (
<TenantJobFlow onJobCreated={loadJobs} />
)}
</CardContent>
</Card>
{/* Jobs List Card */}
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
<CardHeader className="px-3 sm:px-6">
<div className="flex items-center justify-between gap-2 flex-wrap">
<div className="flex items-center gap-2">
<CardTitle style={{ color: 'var(--text)' }}>Recent Jobs</CardTitle>
{isLoadingJobs && <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--text-muted)' }} />}
</div>
<div className="flex items-center gap-2 flex-wrap">
<div className="relative">
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5" style={{ color: 'var(--text-muted)' }} />
<input
type="text"
placeholder="Search..."
aria-label="Search jobs"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="h-7 w-[160px] sm:w-[200px] text-xs rounded-md border pl-7 pr-2"
style={{
backgroundColor: 'var(--input)',
borderColor: 'var(--border)',
color: 'var(--text)',
}}
/>
</div>
<Select value={statusFilter} onValueChange={(v) => {
setStatusFilter(v)
localStorage.setItem("nomad-karaoke-status-filter", v)
}}>
<SelectTrigger className="h-7 w-[130px] text-xs" aria-label="Filter by status">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All statuses</SelectItem>
<SelectItem value="active">Active</SelectItem>
<SelectItem value="failed">Failed</SelectItem>
<SelectItem value="complete">Completed</SelectItem>
<SelectItem value="cancelled">Cancelled</SelectItem>
<SelectItem value="awaiting_review">Awaiting review</SelectItem>
<SelectItem value="processing">Processing</SelectItem>
</SelectContent>
</Select>
<Select value={String(jobLimit)} onValueChange={(v) => {
const val = Number(v)
setJobLimit(val)
localStorage.setItem("nomad-karaoke-job-limit", String(val))
}}>
<SelectTrigger className="h-7 w-[70px] text-xs" aria-label="Results per page">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
<SelectItem value="50">50</SelectItem>
<SelectItem value="100">100</SelectItem>
<SelectItem value="1000">1000</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<CardDescription style={{ color: 'var(--text-muted)' }}>
{!hasFetchedSuccessfully
? 'Loading...'
: searchQuery || (statusFilter !== 'all' && statusFilter !== 'active')
? `${jobs.length} job${jobs.length !== 1 ? 's' : ''} matching filters`
: `${jobs.length} job${jobs.length !== 1 ? 's' : ''}`}
</CardDescription>
</CardHeader>
<CardContent className="px-3 sm:px-6">
{jobs.length === 0 ? (
<div className="text-center py-8" style={{ color: 'var(--text-muted)' }}>
{!hasFetchedSuccessfully ? (
<>
<Loader2 className="w-12 h-12 mx-auto mb-3 opacity-50 animate-spin" />
<p>Loading jobs...</p>
</>
) : searchQuery || (statusFilter !== 'all' && statusFilter !== 'active') ? (
<>
<Search className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>No jobs match your filters.</p>
</>
) : (
<>
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>No jobs yet. Create one to get started!</p>
</>
)}
</div>
) : (
<div className="space-y-3">
{jobs.map((job) => (
<JobCard key={job.job_id} job={job} onRefresh={loadJobs} showAdminControls={isAdmin && showAdminControls} />
))}
</div>
)}
</CardContent>
</Card>
</div>
</main>
<VersionFooter />
</div>
)
}
// Wrap with Suspense for useSearchParams
export default function AppPage() {
return (
<Suspense fallback={
<div className="min-h-screen flex items-center justify-center animated-gradient">
<Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--text-muted)' }} />
</div>
}>
<AppPageContent />
</Suspense>
)
export default function DashboardRedirect() {
return <LocaleRedirect />
}
+3 -275
View File
@@ -1,277 +1,5 @@
"use client"
import { LocaleRedirect } from "@/components/LocaleRedirect"
import { Suspense, useEffect, useState, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Loader2, CheckCircle, XCircle, Gift, ShoppingCart } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useAuth } from "@/lib/auth"
type VerifyState = "verifying" | "preparing" | "credits_granted" | "credits_denied" | "credits_pending" | "success" | "error"
function VerifyMagicLinkContent() {
const router = useRouter()
const searchParams = useSearchParams()
const [state, setState] = useState<VerifyState>("verifying")
const [errorMessage, setErrorMessage] = useState("")
const [creditsGranted, setCreditsGranted] = useState(0)
const [creditStatus, setCreditStatus] = useState<string>("not_applicable")
const hasVerified = useRef(false)
const { verifyMagicLink, user, error } = useAuth()
useEffect(() => {
if (hasVerified.current) return
hasVerified.current = true
const token = searchParams.get("token")
if (!token) {
setState("error")
setErrorMessage("No verification token provided")
return
}
const verify = async () => {
// Show "preparing your account" while the backend runs AI evaluation
setState("preparing")
const success = await verifyMagicLink(token)
if (success) {
const lastVerifyResponse = (window as any).__LAST_VERIFY_RESPONSE__
const credits = lastVerifyResponse?.credits_granted || 0
const status = lastVerifyResponse?.credit_status || "not_applicable"
setCreditsGranted(credits)
setCreditStatus(status)
// Check for tenant subdomain redirect
if (lastVerifyResponse?.tenant_subdomain) {
const currentHost = window.location.hostname.toLowerCase()
const tenantSubdomain = lastVerifyResponse.tenant_subdomain.toLowerCase()
if (currentHost !== tenantSubdomain) {
setState("success")
setTimeout(() => {
window.location.href = `https://${tenantSubdomain}/app`
}, 1500)
return
}
}
// Show appropriate interstitial based on credit status
if (status === "granted" && credits > 0) {
setState("credits_granted")
} else if (status === "denied") {
setState("credits_denied")
} else if (status === "pending_review") {
setState("credits_pending")
} else {
// Returning user or not applicable — go straight to app
setState("success")
setTimeout(() => {
router.push("/app")
}, 1500)
}
} else {
setState("error")
const authStore = useAuth.getState()
setErrorMessage(authStore.error || "Invalid or expired link")
}
}
verify()
}, [searchParams, verifyMagicLink, router])
const goToApp = () => router.push("/app")
const goToBuy = () => router.push("/app?buy=true")
return (
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
{/* Verifying token */}
{state === "verifying" && (
<>
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Verifying your sign-in link...
</h1>
<p className="text-muted-foreground">
Please wait while we sign you in.
</p>
</>
)}
{/* Preparing account (AI evaluation running) */}
{state === "preparing" && (
<>
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Preparing your account...
</h1>
<p className="text-muted-foreground">
Just a moment while we set things up for you.
</p>
</>
)}
{/* Credits granted - celebratory interstitial */}
{state === "credits_granted" && (
<>
<div className="relative mx-auto mb-4 w-16 h-16">
<Gift className="w-16 h-16 text-primary" />
</div>
<h1 className="text-2xl font-bold text-foreground mb-2">
Welcome to Nomad Karaoke!
</h1>
<div className="bg-primary/10 border border-primary/20 rounded-lg p-4 mb-4">
<p className="text-3xl font-bold text-primary">{creditsGranted}</p>
<p className="text-sm font-medium text-primary/80">free credits to get started</p>
</div>
<p className="text-sm text-muted-foreground mb-2">
Each credit creates one professional karaoke video.
</p>
<p className="text-xs text-muted-foreground mb-6">
These credits cost us real money to fulfil, so please use them wisely
and let us know what you think!
</p>
<Button
onClick={goToApp}
className="w-full bg-primary hover:bg-primary/90"
>
Start Creating Karaoke
</Button>
</>
)}
{/* Credits denied - friendly rejection interstitial */}
{state === "credits_denied" && (
<>
<XCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Welcome to Nomad Karaoke
</h1>
<p className="text-muted-foreground mb-4">
We weren&apos;t able to grant free credits this time.
Karaoke generation costs us real money for every job,
so we need to be careful about free credit distribution.
</p>
<p className="text-sm text-muted-foreground mb-6">
If you think this is a mistake, check your email — we&apos;ve sent you
details on how to reach out to get this resolved.
</p>
<div className="space-y-2">
<Button
onClick={goToBuy}
className="w-full bg-primary hover:bg-primary/90"
>
<ShoppingCart className="w-4 h-4 mr-2" />
Buy Credits
</Button>
<Button
onClick={goToApp}
variant="ghost"
className="w-full"
>
Go to Dashboard
</Button>
</div>
</>
)}
{/* Credits pending review - friendly holding message */}
{state === "credits_pending" && (
<>
<Loader2 className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Welcome to Nomad Karaoke!
</h1>
<p className="text-muted-foreground mb-4">
We weren&apos;t able to assign your free credits automatically this time.
Our team will review your signup shortly and assign credits if we&apos;re able to.
</p>
<p className="text-sm text-muted-foreground mb-6">
You can still explore the app while you wait, or purchase credits
to get started right away.
</p>
<div className="space-y-2">
<Button
onClick={goToBuy}
className="w-full bg-primary hover:bg-primary/90"
>
<ShoppingCart className="w-4 h-4 mr-2" />
Buy Credits
</Button>
<Button
onClick={goToApp}
variant="ghost"
className="w-full"
>
Explore the App
</Button>
</div>
</>
)}
{/* Simple success (returning user) */}
{state === "success" && (
<>
<CheckCircle className="w-12 h-12 text-success mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Successfully signed in!
</h1>
<p className="text-muted-foreground mb-4">
Welcome back{user?.email ? `, ${user.email}` : ""}!
</p>
<p className="text-sm text-muted-foreground">
Redirecting you to the app...
</p>
</>
)}
{/* Error */}
{state === "error" && (
<>
<XCircle className="w-12 h-12 text-destructive mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Sign-in failed
</h1>
<p className="text-muted-foreground mb-6">
{errorMessage || "The link may have expired or already been used."}
</p>
<div className="space-y-2">
<Button
onClick={() => router.push("/app")}
className="w-full bg-primary hover:bg-primary/90"
>
Go to App
</Button>
<p className="text-xs text-muted-foreground">
You can request a new sign-in link from the app.
</p>
</div>
</>
)}
</div>
)
}
function VerifyLoadingFallback() {
return (
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
Loading...
</h1>
<p className="text-muted-foreground">
Please wait.
</p>
</div>
)
}
export default function VerifyMagicLinkPage() {
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<Suspense fallback={<VerifyLoadingFallback />}>
<VerifyMagicLinkContent />
</Suspense>
</div>
)
export default function VerifyRedirect() {
return <LocaleRedirect />
}
+3 -77
View File
@@ -1,79 +1,5 @@
"use client"
import { LocaleRedirect } from "@/components/LocaleRedirect"
import { Suspense } from "react"
import { useSearchParams } from "next/navigation"
import { CheckCircle, Loader2, Mail, Clock } from "lucide-react"
import { Button } from "@/components/ui/button"
function OrderSuccessContent() {
const searchParams = useSearchParams()
const sessionId = searchParams.get("session_id")
return (
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
<CheckCircle className="w-16 h-16 text-success mx-auto mb-4" />
<h1 className="text-2xl font-bold text-foreground mb-2">
Order Confirmed!
</h1>
<p className="text-muted-foreground mb-6">
Thank you for your order. We&apos;re creating your custom karaoke video now.
</p>
<div className="space-y-4 mb-6">
<div className="flex items-center gap-3 text-left p-3 bg-secondary rounded-lg">
<Clock className="w-5 h-5 text-primary flex-shrink-0" />
<div>
<p className="font-medium text-foreground">Delivery within 24 hours</p>
<p className="text-sm text-muted-foreground">
Most orders are completed in just a few hours
</p>
</div>
</div>
<div className="flex items-center gap-3 text-left p-3 bg-secondary rounded-lg">
<Mail className="w-5 h-5 text-primary flex-shrink-0" />
<div>
<p className="font-medium text-foreground">Check your email</p>
<p className="text-sm text-muted-foreground">
We&apos;ll send your video when it&apos;s ready
</p>
</div>
</div>
</div>
<div className="space-y-3">
<Button
asChild
className="w-full bg-primary hover:bg-primary/90"
>
<a href="https://nomadkaraoke.com">
Back to Nomad Karaoke
</a>
</Button>
<p className="text-xs text-muted-foreground">
Questions? Email us at help@nomadkaraoke.com
</p>
</div>
</div>
)
}
export default function OrderSuccessPage() {
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<Suspense
fallback={
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
<Loader2 className="w-16 h-16 text-primary mx-auto mb-4 animate-spin" />
<p className="text-muted-foreground">Loading...</p>
</div>
}
>
<OrderSuccessContent />
</Suspense>
</div>
)
export default function OrderRedirect() {
return <LocaleRedirect />
}
+2 -34
View File
@@ -1,37 +1,5 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { routing } from '@/i18n/routing';
import { LocaleRedirect } from "@/components/LocaleRedirect"
export default function RootPage() {
const router = useRouter();
useEffect(() => {
// 1. Check localStorage for saved preference
try {
const saved = localStorage.getItem('locale');
if (saved && routing.locales.includes(saved as typeof routing.locales[number])) {
router.replace(`/${saved}/`);
return;
}
} catch {
// localStorage not available
}
// 2. Detect from browser language
const browserLangs = navigator.languages || [navigator.language];
for (const lang of browserLangs) {
const prefix = lang.split('-')[0].toLowerCase();
if (routing.locales.includes(prefix as typeof routing.locales[number])) {
router.replace(`/${prefix}/`);
return;
}
}
// 3. Fallback to default
router.replace(`/${routing.defaultLocale}/`);
}, [router]);
return null;
return <LocaleRedirect />
}
+3 -83
View File
@@ -1,85 +1,5 @@
"use client"
import { LocaleRedirect } from "@/components/LocaleRedirect"
import { Suspense, useEffect, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { CheckCircle, Loader2, Coins } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useAuth } from "@/lib/auth"
function PaymentSuccessContent() {
const router = useRouter()
const searchParams = useSearchParams()
const [isLoading, setIsLoading] = useState(true)
const { user, fetchUser } = useAuth()
useEffect(() => {
// Refresh user data to get updated credits
const refreshUser = async () => {
await fetchUser()
setIsLoading(false)
}
refreshUser()
}, [fetchUser])
const sessionId = searchParams.get("session_id")
return (
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
<CheckCircle className="w-16 h-16 text-success mx-auto mb-4" />
<h1 className="text-2xl font-bold text-foreground mb-2">
Payment Successful!
</h1>
<p className="text-muted-foreground mb-6">
Thank you for your purchase. Your credits have been added to your account.
</p>
{isLoading ? (
<div className="flex items-center justify-center gap-2 text-muted-foreground mb-6">
<Loader2 className="w-4 h-4 animate-spin" />
Loading your balance...
</div>
) : user ? (
<div className="bg-secondary rounded-lg p-4 mb-6">
<div className="flex items-center justify-center gap-2 text-warning">
<Coins className="w-5 h-5" />
<span className="text-2xl font-bold">{user.credits}</span>
<span className="text-muted-foreground">credits available</span>
</div>
</div>
) : null}
<div className="space-y-3">
<Button
onClick={() => router.push("/app")}
className="w-full bg-primary hover:bg-primary/90"
>
Start Creating Karaoke
</Button>
<p className="text-xs text-muted-foreground">
A confirmation email has been sent to your email address.
</p>
</div>
</div>
)
}
export default function PaymentSuccessPage() {
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<Suspense
fallback={
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
<Loader2 className="w-16 h-16 text-primary mx-auto mb-4 animate-spin" />
<p className="text-muted-foreground">Loading...</p>
</div>
}
>
<PaymentSuccessContent />
</Suspense>
</div>
)
export default function PaymentRedirect() {
return <LocaleRedirect />
}
+45
View File
@@ -0,0 +1,45 @@
'use client';
import { useEffect } from 'react';
import { routing } from '@/i18n/routing';
/**
* Detects the user's preferred locale and redirects to the locale-prefixed
* version of the current URL. Preserves path, query string, and hash.
*
* Used by legacy non-locale routes (e.g., /app → /en/app) to redirect
* to the proper [locale] routes.
*/
export function LocaleRedirect() {
useEffect(() => {
const locale = detectLocale();
const { pathname, search, hash } = window.location;
window.location.replace(`/${locale}${pathname}${search}${hash}`);
}, []);
return null;
}
function detectLocale(): string {
// 1. Check localStorage for saved preference
try {
const saved = localStorage.getItem('locale');
if (saved && routing.locales.includes(saved as typeof routing.locales[number])) {
return saved;
}
} catch {
// localStorage not available
}
// 2. Detect from browser language
const browserLangs = navigator.languages || [navigator.language];
for (const lang of browserLangs) {
const prefix = lang.split('-')[0].toLowerCase();
if (routing.locales.includes(prefix as typeof routing.locales[number])) {
return prefix;
}
}
// 3. Fallback to default
return routing.defaultLocale;
}
+1 -1
View File
@@ -1,7 +1,7 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { useRouter } from '@/i18n/routing'
import { TenantLogo } from '@/components/tenant-logo'
import { AuthDialog } from '@/components/auth/AuthDialog'
import { useTenant } from '@/lib/tenant'
+7 -7
View File
@@ -1,6 +1,7 @@
"use client"
import { useRouter } from "next/navigation"
import { useRouter, Link } from "@/i18n/routing"
import NextLink from "next/link"
import { useAuth } from "@/lib/auth"
import { Logo } from "./logo"
import { Button } from "./ui/button"
@@ -13,7 +14,6 @@ import {
DropdownMenuTrigger,
} from "./ui/dropdown-menu"
import { User, LogOut, Settings, Shield, Mail, Phone, HelpCircle, Eye } from "lucide-react"
import Link from "next/link"
import LanguageSwitcher from "./LanguageSwitcher"
import { useTranslations } from "next-intl"
@@ -29,7 +29,7 @@ export function AppHeader() {
const handleBackToAdmin = () => {
endImpersonation()
router.push("/admin")
window.location.href = "/admin"
}
if (!user) return null
@@ -49,9 +49,9 @@ export function AppHeader() {
{t('myJobs')}
</Link>
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
<Link href="/admin" className="text-sm font-medium hover:text-primary transition-colors">
<NextLink href="/admin" className="text-sm font-medium hover:text-primary transition-colors">
{t('admin')}
</Link>
</NextLink>
)}
</nav>
@@ -124,10 +124,10 @@ export function AppHeader() {
</DropdownMenuItem>
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
<DropdownMenuItem asChild>
<Link href="/admin">
<NextLink href="/admin">
<Shield className="w-4 h-4 mr-2" />
{t('adminDashboard')}
</Link>
</NextLink>
</DropdownMenuItem>
)}
<DropdownMenuItem>
@@ -26,7 +26,7 @@ import {
ChevronRight,
X,
} from "lucide-react"
import Link from "next/link"
import { Link } from "@/i18n/routing"
// ─── Types ─────────────────────────────────────────────────────────
+1 -1
View File
@@ -2,7 +2,7 @@
import { useState, useEffect } from "react"
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical, Gift } from "lucide-react"
import Link from "next/link"
import { Link } from "@/i18n/routing"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
+2 -2
View File
@@ -1,6 +1,6 @@
"use client"
import { useRouter } from "next/navigation"
import { useRouter as useNextRouter } from "next/navigation"
import { useAuth } from "@/lib/auth"
import { Button } from "@/components/ui/button"
import { Eye, Shield } from "lucide-react"
@@ -11,7 +11,7 @@ import { Eye, Shield } from "lucide-react"
*/
export function ImpersonationBanner() {
const { isImpersonating, impersonatedUserEmail, endImpersonation } = useAuth()
const router = useRouter()
const router = useNextRouter()
if (!isImpersonating) {
return null
@@ -1,12 +1,11 @@
"use client"
import { useState, useEffect, useRef, useCallback, useMemo } from "react"
import { useRouter } from "next/navigation"
import { useRouter, Link } from "@/i18n/routing"
import { useTranslations } from 'next-intl'
import { Button } from "@/components/ui/button"
import { Spinner } from "@/components/ui/spinner"
import { ArrowLeft, Play, Pause, Check } from "lucide-react"
import Link from "next/link"
import { toast } from "sonner"
import {
api,
@@ -2,7 +2,7 @@
import { useTranslations } from 'next-intl'
import { useState, useEffect, useCallback, useMemo, useRef, memo } from 'react'
import { useRouter } from 'next/navigation'
import { useRouter } from '@/i18n/routing'
import { Button } from '@/components/ui/button'
import { Video, Check, CheckCircle2 } from 'lucide-react'
import { toast } from 'sonner'
+1 -1
View File
@@ -3,7 +3,7 @@
import type React from "react"
import { useEffect } from "react"
import { useRouter } from "next/navigation"
import { useRouter } from "@/i18n/routing"
import { useAuth } from "@/lib/auth"
interface ProtectedRouteProps {
+9 -1
View File
@@ -36,5 +36,13 @@ const customJestConfig = {
}
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)
// We must override transformIgnorePatterns AFTER next/jest generates its config,
// because next/jest's defaults would otherwise re-add next-intl to the ignore list.
module.exports = async () => {
const jestConfig = await createJestConfig(customJestConfig)()
jestConfig.transformIgnorePatterns = [
'/node_modules/(?!(next-intl|use-intl|@formatjs|intl-messageformat)/)',
]
return jestConfig
}
+23
View File
@@ -36,6 +36,29 @@ jest.mock('next-intl', () => ({
NextIntlClientProvider: ({ children }) => children,
}))
// Mock @/i18n/routing — locale-aware navigation primitives
jest.mock('@/i18n/routing', () => {
const React = require('react')
return {
routing: {
locales: ['en', 'es', 'de'],
defaultLocale: 'en',
},
Link: ({ children, href, ...props }) =>
React.createElement('a', { href, ...props }, children),
redirect: jest.fn(),
usePathname: () => '/',
useRouter: () => ({
push: jest.fn(),
replace: jest.fn(),
prefetch: jest.fn(),
back: jest.fn(),
forward: jest.fn(),
refresh: jest.fn(),
}),
}
})
// Mock window.matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.160.2"
version = "0.161.0"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"