Merge pull request 'dev' (#4) from dev into master

Reviewed-on: #4
This commit was merged in pull request #4.
This commit is contained in:
2026-02-07 21:23:11 -05:00
18 changed files with 1056 additions and 1582 deletions

View File

@@ -1,20 +1,20 @@
/* Desktop navigation - visible on medium screens and up */ /* Desktop navigation - visible on larger screens */
.desktop-nav { .desktop-nav {
display: none; display: none;
} }
@media (min-width: 768px) { @media (min-width: 1280px) {
.desktop-nav { .desktop-nav {
display: flex; display: flex;
} }
} }
/* Mobile navigation - visible below medium screens */ /* Mobile navigation - visible below larger screens */
.mobile-nav { .mobile-nav {
display: flex; display: flex;
} }
@media (min-width: 768px) { @media (min-width: 1280px) {
.mobile-nav { .mobile-nav {
display: none; display: none;
} }
@@ -42,7 +42,7 @@
border-radius: 12px; border-radius: 12px;
} }
@media (min-width: 768px) { @media (min-width: 1280px) {
.mobile-menu-dropdown { .mobile-menu-dropdown {
display: none; display: none;
} }
@@ -56,14 +56,14 @@ nav {
width: 100%; width: 100%;
} }
@media (min-width: 768px) { @media (min-width: 1280px) {
.desktop-nav { .desktop-nav {
flex: 1; flex: 1;
display: flex; display: flex;
align-items: center; align-items: center;
min-width: 0; min-width: 0;
margin-left: 2rem; margin-left: 2rem;
gap: clamp(0.75rem, 1.5vw, 1.25rem); gap: clamp(0.5rem, 1vw, 1rem);
} }
} }
@@ -72,17 +72,20 @@ nav {
flex: 1; flex: 1;
justify-content: flex-end; justify-content: flex-end;
align-items: center; align-items: center;
gap: clamp(0.75rem, 1.5vw, 1.25rem); flex-wrap: nowrap;
overflow: visible;
gap: clamp(0.25rem, 0.75vw, 0.75rem);
margin: 0; margin: 0;
padding: 0; padding: 0 0.25rem;
} }
.desktop-nav-list li { .desktop-nav-list li {
flex-shrink: 1; flex-shrink: 0;
} }
.desktop-nav-list a { .desktop-nav-list a {
white-space: nowrap; white-space: nowrap;
padding: 0.375rem 0.625rem;
} }
.nav-user-inline { .nav-user-inline {

View File

@@ -6,10 +6,10 @@
} }
:root { :root {
--lrc-text-color: #333; /* darker text */ --lrc-text-color: #666; /* muted text for inactive lines */
--lrc-bg-color: rgba(0, 0, 0, 0.05); --lrc-bg-color: rgba(0, 0, 0, 0.05);
--lrc-active-color: #000; /* bold black for active */ --lrc-active-color: #000; /* bold black for active */
--lrc-active-shadow: none; /* no glow in light mode */ --lrc-active-shadow: 0 1px 2px rgba(0, 0, 0, 0.15); /* subtle shadow in light mode */
--lrc-hover-color: #005fcc; /* darker blue hover */ --lrc-hover-color: #005fcc; /* darker blue hover */
} }
@@ -259,7 +259,7 @@ body {
opacity: 1; opacity: 1;
pointer-events: auto; pointer-events: auto;
transition: opacity 0.3s ease; transition: opacity 0.3s ease;
max-height: 125px; max-height: 220px;
max-width: 100%; max-width: 100%;
overflow-y: auto; overflow-y: auto;
margin-top: 1rem; margin-top: 1rem;
@@ -277,6 +277,9 @@ body {
scrollbar-width: thin; scrollbar-width: thin;
scrollbar-color: #999 transparent; scrollbar-color: #999 transparent;
scroll-padding-bottom: 1rem; scroll-padding-bottom: 1rem;
overscroll-behavior: contain;
touch-action: pan-y;
scroll-behavior: smooth;
} }
.lrc-text.empty { .lrc-text.empty {
@@ -297,9 +300,10 @@ body {
.lrc-line.active { .lrc-line.active {
color: var(--lrc-active-color); color: var(--lrc-active-color);
font-weight: 600; font-weight: 700;
font-size: 0.8rem; font-size: 0.95rem;
text-shadow: var(--lrc-active-shadow); text-shadow: var(--lrc-active-shadow);
transform: scale(1.02);
} }
.lrc-line:hover { .lrc-line:hover {

View File

@@ -1,27 +1,49 @@
import React, { Suspense, lazy, useState, useMemo, useEffect } from 'react'; import React, { Suspense, lazy, useState, useMemo, useEffect } from 'react';
import type { ComponentType } from 'react'; import type { ComponentType } from 'react';
import Memes from './Memes.jsx'; import Memes from './Memes.tsx';
import Lighting from './Lighting.jsx'; import Lighting from './Lighting.tsx';
import { toast } from 'react-toastify'; import { toast } from 'react-toastify';
import { JoyUIRootIsland } from './Components.jsx'; import { JoyUIRootIsland } from './Components.tsx';
import { PrimeReactProvider } from "primereact/api"; import { PrimeReactProvider } from "primereact/api";
import { usePrimeReactThemeSwitcher } from '@/hooks/usePrimeReactThemeSwitcher.jsx'; import { usePrimeReactThemeSwitcher } from '@/hooks/usePrimeReactThemeSwitcher.tsx';
import CustomToastContainer from '../components/ToastProvider.jsx'; import CustomToastContainer from '../components/ToastProvider.tsx';
import 'primereact/resources/themes/bootstrap4-light-blue/theme.css'; import 'primereact/resources/themes/bootstrap4-light-blue/theme.css';
import 'primereact/resources/primereact.min.css'; import 'primereact/resources/primereact.min.css';
import "primeicons/primeicons.css"; import "primeicons/primeicons.css";
const LoginPage = lazy(() => import('./Login.jsx')); const LoginPage = lazy(() => import('./Login.tsx'));
const LyricSearch = lazy(() => import('./LyricSearch')); const LyricSearch = lazy(() => import('./LyricSearch'));
const MediaRequestForm = lazy(() => import('./TRip/MediaRequestForm.jsx')); const MediaRequestForm = lazy(() => import('./TRip/MediaRequestForm.tsx'));
const RequestManagement = lazy(() => import('./TRip/RequestManagement.jsx')); const RequestManagement = lazy(() => import('./TRip/RequestManagement.tsx'));
const DiscordLogs = lazy(() => import('./DiscordLogs.jsx')); const DiscordLogs = lazy(() => import('./DiscordLogs.tsx'));
// NOTE: Player is intentionally NOT imported at module initialization. // NOTE: Player is intentionally NOT imported at module initialization.
// We create the lazy import inside the component at render-time only when // We create the lazy import inside the component at render-time only when
// we are on the main site and the Player island should be rendered. This // we are on the main site and the Player island should be rendered. This
// prevents bundling the player island into pages that are explicitly // prevents bundling the player island into pages that are explicitly
// identified as subsites. // identified as subsites.
const ReqForm = lazy(() => import('./req/ReqForm.jsx')); const ReqForm = lazy(() => import('./req/ReqForm.tsx'));
// Simple error boundary for lazy islands
class LazyBoundary extends React.Component<{ children: React.ReactNode }, { hasError: boolean }> {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(err) {
if (import.meta.env.DEV) {
console.error('[AppLayout] lazy island error', err);
}
}
render() {
if (this.state.hasError) {
return <div style={{ padding: '1rem', textAlign: 'center' }}>Something went wrong loading this module.</div>;
}
return this.props.children;
}
}
declare global { declare global {
interface Window { interface Window {
@@ -55,15 +77,18 @@ export default function Root({ child, user = undefined, ...props }: RootProps):
// don't need to pass guards. // don't need to pass guards.
const isSubsite = typeof document !== 'undefined' && document.documentElement.getAttribute('data-subsite') === 'true'; const isSubsite = typeof document !== 'undefined' && document.documentElement.getAttribute('data-subsite') === 'true';
// Log when the active child changes (DEV only) // Log when the active child changes (DEV only)
const devLogsEnabled = import.meta.env.DEV && import.meta.env.VITE_DEV_LOGS === '1';
useEffect(() => { useEffect(() => {
if (!devLogsEnabled) return;
try { try {
if (typeof console !== 'undefined' && typeof document !== 'undefined' && import.meta.env.DEV) { if (typeof console !== 'undefined' && typeof document !== 'undefined') {
console.debug(`[AppLayout] child=${String(child)}, data-subsite=${document.documentElement.getAttribute('data-subsite')}`); console.debug(`[AppLayout] child=${String(child)}, data-subsite=${document.documentElement.getAttribute('data-subsite')}`);
} }
} catch (e) { } catch (e) {
// no-op // no-op
} }
}, [child]); }, [child, devLogsEnabled]);
// Only initialize the lazy player when this is NOT a subsite and the // Only initialize the lazy player when this is NOT a subsite and the
// active child is the Player island. Placing the lazy() call here // active child is the Player island. Placing the lazy() call here
@@ -82,7 +107,7 @@ export default function Root({ child, user = undefined, ...props }: RootProps):
let mounted = true; let mounted = true;
if (wantPlayer) { if (wantPlayer) {
if (import.meta.env.DEV) { try { console.debug('[AppLayout] dynamic-import: requesting AudioPlayer'); } catch (e) { } } if (import.meta.env.DEV) { try { console.debug('[AppLayout] dynamic-import: requesting AudioPlayer'); } catch (e) { } }
import('./Radio.js') import('./Radio.tsx')
.then((mod) => { .then((mod) => {
if (!mounted) return; if (!mounted) return;
// set the component factory // set the component factory
@@ -114,23 +139,59 @@ export default function Root({ child, user = undefined, ...props }: RootProps):
color="danger"> color="danger">
Work in progress... bugs are to be expected. Work in progress... bugs are to be expected.
</Alert> */} </Alert> */}
{child == "LoginPage" && (<LoginPage {...props} loggedIn={loggedIn} />)} {child == "LoginPage" && (
{child == "LyricSearch" && (<LyricSearch />)} <LazyBoundary>
<Suspense fallback={<div style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>}>
<LoginPage {...props} loggedIn={loggedIn} />
</Suspense>
</LazyBoundary>
)}
{child == "LyricSearch" && (
<LazyBoundary>
<Suspense fallback={<div style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>}>
<LyricSearch />
</Suspense>
</LazyBoundary>
)}
{child == "Player" && !isSubsite && PlayerComp && ( {child == "Player" && !isSubsite && PlayerComp && (
<LazyBoundary>
<Suspense fallback={null}> <Suspense fallback={null}>
<PlayerComp user={user} /> <PlayerComp user={user} />
</Suspense> </Suspense>
</LazyBoundary>
)}
{child == "Memes" && (
<LazyBoundary>
<Memes />
</LazyBoundary>
)} )}
{child == "Memes" && <Memes />}
{child == "DiscordLogs" && ( {child == "DiscordLogs" && (
<LazyBoundary>
<Suspense fallback={<div style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>}> <Suspense fallback={<div style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>}>
<DiscordLogs /> <DiscordLogs />
</Suspense> </Suspense>
</LazyBoundary>
)}
{child == "qs2.MediaRequestForm" && (
<LazyBoundary>
<MediaRequestForm />
</LazyBoundary>
)}
{child == "qs2.RequestManagement" && (
<LazyBoundary>
<RequestManagement />
</LazyBoundary>
)}
{child == "ReqForm" && (
<LazyBoundary>
<ReqForm />
</LazyBoundary>
)}
{child == "Lighting" && (
<LazyBoundary>
<Lighting key={window.location.pathname + Math.random()} />
</LazyBoundary>
)} )}
{child == "qs2.MediaRequestForm" && <MediaRequestForm />}
{child == "qs2.RequestManagement" && <RequestManagement />}
{child == "ReqForm" && <ReqForm />}
{child == "Lighting" && <Lighting key={window.location.pathname + Math.random()} />}
</JoyUIRootIsland> </JoyUIRootIsland>
</PrimeReactProvider> </PrimeReactProvider>
); );

View File

@@ -3284,9 +3284,14 @@ export default function DiscordLogs() {
// Check if current channel is dds-archive // Check if current channel is dds-archive
const isArchiveChannel = selectedChannel?.name === 'dds-archive'; const isArchiveChannel = selectedChannel?.name === 'dds-archive';
// Check if current channel is a thread (types 10, 11, 12)
const isThread = selectedChannel?.type === 10 || selectedChannel?.type === 11 || selectedChannel?.type === 12;
// Check if Havoc bot is in the channel's member list // Check if Havoc bot is in the channel's member list
const HAVOC_BOT_ID = '1219636064608583770'; const HAVOC_BOT_ID = '1219636064608583770';
const isHavocInChannel = useMemo(() => { const isHavocInChannel = useMemo(() => {
// Threads inherit access from parent channel - if we can see the thread, Havoc has access
if (isThread) return true;
if (!members?.groups) return true; // Assume present if members not loaded if (!members?.groups) return true; // Assume present if members not loaded
for (const group of members.groups) { for (const group of members.groups) {
if (group.members?.some(m => m.id === HAVOC_BOT_ID)) { if (group.members?.some(m => m.id === HAVOC_BOT_ID)) {
@@ -3294,7 +3299,7 @@ export default function DiscordLogs() {
} }
} }
return false; return false;
}, [members]); }, [members, isThread]);
// Group messages by author and time window (5 minutes) // Group messages by author and time window (5 minutes)
// Messages are in ASC order (oldest first, newest at bottom), so we group accordingly // Messages are in ASC order (oldest first, newest at bottom), so we group accordingly

View File

@@ -14,6 +14,96 @@ function clearCookie(name: string): void {
document.cookie = `${name}=; Max-Age=0; path=/;`; document.cookie = `${name}=; Max-Age=0; path=/;`;
} }
// Trusted domains for redirect validation
const TRUSTED_DOMAINS = ['codey.lol', 'boatson.boats'];
/**
* Parse and decode the redirect URL from query params
*/
function getRedirectParam(): string | null {
const urlParams = new URLSearchParams(window.location.search);
let redirectParam = urlParams.get('redirect') || urlParams.get('returnUrl');
if (!redirectParam) return null;
// Handle double-encoding
if (redirectParam.includes('%')) {
try {
redirectParam = decodeURIComponent(redirectParam);
} catch {
// If decoding fails, use the original value
}
}
return redirectParam;
}
/**
* Check if a URL is a valid trusted external URL
*/
function isTrustedExternalUrl(url: string): boolean {
try {
const parsed = new URL(url);
if (parsed.protocol !== 'https:') return false;
return TRUSTED_DOMAINS.some(domain =>
parsed.hostname === domain || parsed.hostname.endsWith('.' + domain)
);
} catch {
return false;
}
}
/**
* Get validated redirect URL for POST-LOGIN redirect (after form submission)
* Allows: relative paths OR trusted external URLs
* This is safe because the user just authenticated fresh
*/
function getPostLoginRedirectUrl(): string {
const redirectParam = getRedirectParam();
if (!redirectParam) return '/';
// Relative path: must start with '/' but not '//' (protocol-relative)
if (redirectParam.startsWith('/') && !redirectParam.startsWith('//')) {
return redirectParam;
}
// External URL: must be https and trusted domain
if (isTrustedExternalUrl(redirectParam)) {
return redirectParam;
}
return '/';
}
/**
* Get validated redirect URL for AUTO-REDIRECT (when already logged in)
* Only allows: relative paths
* External URLs are BLOCKED because if a logged-in user was redirected here
* from an external resource, nginx denied them access - redirecting back would loop
*/
function getAutoRedirectUrl(): string | null {
const redirectParam = getRedirectParam();
if (!redirectParam) return null;
// Only allow relative paths for auto-redirect
if (redirectParam.startsWith('/') && !redirectParam.startsWith('//')) {
return redirectParam;
}
// Block external URLs - would cause redirect loop with nginx
return null;
}
/**
* Check if the returnUrl is an external trusted domain
* Used to detect access denial from nginx-protected external vhosts
*/
function isExternalReturnUrl(): boolean {
const redirectParam = getRedirectParam();
if (!redirectParam) return false;
if (redirectParam.startsWith('/')) return false;
return isTrustedExternalUrl(redirectParam);
}
interface LoginPageProps { interface LoginPageProps {
loggedIn?: boolean; loggedIn?: boolean;
accessDenied?: boolean; accessDenied?: boolean;
@@ -33,6 +123,16 @@ export default function LoginPage({ loggedIn = false, accessDenied = false, requ
} }
}, []); }, []);
// If user is already logged in and not access denied, redirect them
// This handles the case where token was refreshed successfully
// NOTE: Only auto-redirect to relative URLs - external URLs mean nginx denied access
useEffect(() => {
if (loggedIn && !accessDenied) {
const returnTo = getAutoRedirectUrl() || '/';
window.location.href = returnTo;
}
}, [loggedIn, accessDenied]);
async function handleSubmit(e: FormEvent<HTMLFormElement>): Promise<void> { async function handleSubmit(e: FormEvent<HTMLFormElement>): Promise<void> {
e.preventDefault(); e.preventDefault();
setLoading(true); setLoading(true);
@@ -53,7 +153,7 @@ export default function LoginPage({ loggedIn = false, accessDenied = false, requ
password, password,
grant_type: "password", grant_type: "password",
scope: "", scope: "",
client_id: "", client_id: "b8308cf47d424e66",
client_secret: "", client_secret: "",
}); });
@@ -86,11 +186,8 @@ export default function LoginPage({ loggedIn = false, accessDenied = false, requ
toast.success("Login successful!", { toast.success("Login successful!", {
toastId: "login-success-toast", toastId: "login-success-toast",
}); });
// Check for returnUrl in query params // After fresh login, allow redirect to external trusted URLs
const urlParams = new URLSearchParams(window.location.search); const returnTo = getPostLoginRedirectUrl();
const returnUrl = urlParams.get('returnUrl');
// Validate returnUrl is a relative path (security: prevent open redirect)
const returnTo = (returnUrl && returnUrl.startsWith('/')) ? returnUrl : '/';
window.location.href = returnTo; window.location.href = returnTo;
} else { } else {
toast.error("Login failed: no access token received", { toast.error("Login failed: no access token received", {
@@ -109,6 +206,10 @@ export default function LoginPage({ loggedIn = false, accessDenied = false, requ
if (loggedIn) { if (loggedIn) {
const rolesList = Array.isArray(requiredRoles) ? requiredRoles : (requiredRoles ? requiredRoles.split(',') : []); const rolesList = Array.isArray(requiredRoles) ? requiredRoles : (requiredRoles ? requiredRoles.split(',') : []);
// Check if this is an external resource denial (nginx redirect)
const isExternalDenial = rolesList.some(r => r === '(external resource)');
const displayRoles = rolesList.filter(r => r !== '(external resource)');
return ( return (
<div className="flex items-center justify-center px-4 py-16"> <div className="flex items-center justify-center px-4 py-16">
<div className="max-w-md w-full bg-white dark:bg-[#1a1a1a] rounded-2xl shadow-xl shadow-neutral-900/5 dark:shadow-black/30 border border-neutral-200/60 dark:border-neutral-800/60 px-10 py-8 text-center"> <div className="max-w-md w-full bg-white dark:bg-[#1a1a1a] rounded-2xl shadow-xl shadow-neutral-900/5 dark:shadow-black/30 border border-neutral-200/60 dark:border-neutral-800/60 px-10 py-8 text-center">
@@ -117,11 +218,11 @@ export default function LoginPage({ loggedIn = false, accessDenied = false, requ
<p className="text-sm text-neutral-600 dark:text-neutral-400 mb-4"> <p className="text-sm text-neutral-600 dark:text-neutral-400 mb-4">
You don't have permission to access this resource. You don't have permission to access this resource.
</p> </p>
{rolesList.length > 0 && ( {displayRoles.length > 0 && (
<div className="mb-5 p-3 bg-neutral-100 dark:bg-neutral-800/50 rounded-xl border border-neutral-200/60 dark:border-neutral-700/60"> <div className="mb-5 p-3 bg-neutral-100 dark:bg-neutral-800/50 rounded-xl border border-neutral-200/60 dark:border-neutral-700/60">
<p className="text-sm text-neutral-500 dark:text-neutral-500 mb-2 font-medium">Required role{rolesList.length > 1 ? 's' : ''}:</p> <p className="text-sm text-neutral-500 dark:text-neutral-500 mb-2 font-medium">Required role{displayRoles.length > 1 ? 's' : ''}:</p>
<div className="flex flex-wrap justify-center gap-2"> <div className="flex flex-wrap justify-center gap-2">
{rolesList.map((role, i) => ( {displayRoles.map((role, i) => (
<span key={i} className="px-2.5 py-1 text-xs font-semibold bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300 rounded-full"> <span key={i} className="px-2.5 py-1 text-xs font-semibold bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300 rounded-full">
{role} {role}
</span> </span>
@@ -129,6 +230,13 @@ export default function LoginPage({ loggedIn = false, accessDenied = false, requ
</div> </div>
</div> </div>
)} )}
{isExternalDenial && displayRoles.length === 0 && (
<div className="mb-5 p-3 bg-amber-50 dark:bg-amber-900/20 rounded-xl border border-amber-200/60 dark:border-amber-700/40">
<p className="text-sm text-amber-700 dark:text-amber-300">
This resource requires elevated permissions.
</p>
</div>
)}
<p className="text-xs italic text-neutral-400 dark:text-neutral-500 mb-5"> <p className="text-xs italic text-neutral-400 dark:text-neutral-500 mb-5">
If you believe this is an error, scream at codey. If you believe this is an error, scream at codey.
</p> </p>

View File

@@ -44,6 +44,11 @@ export default function Player({ user }: PlayerProps) {
// Global CSS now contains the paginator / dialog datatable dark rules. // Global CSS now contains the paginator / dialog datatable dark rules.
const [isQueueVisible, setQueueVisible] = useState(false); const [isQueueVisible, setQueueVisible] = useState(false);
const lrcContainerRef = useRef<HTMLDivElement | null>(null);
const lrcWheelHandlerRef = useRef<((e: WheelEvent) => void) | null>(null);
const lrcScrollTimeout = useRef<number | null>(null);
const lrcScrollRaf = useRef<number | null>(null);
const lrcActiveRef = useRef<HTMLElement | null>(null);
// Mouse wheel scroll fix for queue modal // Mouse wheel scroll fix for queue modal
useEffect(() => { useEffect(() => {
if (!isQueueVisible) return; if (!isQueueVisible) return;
@@ -151,6 +156,10 @@ export default function Player({ user }: PlayerProps) {
const lastUpdateTimestamp = useRef<number>(Date.now()); const lastUpdateTimestamp = useRef<number>(Date.now());
const activeStationRef = useRef<string>(activeStation); const activeStationRef = useRef<string>(activeStation);
const wsInstance = useRef<WebSocket | null>(null); const wsInstance = useRef<WebSocket | null>(null);
const wsReconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const wsConnectionCheckTimer = useRef<ReturnType<typeof setInterval> | null>(null);
const wsLastMessageTime = useRef<number>(Date.now());
const [isStreamReady, setIsStreamReady] = useState(false);
const formatTime = (seconds: number): string => { const formatTime = (seconds: number): string => {
if (!seconds || isNaN(seconds) || seconds < 0) return "00:00"; if (!seconds || isNaN(seconds) || seconds < 0) return "00:00";
@@ -166,6 +175,7 @@ export default function Player({ user }: PlayerProps) {
// Initialize or switch HLS stream // Initialize or switch HLS stream
const initializeStream = (station) => { const initializeStream = (station) => {
setIsStreamReady(false);
import('hls.js').then(({ default: Hls }) => { import('hls.js').then(({ default: Hls }) => {
const audio = audioElement.current; const audio = audioElement.current;
if (!audio) return; if (!audio) return;
@@ -183,11 +193,13 @@ export default function Player({ user }: PlayerProps) {
// Handle audio load errors // Handle audio load errors
audio.onerror = () => { audio.onerror = () => {
setIsPlaying(false); setIsPlaying(false);
setIsStreamReady(false);
}; };
if (audio.canPlayType("application/vnd.apple.mpegurl")) { if (audio.canPlayType("application/vnd.apple.mpegurl")) {
audio.src = streamUrl; audio.src = streamUrl;
audio.load(); audio.load();
setIsStreamReady(true);
audio.play().then(() => setIsPlaying(true)).catch(() => { audio.play().then(() => setIsPlaying(true)).catch(() => {
setTrackTitle("Offline"); setTrackTitle("Offline");
setIsPlaying(false); setIsPlaying(false);
@@ -217,6 +229,7 @@ export default function Player({ user }: PlayerProps) {
hls.attachMedia(audio); hls.attachMedia(audio);
hls.on(Hls.Events.MEDIA_ATTACHED, () => hls.loadSource(streamUrl)); hls.on(Hls.Events.MEDIA_ATTACHED, () => hls.loadSource(streamUrl));
hls.on(Hls.Events.MANIFEST_PARSED, () => { hls.on(Hls.Events.MANIFEST_PARSED, () => {
setIsStreamReady(true);
audio.play().then(() => setIsPlaying(true)).catch(() => { audio.play().then(() => setIsPlaying(true)).catch(() => {
setIsPlaying(false); setIsPlaying(false);
}); });
@@ -228,6 +241,7 @@ export default function Player({ user }: PlayerProps) {
hlsInstance.current = null; hlsInstance.current = null;
setTrackTitle("Offline"); setTrackTitle("Offline");
setIsPlaying(false); setIsPlaying(false);
setIsStreamReady(false);
} }
}); });
}); });
@@ -249,16 +263,56 @@ export default function Player({ user }: PlayerProps) {
// Scroll active lyric into view // Scroll active lyric into view
useEffect(() => { useEffect(() => {
setTimeout(() => { const container = lrcContainerRef.current;
const activeElement = document.querySelector('.lrc-line.active'); if (!container || lyrics.length === 0) return;
const lyricsContainer = document.querySelector('.lrc-text');
if (activeElement && lyricsContainer) { const scheduleScroll = () => {
(lyricsContainer as HTMLElement).style.maxHeight = '220px'; // Read ref/DOM inside the callback so we get the updated element after render
(lyricsContainer as HTMLElement).style.overflowY = 'auto'; const activeElement = lrcActiveRef.current || (container.querySelector('.lrc-line.active') as HTMLElement | null);
activeElement.scrollIntoView({ behavior: 'smooth', block: 'center' }); if (!activeElement) return;
// Use getBoundingClientRect for accurate positioning
const containerRect = container.getBoundingClientRect();
const activeRect = activeElement.getBoundingClientRect();
// Calculate where the element is relative to the container's current scroll
const elementTopInContainer = activeRect.top - containerRect.top + container.scrollTop;
// Center the active line in the container
const targetScrollTop = elementTopInContainer - (container.clientHeight / 2) + (activeElement.offsetHeight / 2);
container.scrollTo({ top: Math.max(targetScrollTop, 0), behavior: 'smooth' });
};
// Debounce a tick then align to paint frame so ref is updated after render
if (lrcScrollTimeout.current) window.clearTimeout(lrcScrollTimeout.current);
lrcScrollTimeout.current = window.setTimeout(() => {
if (lrcScrollRaf.current) cancelAnimationFrame(lrcScrollRaf.current);
lrcScrollRaf.current = requestAnimationFrame(scheduleScroll);
}, 16);
const wheelHandler = (e: WheelEvent) => {
const atTop = container.scrollTop === 0;
const atBottom = container.scrollTop + container.clientHeight >= container.scrollHeight;
if ((e.deltaY < 0 && atTop) || (e.deltaY > 0 && atBottom)) {
e.preventDefault();
} else {
e.stopPropagation();
} }
}, 0); };
}, [currentLyricIndex, lyrics]);
if (lrcWheelHandlerRef.current) {
container.removeEventListener('wheel', lrcWheelHandlerRef.current as EventListener);
}
lrcWheelHandlerRef.current = wheelHandler;
container.addEventListener('wheel', wheelHandler, { passive: false });
return () => {
if (lrcScrollTimeout.current) window.clearTimeout(lrcScrollTimeout.current);
if (lrcScrollRaf.current) cancelAnimationFrame(lrcScrollRaf.current);
container.removeEventListener('wheel', wheelHandler as EventListener);
};
}, [currentLyricIndex, lyrics.length]);
// Handle station changes: reset and start new stream // Handle station changes: reset and start new stream
useEffect(() => { useEffect(() => {
@@ -306,11 +360,20 @@ export default function Player({ user }: PlayerProps) {
const handleTrackData = useCallback((trackData) => { const handleTrackData = useCallback((trackData) => {
const requestStation = activeStationRef.current; const requestStation = activeStationRef.current;
// Guard: if trackData is null/undefined or empty object, ignore
if (!trackData || (typeof trackData === 'object' && Object.keys(trackData).length === 0)) {
return;
}
// Only set "No track playing" if we have clear indication of no track // Only set "No track playing" if we have clear indication of no track
// and not just missing song field (to avoid flickering during transitions) // AND we don't already have a valid track playing (to prevent race conditions)
if ((!trackData.song || trackData.song === 'N/A') && (!trackData.artist || trackData.artist === 'N/A')) { if ((!trackData.song || trackData.song === 'N/A') && (!trackData.artist || trackData.artist === 'N/A')) {
// Only clear if we don't have a current track UUID (meaning we never had valid data)
if (!currentTrackUuid.current) {
setTrackTitle('No track playing'); setTrackTitle('No track playing');
setLyrics([]); setLyrics([]);
}
// Otherwise ignore this empty data - keep showing current track
return; return;
} }
@@ -338,28 +401,66 @@ export default function Player({ user }: PlayerProps) {
}, []); }, []);
const initializeWebSocket = useCallback((station) => { const initializeWebSocket = useCallback((station) => {
// Clean up existing WebSocket // Clean up existing WebSocket and timers
if (wsReconnectTimer.current) {
clearTimeout(wsReconnectTimer.current);
wsReconnectTimer.current = null;
}
if (wsConnectionCheckTimer.current) {
clearInterval(wsConnectionCheckTimer.current);
wsConnectionCheckTimer.current = null;
}
if (wsInstance.current) { if (wsInstance.current) {
wsInstance.current.onclose = null; // Prevent triggering reconnection logic wsInstance.current.onclose = null; // Prevent triggering reconnection logic
wsInstance.current.onerror = null;
wsInstance.current.close(); wsInstance.current.close();
wsInstance.current = null; wsInstance.current = null;
} }
const connectWebSocket = (retryCount = 0) => { let retryCount = 0;
const baseDelay = 1000; // 1 second const baseDelay = 1000; // 1 second
const maxDelay = 30000; // 30 seconds const maxDelay = 30000; // 30 seconds
let isIntentionallyClosed = false;
const connectWebSocket = () => {
if (isIntentionallyClosed) return;
const wsUrl = `${API_URL.replace(/^https?:/, 'wss:')}/radio/ws/${station}`; const wsUrl = `${API_URL.replace(/^https?:/, 'wss:')}/radio/ws/${station}`;
const ws = new WebSocket(wsUrl); const ws = new WebSocket(wsUrl);
ws.onopen = function () { ws.onopen = function () {
// Reset retry count on successful connection // Reset retry count on successful connection
retryCount = 0;
wsLastMessageTime.current = Date.now();
// Start periodic connection check - if no messages received for 2 minutes,
// the connection is likely dead (server sends track updates regularly)
if (wsConnectionCheckTimer.current) {
clearInterval(wsConnectionCheckTimer.current);
}
wsConnectionCheckTimer.current = setInterval(() => {
const timeSinceLastMessage = Date.now() - wsLastMessageTime.current;
const isStale = timeSinceLastMessage > 120000; // 2 minutes without any message
// Check if connection appears dead
if (ws.readyState !== WebSocket.OPEN || isStale) {
console.warn('WebSocket connection appears stale, reconnecting...');
// Force close and let onclose handle reconnection
ws.close();
}
}, 30000); // Check every 30 seconds
}; };
ws.onmessage = function (event) { ws.onmessage = function (event) {
// Track last message time for connection health monitoring
wsLastMessageTime.current = Date.now();
try { try {
const data = JSON.parse(event.data); const data = JSON.parse(event.data);
// Ignore pong responses and other control messages
if (data.type === 'pong' || data.type === 'ping' || data.type === 'error' || data.type === 'status') return;
if (data.type === 'track_change') { if (data.type === 'track_change') {
// Handle track change // Handle track change
setLyrics([]); setLyrics([]);
@@ -370,24 +471,35 @@ export default function Player({ user }: PlayerProps) {
const parsedLyrics = parseLrcString(data.data); const parsedLyrics = parseLrcString(data.data);
setLyrics(parsedLyrics); setLyrics(parsedLyrics);
setCurrentLyricIndex(0); setCurrentLyricIndex(0);
} else { } else if (data.type === 'now_playing' || data.type === 'initial') {
// Handle initial now playing data // Explicit now playing message
handleTrackData(data.data || data);
} else if (!data.type && (data.song || data.artist || data.uuid)) {
// Untyped message with track data fields - treat as now playing
handleTrackData(data); handleTrackData(data);
} }
// Ignore any other message types that don't contain track data
} catch (error) { } catch (error) {
console.error('Error parsing WebSocket message:', error); console.error('Error parsing WebSocket message:', error);
} }
}; };
ws.onclose = function (event) { ws.onclose = function (event) {
// Don't retry if it was a clean close (code 1000) // Clear connection check timer
if (event.code === 1000) return; if (wsConnectionCheckTimer.current) {
clearInterval(wsConnectionCheckTimer.current);
wsConnectionCheckTimer.current = null;
}
// Attempt reconnection with exponential backoff // Always attempt reconnection unless intentionally closed
if (isIntentionallyClosed) return;
// Exponential backoff for reconnection
const delay = Math.min(baseDelay * Math.pow(2, retryCount), maxDelay); const delay = Math.min(baseDelay * Math.pow(2, retryCount), maxDelay);
retryCount++;
setTimeout(() => { wsReconnectTimer.current = setTimeout(() => {
connectWebSocket(retryCount + 1); connectWebSocket();
}, delay); }, delay);
}; };
@@ -400,6 +512,25 @@ export default function Player({ user }: PlayerProps) {
}; };
connectWebSocket(); connectWebSocket();
// Return cleanup function
return () => {
isIntentionallyClosed = true;
if (wsReconnectTimer.current) {
clearTimeout(wsReconnectTimer.current);
wsReconnectTimer.current = null;
}
if (wsConnectionCheckTimer.current) {
clearInterval(wsConnectionCheckTimer.current);
wsConnectionCheckTimer.current = null;
}
if (wsInstance.current) {
wsInstance.current.onclose = null;
wsInstance.current.onerror = null;
wsInstance.current.close();
wsInstance.current = null;
}
};
}, [handleTrackData, parseLrcString]); }, [handleTrackData, parseLrcString]);
const setTrackMetadata = useCallback((trackData, requestStation) => { const setTrackMetadata = useCallback((trackData, requestStation) => {
@@ -422,34 +553,43 @@ export default function Player({ user }: PlayerProps) {
// Ensure the ref points to the current activeStation for in-flight guards // Ensure the ref points to the current activeStation for in-flight guards
activeStationRef.current = activeStation; activeStationRef.current = activeStation;
// Clean up the existing WebSocket connection before initializing a new one // Initialize WebSocket connection for metadata
const cleanupWebSocket = async () => { const cleanupWs = initializeWebSocket(activeStation);
if (wsInstance.current) {
wsInstance.current.onclose = null; // Prevent triggering reconnection logic // Handle visibility change - reconnect when page becomes visible
wsInstance.current.close(); const handleVisibilityChange = () => {
wsInstance.current = null; if (document.visibilityState === 'visible') {
// Check if WebSocket is not connected or not open
if (!wsInstance.current || wsInstance.current.readyState !== WebSocket.OPEN) {
// Reinitialize WebSocket connection
if (cleanupWs) cleanupWs();
initializeWebSocket(activeStation);
}
} }
}; };
cleanupWebSocket().then(() => { document.addEventListener('visibilitychange', handleVisibilityChange);
// Initialize WebSocket connection for metadata
initializeWebSocket(activeStation);
});
return () => { return () => {
// Clean up WebSocket on station change or component unmount document.removeEventListener('visibilitychange', handleVisibilityChange);
if (wsInstance.current) { if (cleanupWs) cleanupWs();
wsInstance.current.onclose = null; // Prevent triggering reconnection logic
wsInstance.current.close();
wsInstance.current = null;
}
}; };
}, [activeStation, initializeWebSocket]); }, [activeStation, initializeWebSocket]);
// Cleanup WebSocket on component unmount // Cleanup WebSocket on component unmount
useEffect(() => { useEffect(() => {
return () => { return () => {
if (wsReconnectTimer.current) {
clearTimeout(wsReconnectTimer.current);
wsReconnectTimer.current = null;
}
if (wsConnectionCheckTimer.current) {
clearInterval(wsConnectionCheckTimer.current);
wsConnectionCheckTimer.current = null;
}
if (wsInstance.current) { if (wsInstance.current) {
wsInstance.current.onclose = null;
wsInstance.current.onerror = null;
wsInstance.current.close(); wsInstance.current.close();
wsInstance.current = null; wsInstance.current = null;
} }
@@ -621,7 +761,7 @@ export default function Player({ user }: PlayerProps) {
const [queueSearch, setQueueSearch] = useState(""); const [queueSearch, setQueueSearch] = useState("");
const fetchQueue = async (page = queuePage, rows = queueRows, search = queueSearch) => { const fetchQueue = async (page = queuePage, rows = queueRows, search = queueSearch) => {
const start = page * rows; const start = page * rows;
console.log("Fetching queue for station (ref):", activeStationRef.current); // console.log("Fetching queue for station (ref):", activeStationRef.current);
try { try {
const response = await authFetch(`${API_URL}/radio/get_queue`, { const response = await authFetch(`${API_URL}/radio/get_queue`, {
method: "POST", method: "POST",
@@ -647,13 +787,13 @@ export default function Player({ user }: PlayerProps) {
useEffect(() => { useEffect(() => {
if (isQueueVisible) { if (isQueueVisible) {
console.log("Fetching queue for station:", activeStation); // console.log("Fetching queue for station:", activeStation);
fetchQueue(queuePage, queueRows, queueSearch); fetchQueue(queuePage, queueRows, queueSearch);
} }
}, [isQueueVisible, queuePage, queueRows, queueSearch, activeStation]); }, [isQueueVisible, queuePage, queueRows, queueSearch, activeStation]);
useEffect(() => { useEffect(() => {
console.log("Active station changed to:", activeStation); // console.log("Active station changed to:", activeStation);
if (isQueueVisible) { if (isQueueVisible) {
fetchQueue(queuePage, queueRows, queueSearch); fetchQueue(queuePage, queueRows, queueSearch);
} }
@@ -661,7 +801,7 @@ export default function Player({ user }: PlayerProps) {
useEffect(() => { useEffect(() => {
if (isQueueVisible) { if (isQueueVisible) {
console.log("Track changed, refreshing queue for station:", activeStation); // console.log("Track changed, refreshing queue for station:", activeStation);
fetchQueue(queuePage, queueRows, queueSearch); fetchQueue(queuePage, queueRows, queueSearch);
} }
}, [currentTrackUuid]); }, [currentTrackUuid]);
@@ -746,10 +886,42 @@ export default function Player({ user }: PlayerProps) {
></div> ></div>
</div> </div>
<div className={`lrc-text mt-4 p-4 rounded-lg bg-neutral-100 dark:bg-neutral-800 ${lyrics.length === 0 ? "empty" : ""}`}> <div
ref={lrcContainerRef}
className={`lrc-text mt-4 p-4 rounded-lg bg-neutral-100 dark:bg-neutral-800 ${lyrics.length === 0 ? "empty" : ""}`}
tabIndex={lyrics.length > 0 ? 0 : -1}
aria-label="Lyrics"
onKeyDown={(e) => {
if (!lrcContainerRef.current || lyrics.length === 0) return;
const container = lrcContainerRef.current;
const step = 24;
switch (e.key) {
case 'ArrowDown':
container.scrollBy({ top: step, behavior: 'smooth' });
e.preventDefault();
break;
case 'ArrowUp':
container.scrollBy({ top: -step, behavior: 'smooth' });
e.preventDefault();
break;
case 'Home':
container.scrollTo({ top: 0, behavior: 'smooth' });
e.preventDefault();
break;
case 'End':
container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
e.preventDefault();
break;
}
}}
>
{lyrics.length === 0 && (
<p className="lrc-line text-sm text-neutral-400 dark:text-neutral-500">No lyrics available.</p>
)}
{lyrics.map((lyricObj, index) => ( {lyrics.map((lyricObj, index) => (
<p <p
key={index} key={index}
ref={index === currentLyricIndex ? (lrcActiveRef as React.RefObject<HTMLParagraphElement>) : undefined}
className={`lrc-line text-sm ${index === currentLyricIndex ? "active font-bold" : ""}`} className={`lrc-line text-sm ${index === currentLyricIndex ? "active font-bold" : ""}`}
> >
{lyricObj.line} {lyricObj.line}
@@ -830,14 +1002,27 @@ export default function Player({ user }: PlayerProps) {
<div className="music-control mt-4 flex justify-center"> <div className="music-control mt-4 flex justify-center">
<div <div
className="music-control__play" className="music-control__play"
onClick={() => { onClick={async () => {
const audio = audioElement.current; const audio = audioElement.current;
if (!audio) return; if (!audio) return;
if (isPlaying) { if (isPlaying) {
audio.pause(); audio.pause();
setIsPlaying(false); setIsPlaying(false);
} else { } else {
audio.play().then(() => setIsPlaying(true)); // If stream is not ready, reinitialize it
if (!isStreamReady || !audio.src || audio.error) {
initializeStream(activeStation);
return;
}
try {
await audio.play();
setIsPlaying(true);
} catch (err) {
console.warn('Playback failed, reinitializing stream:', err);
// Reinitialize stream on playback failure
initializeStream(activeStation);
}
} }
}} }}
role="button" role="button"
@@ -885,7 +1070,7 @@ export default function Player({ user }: PlayerProps) {
fetchQueue(e.page ?? 0, queueRows, queueSearch); fetchQueue(e.page ?? 0, queueRows, queueSearch);
}} }}
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport" paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport"
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries" currentPageReportTemplate="Showing {first} to {last} of {totalRecords} tracks"
paginatorClassName="queue-paginator !bg-neutral-50 dark:!bg-neutral-800 !text-neutral-900 dark:!text-neutral-100 !border-neutral-200 dark:!border-neutral-700" paginatorClassName="queue-paginator !bg-neutral-50 dark:!bg-neutral-800 !text-neutral-900 dark:!text-neutral-100 !border-neutral-200 dark:!border-neutral-700"
className="p-datatable-gridlines rounded-lg shadow-md border-t border-neutral-300 dark:border-neutral-700" className="p-datatable-gridlines rounded-lg shadow-md border-t border-neutral-300 dark:border-neutral-700"
style={{ minHeight: 'auto', height: 'auto', tableLayout: 'fixed', width: '100%' }} style={{ minHeight: 'auto', height: 'auto', tableLayout: 'fixed', width: '100%' }}
@@ -905,7 +1090,7 @@ export default function Player({ user }: PlayerProps) {
sortable sortable
headerClassName="bg-neutral-100 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 font-bold font-sans" headerClassName="bg-neutral-100 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 font-bold font-sans"
style={{ width: '300px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} style={{ width: '300px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
body={(rowData) => <span title={rowData.artistsong} style={{ display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '300px' }}>{rowData.artistsong}</span>} body={(rowData) => <span title={`${rowData.artist} - ${rowData.song}`} style={{ display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '300px' }}>{rowData.artist} - {rowData.song}</span>}
></Column> ></Column>
<Column <Column
field="album" field="album"

View File

@@ -1,19 +1,19 @@
import React from "react"; import React from "react";
import Alert from "@mui/joy/Alert";
import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";
export default function RadioBanner(): React.ReactElement { export default function RadioBanner(): React.ReactElement {
return ( return (
<div> <div className="radio-banner text-center mb-8">
<h2 style={{ textAlign: 'center', marginBottom: '1rem' }}>Radio</h2> <h2 className="text-[#333333] dark:text-[#D4D4D4] text-2xl font-bold mb-4">Radio</h2>
<Alert <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mx-auto max-w-md">
variant="soft" <div className="flex items-center">
color="danger" <svg className="w-6 h-6 text-yellow-600 dark:text-yellow-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
sx={{ fontSize: "1.0rem", textAlign: "center", mt: 4, mb: 4, px: 3, py: 2 }} <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
startDecorator={<ErrorOutlineIcon fontSize="large" />} </svg>
> <p className="text-yellow-800 dark:text-yellow-200 font-medium">
Maintenance in progress. Please check back soon! Maintenance in progress. Please check back soon!
</Alert> </p>
</div>
</div>
</div> </div>
); );
} }

View File

@@ -24,6 +24,7 @@ export default function BreadcrumbNav({ currentPage }: BreadcrumbNavProps): Reac
<React.Fragment key={key}> <React.Fragment key={key}>
<a <a
href={href} href={href}
data-astro-reload
className={`px-3 py-1.5 rounded-full transition-colors ${isActive className={`px-3 py-1.5 rounded-full transition-colors ${isActive
? "bg-neutral-200 dark:bg-neutral-700 font-semibold text-neutral-900 dark:text-white" ? "bg-neutral-200 dark:bg-neutral-700 font-semibold text-neutral-900 dark:text-white"
: "text-neutral-500 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800" : "text-neutral-500 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800"

File diff suppressed because it is too large Load Diff

View File

@@ -100,6 +100,7 @@ export default function MediaRequestForm() {
const albumHeaderRefs = useRef<Record<string | number, HTMLElement | null>>({}); const albumHeaderRefs = useRef<Record<string | number, HTMLElement | null>>({});
const suppressHashRef = useRef(false); const suppressHashRef = useRef(false);
const lastUrlRef = useRef(""); const lastUrlRef = useRef("");
const playPauseClickRef = useRef(false);
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); // Helper for delays const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); // Helper for delays
const sanitizeFilename = (text: string) => (text || "").replace(/[\\/:*?"<>|]/g, "_") || "track"; const sanitizeFilename = (text: string) => (text || "").replace(/[\\/:*?"<>|]/g, "_") || "track";
@@ -558,31 +559,42 @@ export default function MediaRequestForm() {
}; };
const handleTrackPlayPause = async (track: Track, albumId: string | number | null = null, albumIndex: number | null = null) => { const handleTrackPlayPause = async (track: Track, albumId: string | number | null = null, albumIndex: number | null = null) => {
// Prevent double-clicks / rapid clicks
if (playPauseClickRef.current) return;
playPauseClickRef.current = true;
const audio = audioRef.current; const audio = audioRef.current;
if (!audio) return; if (!audio) {
playPauseClickRef.current = false;
return;
}
if (typeof albumIndex === "number") { if (typeof albumIndex === "number") {
ensureAlbumExpanded(albumIndex); ensureAlbumExpanded(albumIndex);
} }
try {
if (currentTrackId === track.id) { if (currentTrackId === track.id) {
if (audio.paused) { if (audio.paused) {
setIsAudioPlaying(true); setIsAudioPlaying(true);
try {
await audio.play(); await audio.play();
} catch (error) {
setIsAudioPlaying(false);
console.error(error);
toast.error("Unable to resume playback.");
}
} else { } else {
setIsAudioPlaying(false); setIsAudioPlaying(false);
audio.pause(); audio.pause();
} }
return; } else {
}
await playTrack(track, { fromQueue: false }); await playTrack(track, { fromQueue: false });
}
} catch (error) {
setIsAudioPlaying(false);
console.error(error);
toast.error("Unable to play/pause track.");
} finally {
// Small delay before allowing next click to prevent rapid clicks
setTimeout(() => {
playPauseClickRef.current = false;
}, 150);
}
}; };
const toggleAlbumShuffle = (albumId) => { const toggleAlbumShuffle = (albumId) => {
@@ -993,7 +1005,14 @@ export default function MediaRequestForm() {
} }
const data = await response.json(); const data = await response.json();
toast.success(`Request submitted! (${allSelectedIds.length} tracks)`); const toastId = 'trip-request-submitted';
toast.success(`Request submitted! (${allSelectedIds.length} tracks)`, {
toastId,
autoClose: 3000,
onClose: () => {
if (typeof window !== 'undefined') window.location.href = '/TRip/requests';
}
});
} catch (err) { } catch (err) {
console.error(err); console.error(err);
toast.error("Failed to submit request."); toast.error("Failed to submit request.");
@@ -1297,22 +1316,13 @@ export default function MediaRequestForm() {
e.stopPropagation(); e.stopPropagation();
handleTrackPlayPause(track, id, albumIndex); handleTrackPlayPause(track, id, albumIndex);
}} }}
onPointerDown={(e) => { style={{ touchAction: "manipulation", WebkitTapHighlightColor: "transparent" }}
try { className={`flex items-center justify-center w-8 h-8 rounded-full border text-sm transition-colors disabled:opacity-60 disabled:cursor-not-allowed select-none ${isCurrentTrack && isAudioPlaying
if (e?.pointerType === "touch" || e.type === "touchstart") {
e.preventDefault();
}
} catch (err) {
// ignore
}
}}
style={{ touchAction: "manipulation" }}
className={`flex items-center justify-center w-8 h-8 rounded-full border text-sm transition-colors disabled:opacity-60 disabled:cursor-not-allowed ${isCurrentTrack && isAudioPlaying
? "border-green-600 text-green-600" ? "border-green-600 text-green-600"
: "border-neutral-400 text-neutral-600 hover:text-blue-600 hover:border-blue-600"}`} : "border-neutral-400 text-neutral-600 hover:text-blue-600 hover:border-blue-600"}`}
aria-label={`${isCurrentTrack && isAudioPlaying ? "Pause" : "Play"} ${track.title}`} aria-label={`${isCurrentTrack && isAudioPlaying ? "Pause" : "Play"} ${track.title}`}
aria-pressed={isCurrentTrack && isAudioPlaying} aria-pressed={isCurrentTrack && isAudioPlaying}
disabled={audioLoadingTrackId === track.id} disabled={audioLoadingTrackId === track.id || playPauseClickRef.current}
> >
{audioLoadingTrackId === track.id ? ( {audioLoadingTrackId === track.id ? (
<InlineSpinner sizeClass="h-4 w-4" /> <InlineSpinner sizeClass="h-4 w-4" />

View File

@@ -279,6 +279,7 @@
display: flex; display: flex;
align-items: center; align-items: center;
width: 100%; width: 100%;
gap: 0.5rem; /* space between track and percent */
} }
@@ -292,6 +293,7 @@
overflow: hidden; /* must clip when scaled */ overflow: hidden; /* must clip when scaled */
margin: 0 !important; margin: 0 !important;
padding: 0 !important; padding: 0 !important;
margin-right: 0; /* ensure neighbor percent isn't pushed inside */
} }
.rm-progress-track-lg { .rm-progress-track-lg {
@@ -308,13 +310,41 @@
transform: scaleX(var(--rm-progress, 0)); /* use custom property (0-1 range) */ transform: scaleX(var(--rm-progress, 0)); /* use custom property (0-1 range) */
border-top-left-radius: 999px; border-top-left-radius: 999px;
border-bottom-left-radius: 999px; border-bottom-left-radius: 999px;
transition: transform 0.24s cubic-bezier(0.4,0,0.2,1), border-radius 0.24s; transition: transform .5s cubic-bezier(.25,.8,.25,1), background-color .28s ease, border-radius .28s;
margin: 0 !important; margin: 0 !important;
padding: 0 !important; padding: 0 !important;
right: 0; right: 0;
min-width: 0; min-width: 0;
will-change: transform; will-change: transform, background-color;
box-sizing: border-box; box-sizing: border-box;
z-index: 1; /* ensure fill sits beneath the percent text */
}
/* Ensure percent label appears above the fill even when inside the track */
.rm-progress-text {
position: relative;
z-index: 2;
flex: none; /* don't stretch */
margin-left: 0.5rem;
white-space: nowrap;
overflow: visible;
}
/* Finalizing pulse for near-100% jobs */
.rm-finalizing {
animation: rm-finalize-pulse 1.6s ease-in-out infinite;
}
@keyframes rm-finalize-pulse {
0% {
box-shadow: 0 0 0 0 rgba(255, 193, 7, 0);
}
50% {
box-shadow: 0 0 12px 4px rgba(255, 193, 7, 0.10);
}
100% {
box-shadow: 0 0 0 0 rgba(255, 193, 7, 0);
}
} }
/* Fix for native audio progress bar (range input) */ /* Fix for native audio progress bar (range input) */
@@ -404,16 +434,47 @@
.rm-progress-text { .rm-progress-text {
font-size: 0.75rem; font-size: 0.75rem;
font-weight: 600; font-weight: 600;
color: inherit;
}
/* Ensure progress styles apply when rendered within a PrimeReact Dialog (portal) */ /* Ensure progress styles apply when rendered within a PrimeReact Dialog (portal) */
.p-dialog .rm-progress-container{display:flex;align-items:center;width:100%} .p-dialog .rm-progress-container {
.p-dialog .rm-progress-track{position:relative;flex:1 1 0%;min-width:0;height:6px;background-color:#80808033;border-radius:999px;overflow:hidden;margin:0!important;padding:0!important} display: flex;
.p-dialog .rm-progress-track-lg{height:10px} align-items: center;
.p-dialog .rm-progress-fill{position:absolute;left:0;top:0;height:100%;width:100%!important;transform-origin:left center;transform:scaleX(var(--rm-progress, 0));border-top-left-radius:999px;border-bottom-left-radius:999px;transition:transform .24s cubic-bezier(.4,0,.2,1),border-radius .24s;margin:0!important;padding:0!important;right:0;min-width:0;will-change:transform;box-sizing:border-box} width: 100%;
.p-dialog .rm-progress-text{font-size:.75rem;font-weight:600;min-width:2.5rem;text-align:right}
min-width: 2.5rem;
text-align: right;
} }
.p-dialog .rm-progress-track {
position: relative;
flex: 1 1 0%;
min-width: 0;
height: 6px;
background-color: #80808033;
border-radius: 999px;
overflow: hidden;
margin: 0 !important;
padding: 0 !important;
}
.p-dialog .rm-progress-track-lg { height: 10px; }
.p-dialog .rm-progress-fill {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100% !important;
transform-origin: left center;
transform: scaleX(var(--rm-progress, 0));
border-top-left-radius: 999px;
border-bottom-left-radius: 999px;
transition: transform .5s cubic-bezier(.25,.8,.25,1), background-color .28s ease, border-radius .28s;
margin: 0 !important;
padding: 0 !important;
right: 0;
min-width: 0;
will-change: transform, background-color;
box-sizing: border-box;
}
.p-dialog .rm-progress-text { font-size: .75rem; font-weight: 600; color: #e5e7eb !important; margin-left: 0.5rem; white-space: nowrap; }
/* Container Styles */ /* Container Styles */
.trip-management-container { .trip-management-container {
@@ -532,6 +593,25 @@
font-size: 0.85rem !important; font-size: 0.85rem !important;
} }
/* Track list scrollbar and status pill adjustments */
.rm-track-list {
/* Give room for overlay scrollbars so status pills don't overlap */
padding-inline-end: 1.25rem; /* ~20px */
}
.rm-track-status {
/* Ensure the status pill has extra right padding and sits visually clear of the scrollbar */
padding-right: 0.75rem !important;
margin-right: 0.25rem !important;
border-radius: 999px !important;
}
/* Slightly reduce spacing on very small screens */
@media (max-width: 480px) {
.rm-track-list { padding-inline-end: 0.75rem; }
.rm-track-status { padding-right: 0.5rem !important; }
}
/* Album header info stacks */ /* Album header info stacks */
.album-header-info { .album-header-info {
flex-direction: column; flex-direction: column;

View File

@@ -11,6 +11,15 @@ import BreadcrumbNav from "./BreadcrumbNav";
import { API_URL } from "@/config"; import { API_URL } from "@/config";
import "./RequestManagement.css"; import "./RequestManagement.css";
interface TrackInfo {
title?: string;
artist?: string;
status?: string;
error?: string;
filename?: string;
[key: string]: unknown;
}
interface RequestJob { interface RequestJob {
id: string | number; id: string | number;
target: string; target: string;
@@ -22,11 +31,12 @@ interface RequestJob {
tarball?: string; tarball?: string;
created_at?: string; created_at?: string;
updated_at?: string; updated_at?: string;
track_list?: TrackInfo[];
[key: string]: unknown; [key: string]: unknown;
} }
const STATUS_OPTIONS = ["Queued", "Started", "Compressing", "Finished", "Failed"]; const STATUS_OPTIONS = ["Queued", "Started", "Compressing", "Finished", "Failed"];
const TAR_BASE_URL = "https://codey.lol/m/m2"; // configurable prefix const TAR_BASE_URL = "https://kr.codey.lol"; // configurable prefix
export default function RequestManagement() { export default function RequestManagement() {
const [requests, setRequests] = useState<RequestJob[]>([]); const [requests, setRequests] = useState<RequestJob[]>([]);
@@ -38,6 +48,8 @@ export default function RequestManagement() {
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null); const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);
const pollingDetailRef = useRef<ReturnType<typeof setInterval> | null>(null); const pollingDetailRef = useRef<ReturnType<typeof setInterval> | null>(null);
// Track finalizing job polls to actively refresh job status when progress hits 100% but status hasn't updated yet
const finalizingPollsRef = useRef<Record<string | number, ReturnType<typeof setInterval> | null>>({});
const resolveTarballPath = (job: RequestJob) => job.tarball; const resolveTarballPath = (job: RequestJob) => job.tarball;
@@ -47,6 +59,13 @@ export default function RequestManagement() {
const filename = absPath.split("/").pop(); // get "SOMETHING.tar.gz" const filename = absPath.split("/").pop(); // get "SOMETHING.tar.gz"
// If the backend already stores a fully qualified URL, return as-is // If the backend already stores a fully qualified URL, return as-is
if (/^https?:\/\//i.test(absPath)) return absPath; if (/^https?:\/\//i.test(absPath)) return absPath;
// Check if path is /storage/music/TRIP
if (absPath.includes("/storage/music/TRIP/")) {
return `https://music.boatson.boats/TRIP/${filename}`;
}
// Otherwise, assume /storage/music2/completed/{quality} format
return `${TAR_BASE_URL}/${quality}/${filename}`; return `${TAR_BASE_URL}/${quality}/${filename}`;
}; };
@@ -182,30 +201,105 @@ export default function RequestManagement() {
const computePct = (p: unknown) => { const computePct = (p: unknown) => {
if (p === null || p === undefined || p === "") return 0; if (p === null || p === undefined || p === "") return 0;
// Handle "X / Y" format (e.g., "9 / 545") - note spaces around slash from backend
if (typeof p === 'string' && p.includes('/')) {
const parts = p.split('/').map(s => s.trim());
const current = parseFloat(parts[0]);
const total = parseFloat(parts[1]);
if (Number.isFinite(current) && Number.isFinite(total) && total > 0) {
return Math.min(100, Math.max(0, Math.round((current / total) * 100)));
}
return 0;
}
const num = Number(p); const num = Number(p);
if (!Number.isFinite(num)) return 0; if (!Number.isFinite(num)) return 0;
const normalized = num > 1 ? num : num * 100; // Backend sends progress as 0-100 directly, so just clamp it
return Math.min(100, Math.max(0, Math.round(normalized))); return Math.min(100, Math.max(0, Math.round(num)));
}; };
// Visual pct used for display/fill. Prevent briefly showing 100% unless status is Finished
const displayPct = (p: unknown, status?: string) => {
const pct = computePct(p);
const statusNorm = String(status || "").trim();
// If the backend reports 100% but the job hasn't reached 'Finished', show 99 to avoid flash
if (pct >= 100 && statusNorm.toLowerCase() !== 'finished') return 99;
return pct;
};
const isFinalizingJob = (job: RequestJob | { progress?: unknown; status?: string }) => {
const pct = computePct(job.progress);
const statusNorm = String(job.status || "").trim().toLowerCase();
// Only treat as finalizing when status is explicitly "Compressing"
// This is set by the backend only when progress == 100 and tarball isn't ready yet
return statusNorm === 'compressing';
};
const startFinalizingPoll = (jobId: string | number) => {
if (finalizingPollsRef.current[jobId]) return; // already polling
let attempts = 0;
const iv = setInterval(async () => {
attempts += 1;
try {
const updated = await fetchJobDetail(jobId);
if (updated) {
// Merge the updated job into requests list so UI refreshes
setRequests((prev) => prev.map((r) => (r.id === updated.id ? updated : r)));
// If it's no longer finalizing, stop this poll
if (!isFinalizingJob(updated)) {
if (finalizingPollsRef.current[jobId]) {
clearInterval(finalizingPollsRef.current[jobId] as ReturnType<typeof setInterval>);
finalizingPollsRef.current[jobId] = null;
}
}
}
} catch (err) {
// ignore individual errors; we'll retry a few times
}
// safety cap: stop after ~20 attempts (~30s)
if (attempts >= 20) {
if (finalizingPollsRef.current[jobId]) {
clearInterval(finalizingPollsRef.current[jobId] as ReturnType<typeof setInterval>);
finalizingPollsRef.current[jobId] = null;
}
}
}, 1500);
finalizingPollsRef.current[jobId] = iv;
};
// stop all finalizing polls on unmount
useEffect(() => {
return () => {
Object.values(finalizingPollsRef.current).forEach((iv) => {
if (iv) clearInterval(iv);
});
};
}, []);
const progressBarTemplate = (rowData: RequestJob) => { const progressBarTemplate = (rowData: RequestJob) => {
const p = rowData.progress; const p = rowData.progress;
if (p === null || p === undefined || p === "") return "—"; if (p === null || p === undefined || p === "") return "—";
const pct = computePct(p); const pctRaw = computePct(p);
const isFinalizing = isFinalizingJob(rowData);
const pct = isFinalizing ? 99 : pctRaw;
const getProgressColor = () => { const getProgressColor = () => {
if (rowData.status === "Failed") return "bg-red-500"; if (rowData.status === "Failed") return "bg-red-500";
if (rowData.status === "Finished") return "bg-green-500"; if (rowData.status === "Finished") return "bg-green-500";
if (pct < 30) return "bg-blue-400"; if (isFinalizing) return "bg-yellow-500"; // finalizing indicator
if (pct < 70) return "bg-blue-500"; if (pctRaw < 30) return "bg-blue-400";
if (pctRaw < 70) return "bg-blue-500";
return "bg-blue-600"; return "bg-blue-600";
}; };
// If this job appears to be finalizing, ensure a poll is active to get the real status
if (isFinalizing) startFinalizingPoll(rowData.id);
return ( return (
<div className="rm-progress-container"> <div className="rm-progress-container">
<div className="rm-progress-track" style={{ flex: 1, minWidth: 0 }}> <div className="rm-progress-track" style={{ flex: 1, minWidth: 0 }}>
<div <div
className={`rm-progress-fill ${getProgressColor()}`} className={`rm-progress-fill ${getProgressColor()} ${isFinalizing ? 'rm-finalizing' : ''}`}
style={{ style={{
// CSS custom property for progress animation // CSS custom property for progress animation
['--rm-progress' as string]: (pct / 100).toString(), ['--rm-progress' as string]: (pct / 100).toString(),
@@ -213,12 +307,12 @@ export default function RequestManagement() {
borderBottomRightRadius: pct === 100 ? '999px' : 0 borderBottomRightRadius: pct === 100 ? '999px' : 0
}} }}
data-pct={pct} data-pct={pct}
aria-valuenow={pct} aria-valuenow={pctRaw}
aria-valuemin={0} aria-valuemin={0}
aria-valuemax={100} aria-valuemax={100}
/> />
</div> </div>
<span className="rm-progress-text" style={{ marginLeft: 8, flex: 'none' }}>{pct}%</span> <span className="rm-progress-text" style={{ marginLeft: 8, flex: 'none' }}>{pct}%{isFinalizing ? ' (finalizing...)' : ''}</span>
</div> </div>
); );
}; };
@@ -411,26 +505,34 @@ export default function RequestManagement() {
<div className="rm-progress-container mt-2"> <div className="rm-progress-container mt-2">
<div className="rm-progress-track rm-progress-track-lg"> <div className="rm-progress-track rm-progress-track-lg">
{(() => { {(() => {
const pctDialog = computePct(selectedRequest.progress); const pctRawDialog = computePct(selectedRequest.progress);
const isFinalizingDialog = isFinalizingJob(selectedRequest);
const pctDialog = isFinalizingDialog ? 99 : pctRawDialog;
const status = selectedRequest.status; const status = selectedRequest.status;
const fillColor = status === "Failed" ? "bg-red-500" : status === "Finished" ? "bg-green-500" : "bg-blue-500"; const fillColor = status === "Failed" ? "bg-red-500" : status === "Finished" ? "bg-green-500" : isFinalizingDialog ? "bg-yellow-500" : "bg-blue-500";
// Ensure we poll for finalizing jobs to get the real status update
if (isFinalizingDialog) startFinalizingPoll(selectedRequest.id);
return ( return (
<>
<div <div
className={`rm-progress-fill ${fillColor}`} className={`rm-progress-fill ${fillColor} ${isFinalizingDialog ? 'rm-finalizing' : ''}`}
style={{ style={{
['--rm-progress' as string]: (pctDialog / 100).toString(), ['--rm-progress' as string]: (pctDialog / 100).toString(),
borderTopRightRadius: pctDialog >= 100 ? '999px' : 0, borderTopRightRadius: pctDialog >= 100 ? '999px' : 0,
borderBottomRightRadius: pctDialog >= 100 ? '999px' : 0 borderBottomRightRadius: pctDialog >= 100 ? '999px' : 0
}} }}
data-pct={pctDialog} data-pct={pctDialog}
aria-valuenow={pctDialog} aria-valuenow={pctRawDialog}
aria-valuemin={0} aria-valuemin={0}
aria-valuemax={100} aria-valuemax={100}
/> />
</>
); );
})()} })()}
</div> </div>
<span className="rm-progress-text">{formatProgress(selectedRequest.progress)}</span> <span className="rm-progress-text">{formatProgress(selectedRequest.progress)}{isFinalizingJob(selectedRequest) ? ' — finalizing' : ''}</span>
</div> </div>
</div> </div>
)} )}
@@ -462,6 +564,66 @@ export default function RequestManagement() {
) )
} }
{/* --- Track List Card --- */}
{selectedRequest.track_list && selectedRequest.track_list.length > 0 && (
<div className="p-3 bg-gray-100 dark:bg-neutral-800 rounded-md">
<p className="mb-2"><strong>Tracks ({selectedRequest.track_list.length}):</strong></p>
<div className="max-h-60 overflow-y-auto space-y-2" data-lenis-prevent>
{selectedRequest.track_list.map((track, idx) => {
const rawStatus = String(track.status || "pending");
const statusNorm = rawStatus.trim().toLowerCase();
const isError = statusNorm === "failed" || statusNorm === "error" || !!track.error;
const isSuccess = ["done", "success", "completed", "finished"].includes(statusNorm);
const isPending = ["pending", "queued"].includes(statusNorm);
const isDownloading = ["downloading", "in_progress", "started"].includes(statusNorm);
const statusBadgeClass = isError
? "bg-red-600 text-white"
: isSuccess
? "bg-green-600 text-white"
: isDownloading
? "bg-blue-600 text-white"
: isPending
? "bg-yellow-600 text-white"
: "bg-gray-500 text-white";
const trackTitle = track.title || track.filename || `Track ${idx + 1}`;
const trackArtist = track.artist;
return (
<div
key={idx}
className={`p-2 rounded border ${isError ? "border-red-500/50 bg-red-500/10" : "border-neutral-300 dark:border-neutral-600"}`}
>
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate" title={trackTitle}>
{trackTitle}
</p>
{trackArtist && (
<p className="text-xs text-neutral-500 dark:text-neutral-400 truncate" title={trackArtist}>
{trackArtist}
</p>
)}
</div>
<span className={`px-2 py-0.5 pr-3 mr-2 rounded text-xs font-semibold whitespace-nowrap ${statusBadgeClass} rm-track-status`} title={rawStatus}>
{rawStatus}
</span>
</div>
{track.error && (
<p className="mt-1 text-xs text-red-400 break-words">
<i className="pi pi-exclamation-triangle mr-1" />
{track.error}
</p>
)}
</div>
);
})}
</div>
</div>
)}
</div > </div >
) : ( ) : (
<p>Loading...</p> <p>Loading...</p>

View File

@@ -296,7 +296,7 @@ export default function ReqForm() {
/> />
{selectedItem && selectedTypeLabel && ( {selectedItem && selectedTypeLabel && (
<div className="text-xs font-medium uppercase text-neutral-500 dark:text-neutral-400 tracking-wide"> <div className="text-xs font-medium uppercase text-neutral-500 dark:text-neutral-400 tracking-wide">
Selected type: <span className="font-bold text-neutral-700 dark:text-neutral-200">{selectedTypeLabel}</span> Type: <span className="font-bold text-neutral-700 dark:text-neutral-200">{selectedTypeLabel}</span>
</div> </div>
)} )}
</div> </div>
@@ -334,18 +334,19 @@ export default function ReqForm() {
<div className="space-y-2"> <div className="space-y-2">
<label htmlFor="year" className="block text-sm font-medium text-neutral-700 dark:text-neutral-300"> <label htmlFor="year" className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Year <span className="text-neutral-400">(optional)</span> Year
</label> </label>
<InputText <InputText
id="year" id="year"
value={year} value={year}
onChange={(e) => setYear(e.target.value)} placeholder=""
placeholder="e.g. 2023" readOnly
className="w-full border border-neutral-200 dark:border-neutral-700 rounded-xl px-4 py-3 bg-white dark:bg-neutral-900/50 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:ring-blue-500/20 transition-all outline-none" disabled
className="w-full border border-neutral-200 dark:border-neutral-700 rounded-xl px-4 py-3 bg-neutral-100 dark:bg-neutral-800 text-neutral-500 dark:text-neutral-400 cursor-not-allowed transition-all outline-none"
/> />
</div> </div>
<div className="space-y-2"> {/* <div className="space-y-2">
<label htmlFor="requester" className="block text-sm font-medium text-neutral-700 dark:text-neutral-300"> <label htmlFor="requester" className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Your Name <span className="text-neutral-400">(optional)</span> Your Name <span className="text-neutral-400">(optional)</span>
</label> </label>
@@ -356,7 +357,7 @@ export default function ReqForm() {
placeholder="Who is requesting this?" placeholder="Who is requesting this?"
className="w-full border border-neutral-200 dark:border-neutral-700 rounded-xl px-4 py-3 bg-white dark:bg-neutral-900/50 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:ring-blue-500/20 transition-all outline-none" className="w-full border border-neutral-200 dark:border-neutral-700 rounded-xl px-4 py-3 bg-white dark:bg-neutral-900/50 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:ring-blue-500/20 transition-all outline-none"
/> />
</div> </div> */}
<div className="pt-4"> <div className="pt-4">
<Button <Button

View File

@@ -63,7 +63,7 @@ export const RADIO_API_URL: string = "https://radio-api.codey.lol";
export const socialLinks: Record<string, string> = { export const socialLinks: Record<string, string> = {
}; };
export const MAJOR_VERSION: string = "0.6" export const MAJOR_VERSION: string = "0.7"
export const RELEASE_FLAG: string | null = null; export const RELEASE_FLAG: string | null = null;
export const ENVIRONMENT: "Dev" | "Prod" = import.meta.env.DEV ? "Dev" : "Prod"; export const ENVIRONMENT: "Dev" | "Prod" = import.meta.env.DEV ? "Dev" : "Prod";

View File

@@ -22,9 +22,19 @@ const navItems = [
{ label: "Memes", href: "/memes" }, { label: "Memes", href: "/memes" },
{ label: "TRip", href: "/TRip", auth: true, icon: "pirate" }, { label: "TRip", href: "/TRip", auth: true, icon: "pirate" },
{ label: "Discord Logs", href: "/discord-logs", auth: true }, { label: "Discord Logs", href: "/discord-logs", auth: true },
{ label: "Lighting", href: "/lighting", auth: true }, { label: "Lighting", href: "/lighting", auth: true, adminOnly: true },
{ label: "Status", href: "https://status.boatson.boats", icon: "external" },
{ label: "Git", href: "https://kode.boatson.boats", icon: "external" }, { label: "Git", href: "https://kode.boatson.boats", icon: "external" },
{ label: "Glances", href: "https://_gl.codey.lol", auth: true, icon: "external",
adminOnly: true },
{ label: "PSQL", href: "https://_pg.codey.lol", auth: true, icon: "external",
adminOnly: true },
{ label: "qBitTorrent", href: "https://_qb.codey.lol", auth: true, icon: "external",
adminOnly: true },
{ label: "RQ", href: "https://_rq.codey.lol", auth: true, icon: "external",
adminOnly: true },
{ label: "RI", href: "https://_r0.codey.lol", auth: true, icon: "external",
adminOnly: true },
// { label: "Status", href: "https://status.boatson.boats", icon: "external" },
{ label: "Login", href: "/login", guestOnly: true }, { label: "Login", href: "/login", guestOnly: true },
...(isLoggedIn ? [{ label: "Logout", href: "#logout", onclick: "handleLogout()" }] : []), ...(isLoggedIn ? [{ label: "Logout", href: "#logout", onclick: "handleLogout()" }] : []),
]; ];
@@ -34,6 +44,10 @@ const visibleNavItems = navItems.filter((item) => {
return false; return false;
} }
if (item.adminOnly && !isAdmin) {
return false;
}
if (item.guestOnly && isLoggedIn) { if (item.guestOnly && isLoggedIn) {
return false; return false;
} }
@@ -155,7 +169,7 @@ const currentPath = Astro.url.pathname;
<!-- Mobile Navigation Menu --> <!-- Mobile Navigation Menu -->
<div <div
id="mobile-menu" id="mobile-menu"
class="mobile-menu-dropdown md:hidden" class="mobile-menu-dropdown xl:hidden"
> >
{isLoggedIn && userDisplayName && ( {isLoggedIn && userDisplayName && (
<div class:list={['nav-user-inline', 'nav-user-inline--mobile', isAdmin && 'nav-user-inline--admin']} title={`Logged in as ${userDisplayName}`}> <div class:list={['nav-user-inline', 'nav-user-inline--mobile', isAdmin && 'nav-user-inline--admin']} title={`Logged in as ${userDisplayName}`}>

View File

@@ -15,7 +15,7 @@ interface SubmitRequestBody {
title?: string; title?: string;
year?: string; year?: string;
type?: string; type?: string;
requester?: string; // requester?: string;
[key: string]: unknown; [key: string]: unknown;
} }
@@ -127,7 +127,7 @@ export async function POST({ request }: APIContext): Promise<Response> {
try { try {
// Use pre-parsed body data // Use pre-parsed body data
const extendedRequest = request as ExtendedRequest; const extendedRequest = request as ExtendedRequest;
const { title, year, type, requester } = extendedRequest.bodyData || {}; const { title, year, type } = extendedRequest.bodyData || {};
// Input validation // Input validation
if (!title || typeof title !== 'string' || !title.trim()) { if (!title || typeof title !== 'string' || !title.trim()) {
@@ -174,16 +174,16 @@ export async function POST({ request }: APIContext): Promise<Response> {
return response; return response;
} }
if (requester && (typeof requester !== 'string' || requester.length > 500)) { // if (requester && (typeof requester !== 'string' || requester.length > 500)) {
const response = new Response(JSON.stringify({ error: 'Requester name must be 500 characters or less if provided' }), { // const response = new Response(JSON.stringify({ error: 'Requester name must be 500 characters or less if provided' }), {
status: 400, // status: 400,
headers: { 'Content-Type': 'application/json' }, // headers: { 'Content-Type': 'application/json' },
}); // });
if (!hadCookie) { // if (!hadCookie) {
response.headers.set('Set-Cookie', createNonceCookie(cookieId)); // response.headers.set('Set-Cookie', createNonceCookie(cookieId));
} // }
return response; // return response;
} // }
// Fetch synopsis and IMDb ID from TMDB // Fetch synopsis and IMDb ID from TMDB
let synopsis = ''; let synopsis = '';
@@ -258,13 +258,13 @@ export async function POST({ request }: APIContext): Promise<Response> {
}); });
} }
if (requester && requester.trim()) { // if (requester && requester.trim()) {
fields.push({ // fields.push({
name: "Requested by", // name: "Requested by",
value: requester.trim(), // value: requester.trim(),
inline: false // inline: false
}); // });
} // }
interface DiscordEmbed { interface DiscordEmbed {
title: string; title: string;

View File

@@ -5,8 +5,56 @@ import Root from "@/components/AppLayout.jsx";
import { requireAuthHook } from '@/hooks/requireAuthHook'; import { requireAuthHook } from '@/hooks/requireAuthHook';
const user = await requireAuthHook(Astro); const user = await requireAuthHook(Astro);
const isLoggedIn = Boolean(user); const isLoggedIn = Boolean(user);
const accessDenied = Astro.locals.accessDenied || false; // Detect if returnUrl is external (nginx-protected vhost redirect)
const requiredRoles = Astro.locals.requiredRoles || []; // If logged-in user arrives with external returnUrl, nginx denied them - show access denied
const returnUrl = Astro.url.searchParams.get('returnUrl') || Astro.url.searchParams.get('redirect');
const trustedDomains = ['codey.lol', 'boatson.boats'];
let isExternalReturn = false;
let externalHostname = '';
if (returnUrl && !returnUrl.startsWith('/')) {
try {
const url = new URL(returnUrl);
if (url.protocol === 'https:') {
const isTrusted = trustedDomains.some(domain =>
url.hostname === domain || url.hostname.endsWith('.' + domain)
);
if (isTrusted) {
isExternalReturn = true;
externalHostname = url.hostname;
}
}
} catch {
// Invalid URL
}
}
// If logged in and redirected from an external nginx-protected resource,
// nginx denied access (user lacks role) - treat as access denied to prevent redirect loop
const accessDenied = Astro.locals.accessDenied || (isLoggedIn && isExternalReturn);
const requiredRoles = Astro.locals.requiredRoles || (isExternalReturn ? ['(external resource)'] : []);
// If user is authenticated and arrived with a returnUrl, redirect them there
// This handles the case where access_token expired but refresh_token was still valid
// BUT only for relative URLs - external URLs that sent us here mean access was denied
if (isLoggedIn && !accessDenied) {
if (returnUrl) {
// Validate the return URL for security
let isValidRedirect = false;
// Only allow relative paths for auto-redirect
// External URLs arriving here mean nginx denied access, so don't redirect back
if (returnUrl.startsWith('/') && !returnUrl.startsWith('//')) {
isValidRedirect = true;
}
if (isValidRedirect) {
return Astro.redirect(returnUrl, 302);
}
}
// No returnUrl or external URL (access denied case handled above) - redirect to home
return Astro.redirect('/', 302);
}
--- ---
<Base title="Login"> <Base title="Login">

View File

@@ -1,26 +1,27 @@
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import fs from 'fs'; import crypto from 'crypto';
import path from 'path'; import { API_URL } from '../config';
import os from 'os';
// JWT keys location - can be configured via environment variable // JWKS endpoint for fetching RSA public keys
// In production, prefer using a secret management service (Vault, AWS Secrets Manager, etc.) const JWKS_URL = `${API_URL}/auth/jwks`;
const secretFilePath = import.meta.env.JWT_KEYS_PATH || path.join(
os.homedir(),
'.config',
'api_jwt_keys.json'
);
// Warn if using default location in production // Cache for JWKS keys
if (!import.meta.env.JWT_KEYS_PATH && !import.meta.env.DEV) { interface JwkKey {
console.warn( kty: string;
'[SECURITY WARNING] JWT_KEYS_PATH not set. Using default location ~/.config/api_jwt_keys.json. ' + use?: string;
'Consider using a secret management service in production.' kid: string;
); alg?: string;
n: string;
e: string;
} }
interface JwtKeyFile { interface JwksResponse {
keys: Record<string, string>; keys: JwkKey[];
}
interface CachedKeys {
keys: Map<string, string>; // kid -> PEM public key
fetchedAt: number;
} }
export interface JwtPayload { export interface JwtPayload {
@@ -31,16 +32,98 @@ export interface JwtPayload {
[key: string]: unknown; [key: string]: unknown;
} }
// Load and parse keys JSON once at startup // Cache TTL: 5 minutes (keys are refreshed on cache miss or verification failure)
let keyFileData: JwtKeyFile; const CACHE_TTL_MS = 5 * 60 * 1000;
try {
keyFileData = JSON.parse(fs.readFileSync(secretFilePath, 'utf-8')); let cachedKeys: CachedKeys | null = null;
} catch (err) {
console.error(`[CRITICAL] Failed to load JWT keys from ${secretFilePath}:`, (err as Error).message); /**
throw new Error('JWT keys file not found or invalid. Set JWT_KEYS_PATH environment variable.'); * Convert a JWK RSA public key to PEM format
*/
function jwkToPem(jwk: JwkKey): string {
if (jwk.kty !== 'RSA') {
throw new Error(`Unsupported key type: ${jwk.kty}`);
}
// Decode base64url-encoded modulus and exponent
const n = Buffer.from(jwk.n, 'base64url');
const e = Buffer.from(jwk.e, 'base64url');
// Build the RSA public key using Node's crypto
const publicKey = crypto.createPublicKey({
key: {
kty: 'RSA',
n: jwk.n,
e: jwk.e,
},
format: 'jwk',
});
return publicKey.export({ type: 'spki', format: 'pem' }) as string;
} }
export function verifyToken(token: string | null | undefined): JwtPayload | null { /**
* Fetch JWKS from the API and cache the keys
*/
async function fetchJwks(): Promise<Map<string, string>> {
try {
const response = await fetch(JWKS_URL, {
headers: { 'Accept': 'application/json' },
});
if (!response.ok) {
throw new Error(`JWKS fetch failed: ${response.status} ${response.statusText}`);
}
const jwks: JwksResponse = await response.json();
const keys = new Map<string, string>();
for (const jwk of jwks.keys) {
if (jwk.kty === 'RSA' && jwk.kid) {
try {
const pem = jwkToPem(jwk);
keys.set(jwk.kid, pem);
} catch (err) {
console.warn(`Failed to convert JWK ${jwk.kid} to PEM:`, (err as Error).message);
}
}
}
if (keys.size === 0) {
throw new Error('No valid RSA keys found in JWKS');
}
cachedKeys = {
keys,
fetchedAt: Date.now(),
};
console.log(`[JWT] Fetched ${keys.size} RSA public key(s) from JWKS`);
return keys;
} catch (error) {
console.error('[JWT] Failed to fetch JWKS:', (error as Error).message);
throw error;
}
}
/**
* Get cached keys or fetch fresh ones
*/
async function getKeys(forceRefresh = false): Promise<Map<string, string>> {
const now = Date.now();
if (!forceRefresh && cachedKeys && (now - cachedKeys.fetchedAt) < CACHE_TTL_MS) {
return cachedKeys.keys;
}
return fetchJwks();
}
/**
* Verify a JWT token using RS256 with keys from JWKS
*/
export async function verifyToken(token: string | null | undefined): Promise<JwtPayload | null> {
if (!token) { if (!token) {
return null; return null;
} }
@@ -52,14 +135,22 @@ export function verifyToken(token: string | null | undefined): JwtPayload | null
} }
const kid = decoded.header.kid; const kid = decoded.header.kid;
const key = keyFileData.keys[kid]; let keys = await getKeys();
let publicKey = keys.get(kid);
if (!key) { // If key not found, try refreshing JWKS (handles key rotation)
if (!publicKey) {
console.log(`[JWT] Key ${kid} not in cache, refreshing JWKS...`);
keys = await getKeys(true);
publicKey = keys.get(kid);
if (!publicKey) {
throw new Error(`Unknown kid: ${kid}`); throw new Error(`Unknown kid: ${kid}`);
} }
}
// Verify using the correct key and HS256 algo // Verify using RS256
const payload = jwt.verify(token, key, { algorithms: ['HS256'] }) as JwtPayload; const payload = jwt.verify(token, publicKey, { algorithms: ['RS256'] }) as JwtPayload;
return payload; return payload;
} catch (error) { } catch (error) {
@@ -67,3 +158,53 @@ export function verifyToken(token: string | null | undefined): JwtPayload | null
return null; return null;
} }
} }
/**
* Synchronous verification - uses cached keys only (for middleware compatibility)
* Falls back to null if cache is empty; caller should handle async verification
*/
export function verifyTokenSync(token: string | null | undefined): JwtPayload | null {
if (!token) {
return null;
}
if (!cachedKeys || cachedKeys.keys.size === 0) {
// No cached keys - caller needs to use async version
return null;
}
try {
const decoded = jwt.decode(token, { complete: true });
if (!decoded?.header?.kid) {
throw new Error('No kid in token header');
}
const kid = decoded.header.kid;
const publicKey = cachedKeys.keys.get(kid);
if (!publicKey) {
// Key not found - might need refresh, return null to signal async verification needed
return null;
}
// Verify using RS256
const payload = jwt.verify(token, publicKey, { algorithms: ['RS256'] }) as JwtPayload;
return payload;
} catch (error) {
console.error('JWT verification failed:', (error as Error).message);
return null;
}
}
/**
* Pre-warm the JWKS cache at startup
*/
export async function initializeJwks(): Promise<void> {
try {
await fetchJwks();
} catch (error) {
console.error('[JWT] Failed to pre-warm JWKS cache:', (error as Error).message);
// Don't throw - allow lazy initialization on first verification
}
}