Compare commits

1 Commits
dev ... master

Author SHA1 Message Date
4da8ba5dad Merge pull request 'dev' (#3) from dev into master
Reviewed-on: #3
2025-12-24 07:50:59 -05:00
11 changed files with 1500 additions and 659 deletions

View File

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

View File

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

View File

@@ -3284,14 +3284,9 @@ export default function DiscordLogs() {
// Check if current channel is 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
const HAVOC_BOT_ID = '1219636064608583770';
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
for (const group of members.groups) {
if (group.members?.some(m => m.id === HAVOC_BOT_ID)) {
@@ -3299,7 +3294,7 @@ export default function DiscordLogs() {
}
}
return false;
}, [members, isThread]);
}, [members]);
// Group messages by author and time window (5 minutes)
// Messages are in ASC order (oldest first, newest at bottom), so we group accordingly

View File

@@ -53,7 +53,7 @@ export default function LoginPage({ loggedIn = false, accessDenied = false, requ
password,
grant_type: "password",
scope: "",
client_id: "b8308cf47d424e66",
client_id: "",
client_secret: "",
});

View File

@@ -44,11 +44,6 @@ export default function Player({ user }: PlayerProps) {
// Global CSS now contains the paginator / dialog datatable dark rules.
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
useEffect(() => {
if (!isQueueVisible) return;
@@ -156,10 +151,6 @@ export default function Player({ user }: PlayerProps) {
const lastUpdateTimestamp = useRef<number>(Date.now());
const activeStationRef = useRef<string>(activeStation);
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 => {
if (!seconds || isNaN(seconds) || seconds < 0) return "00:00";
@@ -175,7 +166,6 @@ export default function Player({ user }: PlayerProps) {
// Initialize or switch HLS stream
const initializeStream = (station) => {
setIsStreamReady(false);
import('hls.js').then(({ default: Hls }) => {
const audio = audioElement.current;
if (!audio) return;
@@ -193,13 +183,11 @@ export default function Player({ user }: PlayerProps) {
// Handle audio load errors
audio.onerror = () => {
setIsPlaying(false);
setIsStreamReady(false);
};
if (audio.canPlayType("application/vnd.apple.mpegurl")) {
audio.src = streamUrl;
audio.load();
setIsStreamReady(true);
audio.play().then(() => setIsPlaying(true)).catch(() => {
setTrackTitle("Offline");
setIsPlaying(false);
@@ -229,7 +217,6 @@ export default function Player({ user }: PlayerProps) {
hls.attachMedia(audio);
hls.on(Hls.Events.MEDIA_ATTACHED, () => hls.loadSource(streamUrl));
hls.on(Hls.Events.MANIFEST_PARSED, () => {
setIsStreamReady(true);
audio.play().then(() => setIsPlaying(true)).catch(() => {
setIsPlaying(false);
});
@@ -241,7 +228,6 @@ export default function Player({ user }: PlayerProps) {
hlsInstance.current = null;
setTrackTitle("Offline");
setIsPlaying(false);
setIsStreamReady(false);
}
});
});
@@ -263,56 +249,16 @@ export default function Player({ user }: PlayerProps) {
// Scroll active lyric into view
useEffect(() => {
const container = lrcContainerRef.current;
if (!container || lyrics.length === 0) return;
const scheduleScroll = () => {
// Read ref/DOM inside the callback so we get the updated element after render
const activeElement = lrcActiveRef.current || (container.querySelector('.lrc-line.active') as HTMLElement | null);
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();
setTimeout(() => {
const activeElement = document.querySelector('.lrc-line.active');
const lyricsContainer = document.querySelector('.lrc-text');
if (activeElement && lyricsContainer) {
(lyricsContainer as HTMLElement).style.maxHeight = '220px';
(lyricsContainer as HTMLElement).style.overflowY = 'auto';
activeElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
};
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]);
}, 0);
}, [currentLyricIndex, lyrics]);
// Handle station changes: reset and start new stream
useEffect(() => {
@@ -360,20 +306,11 @@ export default function Player({ user }: PlayerProps) {
const handleTrackData = useCallback((trackData) => {
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
// AND we don't already have a valid track playing (to prevent race conditions)
// and not just missing song field (to avoid flickering during transitions)
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');
setLyrics([]);
}
// Otherwise ignore this empty data - keep showing current track
setTrackTitle('No track playing');
setLyrics([]);
return;
}
@@ -401,66 +338,28 @@ export default function Player({ user }: PlayerProps) {
}, []);
const initializeWebSocket = useCallback((station) => {
// Clean up existing WebSocket and timers
if (wsReconnectTimer.current) {
clearTimeout(wsReconnectTimer.current);
wsReconnectTimer.current = null;
}
if (wsConnectionCheckTimer.current) {
clearInterval(wsConnectionCheckTimer.current);
wsConnectionCheckTimer.current = null;
}
// Clean up existing WebSocket
if (wsInstance.current) {
wsInstance.current.onclose = null; // Prevent triggering reconnection logic
wsInstance.current.onerror = null;
wsInstance.current.close();
wsInstance.current = null;
}
let retryCount = 0;
const baseDelay = 1000; // 1 second
const maxDelay = 30000; // 30 seconds
let isIntentionallyClosed = false;
const connectWebSocket = () => {
if (isIntentionallyClosed) return;
const connectWebSocket = (retryCount = 0) => {
const baseDelay = 1000; // 1 second
const maxDelay = 30000; // 30 seconds
const wsUrl = `${API_URL.replace(/^https?:/, 'wss:')}/radio/ws/${station}`;
const ws = new WebSocket(wsUrl);
ws.onopen = function () {
// 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) {
// Track last message time for connection health monitoring
wsLastMessageTime.current = Date.now();
try {
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') {
// Handle track change
setLyrics([]);
@@ -471,35 +370,24 @@ export default function Player({ user }: PlayerProps) {
const parsedLyrics = parseLrcString(data.data);
setLyrics(parsedLyrics);
setCurrentLyricIndex(0);
} else if (data.type === 'now_playing' || data.type === 'initial') {
// 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
} else {
// Handle initial now playing data
handleTrackData(data);
}
// Ignore any other message types that don't contain track data
} catch (error) {
console.error('Error parsing WebSocket message:', error);
}
};
ws.onclose = function (event) {
// Clear connection check timer
if (wsConnectionCheckTimer.current) {
clearInterval(wsConnectionCheckTimer.current);
wsConnectionCheckTimer.current = null;
}
// Don't retry if it was a clean close (code 1000)
if (event.code === 1000) return;
// Always attempt reconnection unless intentionally closed
if (isIntentionallyClosed) return;
// Exponential backoff for reconnection
// Attempt reconnection with exponential backoff
const delay = Math.min(baseDelay * Math.pow(2, retryCount), maxDelay);
retryCount++;
wsReconnectTimer.current = setTimeout(() => {
connectWebSocket();
setTimeout(() => {
connectWebSocket(retryCount + 1);
}, delay);
};
@@ -512,25 +400,6 @@ export default function Player({ user }: PlayerProps) {
};
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]);
const setTrackMetadata = useCallback((trackData, requestStation) => {
@@ -553,43 +422,34 @@ export default function Player({ user }: PlayerProps) {
// Ensure the ref points to the current activeStation for in-flight guards
activeStationRef.current = activeStation;
// Initialize WebSocket connection for metadata
const cleanupWs = initializeWebSocket(activeStation);
// Handle visibility change - reconnect when page becomes visible
const handleVisibilityChange = () => {
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);
}
// Clean up the existing WebSocket connection before initializing a new one
const cleanupWebSocket = async () => {
if (wsInstance.current) {
wsInstance.current.onclose = null; // Prevent triggering reconnection logic
wsInstance.current.close();
wsInstance.current = null;
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
cleanupWebSocket().then(() => {
// Initialize WebSocket connection for metadata
initializeWebSocket(activeStation);
});
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
if (cleanupWs) cleanupWs();
// Clean up WebSocket on station change or component unmount
if (wsInstance.current) {
wsInstance.current.onclose = null; // Prevent triggering reconnection logic
wsInstance.current.close();
wsInstance.current = null;
}
};
}, [activeStation, initializeWebSocket]);
// Cleanup WebSocket on component unmount
useEffect(() => {
return () => {
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;
}
@@ -761,7 +621,7 @@ export default function Player({ user }: PlayerProps) {
const [queueSearch, setQueueSearch] = useState("");
const fetchQueue = async (page = queuePage, rows = queueRows, search = queueSearch) => {
const start = page * rows;
// console.log("Fetching queue for station (ref):", activeStationRef.current);
console.log("Fetching queue for station (ref):", activeStationRef.current);
try {
const response = await authFetch(`${API_URL}/radio/get_queue`, {
method: "POST",
@@ -787,13 +647,13 @@ export default function Player({ user }: PlayerProps) {
useEffect(() => {
if (isQueueVisible) {
// console.log("Fetching queue for station:", activeStation);
console.log("Fetching queue for station:", activeStation);
fetchQueue(queuePage, queueRows, queueSearch);
}
}, [isQueueVisible, queuePage, queueRows, queueSearch, activeStation]);
useEffect(() => {
// console.log("Active station changed to:", activeStation);
console.log("Active station changed to:", activeStation);
if (isQueueVisible) {
fetchQueue(queuePage, queueRows, queueSearch);
}
@@ -801,7 +661,7 @@ export default function Player({ user }: PlayerProps) {
useEffect(() => {
if (isQueueVisible) {
// console.log("Track changed, refreshing queue for station:", activeStation);
console.log("Track changed, refreshing queue for station:", activeStation);
fetchQueue(queuePage, queueRows, queueSearch);
}
}, [currentTrackUuid]);
@@ -886,42 +746,10 @@ export default function Player({ user }: PlayerProps) {
></div>
</div>
<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>
)}
<div className={`lrc-text mt-4 p-4 rounded-lg bg-neutral-100 dark:bg-neutral-800 ${lyrics.length === 0 ? "empty" : ""}`}>
{lyrics.map((lyricObj, index) => (
<p
key={index}
ref={index === currentLyricIndex ? (lrcActiveRef as React.RefObject<HTMLParagraphElement>) : undefined}
className={`lrc-line text-sm ${index === currentLyricIndex ? "active font-bold" : ""}`}
>
{lyricObj.line}
@@ -1002,27 +830,14 @@ export default function Player({ user }: PlayerProps) {
<div className="music-control mt-4 flex justify-center">
<div
className="music-control__play"
onClick={async () => {
onClick={() => {
const audio = audioElement.current;
if (!audio) return;
if (isPlaying) {
audio.pause();
setIsPlaying(false);
} else {
// 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);
}
audio.play().then(() => setIsPlaying(true));
}
}}
role="button"
@@ -1070,7 +885,7 @@ export default function Player({ user }: PlayerProps) {
fetchQueue(e.page ?? 0, queueRows, queueSearch);
}}
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport"
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} tracks"
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries"
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"
style={{ minHeight: 'auto', height: 'auto', tableLayout: 'fixed', width: '100%' }}
@@ -1090,7 +905,7 @@ export default function Player({ user }: PlayerProps) {
sortable
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' }}
body={(rowData) => <span title={`${rowData.artist} - ${rowData.song}`} style={{ display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '300px' }}>{rowData.artist} - {rowData.song}</span>}
body={(rowData) => <span title={rowData.artistsong} style={{ display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '300px' }}>{rowData.artistsong}</span>}
></Column>
<Column
field="album"

View File

@@ -1,19 +1,19 @@
import React from "react";
import Alert from "@mui/joy/Alert";
import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";
export default function RadioBanner(): React.ReactElement {
return (
<div className="radio-banner text-center mb-8">
<h2 className="text-[#333333] dark:text-[#D4D4D4] text-2xl font-bold mb-4">Radio</h2>
<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">
<div className="flex items-center">
<svg className="w-6 h-6 text-yellow-600 dark:text-yellow-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
<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" />
</svg>
<p className="text-yellow-800 dark:text-yellow-200 font-medium">
Maintenance in progress. Please check back soon!
</p>
</div>
</div>
<div>
<h2 style={{ textAlign: 'center', marginBottom: '1rem' }}>Radio</h2>
<Alert
variant="soft"
color="danger"
sx={{ fontSize: "1.0rem", textAlign: "center", mt: 4, mb: 4, px: 3, py: 2 }}
startDecorator={<ErrorOutlineIcon fontSize="large" />}
>
Maintenance in progress. Please check back soon!
</Alert>
</div>
);
}

View File

@@ -24,7 +24,6 @@ export default function BreadcrumbNav({ currentPage }: BreadcrumbNavProps): Reac
<React.Fragment key={key}>
<a
href={href}
data-astro-reload
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"
: "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,7 +100,6 @@ export default function MediaRequestForm() {
const albumHeaderRefs = useRef<Record<string | number, HTMLElement | null>>({});
const suppressHashRef = useRef(false);
const lastUrlRef = useRef("");
const playPauseClickRef = useRef(false);
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); // Helper for delays
const sanitizeFilename = (text: string) => (text || "").replace(/[\\/:*?"<>|]/g, "_") || "track";
@@ -559,42 +558,31 @@ export default function MediaRequestForm() {
};
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;
if (!audio) {
playPauseClickRef.current = false;
return;
}
if (!audio) return;
if (typeof albumIndex === "number") {
ensureAlbumExpanded(albumIndex);
}
try {
if (currentTrackId === track.id) {
if (audio.paused) {
setIsAudioPlaying(true);
if (currentTrackId === track.id) {
if (audio.paused) {
setIsAudioPlaying(true);
try {
await audio.play();
} else {
} catch (error) {
setIsAudioPlaying(false);
audio.pause();
console.error(error);
toast.error("Unable to resume playback.");
}
} else {
await playTrack(track, { fromQueue: false });
setIsAudioPlaying(false);
audio.pause();
}
} 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);
return;
}
await playTrack(track, { fromQueue: false });
};
const toggleAlbumShuffle = (albumId) => {
@@ -1005,14 +993,7 @@ export default function MediaRequestForm() {
}
const data = await response.json();
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';
}
});
toast.success(`Request submitted! (${allSelectedIds.length} tracks)`);
} catch (err) {
console.error(err);
toast.error("Failed to submit request.");
@@ -1316,13 +1297,22 @@ export default function MediaRequestForm() {
e.stopPropagation();
handleTrackPlayPause(track, id, albumIndex);
}}
style={{ touchAction: "manipulation", WebkitTapHighlightColor: "transparent" }}
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
onPointerDown={(e) => {
try {
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-neutral-400 text-neutral-600 hover:text-blue-600 hover:border-blue-600"}`}
aria-label={`${isCurrentTrack && isAudioPlaying ? "Pause" : "Play"} ${track.title}`}
aria-pressed={isCurrentTrack && isAudioPlaying}
disabled={audioLoadingTrackId === track.id || playPauseClickRef.current}
disabled={audioLoadingTrackId === track.id}
>
{audioLoadingTrackId === track.id ? (
<InlineSpinner sizeClass="h-4 w-4" />

View File

@@ -279,7 +279,6 @@
display: flex;
align-items: center;
width: 100%;
gap: 0.5rem; /* space between track and percent */
}
@@ -293,7 +292,6 @@
overflow: hidden; /* must clip when scaled */
margin: 0 !important;
padding: 0 !important;
margin-right: 0; /* ensure neighbor percent isn't pushed inside */
}
.rm-progress-track-lg {
@@ -310,41 +308,13 @@
transform: scaleX(var(--rm-progress, 0)); /* use custom property (0-1 range) */
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;
transition: transform 0.24s cubic-bezier(0.4,0,0.2,1), border-radius 0.24s;
margin: 0 !important;
padding: 0 !important;
right: 0;
min-width: 0;
will-change: transform, background-color;
will-change: transform;
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) */
@@ -434,47 +404,16 @@
.rm-progress-text {
font-size: 0.75rem;
font-weight: 600;
color: inherit;
}
/* 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{display:flex;align-items:center;width:100%}
.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 .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}
.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 */
.trip-management-container {
@@ -593,25 +532,6 @@
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 {
flex-direction: column;

View File

@@ -11,15 +11,6 @@ import BreadcrumbNav from "./BreadcrumbNav";
import { API_URL } from "@/config";
import "./RequestManagement.css";
interface TrackInfo {
title?: string;
artist?: string;
status?: string;
error?: string;
filename?: string;
[key: string]: unknown;
}
interface RequestJob {
id: string | number;
target: string;
@@ -31,7 +22,6 @@ interface RequestJob {
tarball?: string;
created_at?: string;
updated_at?: string;
track_list?: TrackInfo[];
[key: string]: unknown;
}
@@ -48,8 +38,6 @@ export default function RequestManagement() {
const [isLoading, setIsLoading] = useState(true);
const pollingRef = 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;
@@ -59,13 +47,6 @@ export default function RequestManagement() {
const filename = absPath.split("/").pop(); // get "SOMETHING.tar.gz"
// If the backend already stores a fully qualified URL, return as-is
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}`;
};
@@ -201,105 +182,30 @@ export default function RequestManagement() {
const computePct = (p: unknown) => {
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);
if (!Number.isFinite(num)) return 0;
// Backend sends progress as 0-100 directly, so just clamp it
return Math.min(100, Math.max(0, Math.round(num)));
const normalized = num > 1 ? num : num * 100;
return Math.min(100, Math.max(0, Math.round(normalized)));
};
// 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 p = rowData.progress;
if (p === null || p === undefined || p === "") return "—";
const pctRaw = computePct(p);
const isFinalizing = isFinalizingJob(rowData);
const pct = isFinalizing ? 99 : pctRaw;
const pct = computePct(p);
const getProgressColor = () => {
if (rowData.status === "Failed") return "bg-red-500";
if (rowData.status === "Finished") return "bg-green-500";
if (isFinalizing) return "bg-yellow-500"; // finalizing indicator
if (pctRaw < 30) return "bg-blue-400";
if (pctRaw < 70) return "bg-blue-500";
if (pct < 30) return "bg-blue-400";
if (pct < 70) return "bg-blue-500";
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 (
<div className="rm-progress-container">
<div className="rm-progress-track" style={{ flex: 1, minWidth: 0 }}>
<div
className={`rm-progress-fill ${getProgressColor()} ${isFinalizing ? 'rm-finalizing' : ''}`}
className={`rm-progress-fill ${getProgressColor()}`}
style={{
// CSS custom property for progress animation
['--rm-progress' as string]: (pct / 100).toString(),
@@ -307,12 +213,12 @@ export default function RequestManagement() {
borderBottomRightRadius: pct === 100 ? '999px' : 0
}}
data-pct={pct}
aria-valuenow={pctRaw}
aria-valuenow={pct}
aria-valuemin={0}
aria-valuemax={100}
/>
</div>
<span className="rm-progress-text" style={{ marginLeft: 8, flex: 'none' }}>{pct}%{isFinalizing ? ' (finalizing...)' : ''}</span>
<span className="rm-progress-text" style={{ marginLeft: 8, flex: 'none' }}>{pct}%</span>
</div>
);
};
@@ -505,34 +411,26 @@ export default function RequestManagement() {
<div className="rm-progress-container mt-2">
<div className="rm-progress-track rm-progress-track-lg">
{(() => {
const pctRawDialog = computePct(selectedRequest.progress);
const isFinalizingDialog = isFinalizingJob(selectedRequest);
const pctDialog = isFinalizingDialog ? 99 : pctRawDialog;
const pctDialog = computePct(selectedRequest.progress);
const status = selectedRequest.status;
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);
const fillColor = status === "Failed" ? "bg-red-500" : status === "Finished" ? "bg-green-500" : "bg-blue-500";
return (
<>
<div
className={`rm-progress-fill ${fillColor} ${isFinalizingDialog ? 'rm-finalizing' : ''}`}
style={{
['--rm-progress' as string]: (pctDialog / 100).toString(),
borderTopRightRadius: pctDialog >= 100 ? '999px' : 0,
borderBottomRightRadius: pctDialog >= 100 ? '999px' : 0
}}
data-pct={pctDialog}
aria-valuenow={pctRawDialog}
aria-valuemin={0}
aria-valuemax={100}
/>
</>
<div
className={`rm-progress-fill ${fillColor}`}
style={{
['--rm-progress' as string]: (pctDialog / 100).toString(),
borderTopRightRadius: pctDialog >= 100 ? '999px' : 0,
borderBottomRightRadius: pctDialog >= 100 ? '999px' : 0
}}
data-pct={pctDialog}
aria-valuenow={pctDialog}
aria-valuemin={0}
aria-valuemax={100}
/>
);
})()}
</div>
<span className="rm-progress-text">{formatProgress(selectedRequest.progress)}{isFinalizingJob(selectedRequest) ? ' — finalizing' : ''}</span>
<span className="rm-progress-text">{formatProgress(selectedRequest.progress)}</span>
</div>
</div>
)}
@@ -564,66 +462,6 @@ 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 >
) : (
<p>Loading...</p>