Compare commits
5 Commits
823c8b52b3
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 1da33de892 | |||
| 256d5d9c7f | |||
| bb71f662ed | |||
| bc847629e6 | |||
| 7b3862c43a |
@@ -364,7 +364,6 @@ Custom
|
|||||||
padding: 0.25rem 0.5rem;
|
padding: 0.25rem 0.5rem;
|
||||||
border-radius: 9999px;
|
border-radius: 9999px;
|
||||||
border: 1px solid;
|
border: 1px solid;
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.025em;
|
letter-spacing: 0.025em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,10 +29,19 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.mobile-menu-dropdown.open {
|
.mobile-menu-dropdown.open {
|
||||||
max-height: 500px;
|
max-height: none;
|
||||||
|
overflow: visible;
|
||||||
|
padding-bottom: 0.75rem;
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.mobile-menu-dropdown a {
|
||||||
|
font-size: 0.95rem;
|
||||||
|
line-height: 1.25rem;
|
||||||
|
padding: 0.6rem 0.75rem;
|
||||||
|
border-radius: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
@media (min-width: 768px) {
|
@media (min-width: 768px) {
|
||||||
.mobile-menu-dropdown {
|
.mobile-menu-dropdown {
|
||||||
display: none;
|
display: none;
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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 {
|
||||||
@@ -46,7 +68,8 @@ export interface RootProps {
|
|||||||
|
|
||||||
export default function Root({ child, user = undefined, ...props }: RootProps): React.ReactElement {
|
export default function Root({ child, user = undefined, ...props }: RootProps): React.ReactElement {
|
||||||
window.toast = toast;
|
window.toast = toast;
|
||||||
const theme = document.documentElement.getAttribute("data-theme")
|
const theme = document.documentElement.getAttribute("data-theme") ?? null;
|
||||||
|
const toastTheme = theme ?? undefined;
|
||||||
const loggedIn = props.loggedIn ?? Boolean(user);
|
const loggedIn = props.loggedIn ?? Boolean(user);
|
||||||
usePrimeReactThemeSwitcher(theme);
|
usePrimeReactThemeSwitcher(theme);
|
||||||
// Avoid adding the Player island for subsite requests. We expose a
|
// Avoid adding the Player island for subsite requests. We expose a
|
||||||
@@ -54,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
|
||||||
@@ -81,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('./AudioPlayer.jsx')
|
import('./Radio.tsx')
|
||||||
.then((mod) => {
|
.then((mod) => {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
// set the component factory
|
// set the component factory
|
||||||
@@ -102,7 +128,7 @@ export default function Root({ child, user = undefined, ...props }: RootProps):
|
|||||||
return (
|
return (
|
||||||
<PrimeReactProvider>
|
<PrimeReactProvider>
|
||||||
<CustomToastContainer
|
<CustomToastContainer
|
||||||
theme={theme}
|
theme={toastTheme}
|
||||||
newestOnTop={true}
|
newestOnTop={true}
|
||||||
closeOnClick={true} />
|
closeOnClick={true} />
|
||||||
<JoyUIRootIsland>
|
<JoyUIRootIsland>
|
||||||
@@ -113,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 {...props} client:only="react" />)}
|
<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 && (
|
||||||
<Suspense fallback={null}>
|
<LazyBoundary>
|
||||||
<PlayerComp client:only="react" user={user} />
|
<Suspense fallback={null}>
|
||||||
</Suspense>
|
<PlayerComp user={user} />
|
||||||
|
</Suspense>
|
||||||
|
</LazyBoundary>
|
||||||
|
)}
|
||||||
|
{child == "Memes" && (
|
||||||
|
<LazyBoundary>
|
||||||
|
<Memes />
|
||||||
|
</LazyBoundary>
|
||||||
)}
|
)}
|
||||||
{child == "Memes" && <Memes client:only="react" />}
|
|
||||||
{child == "DiscordLogs" && (
|
{child == "DiscordLogs" && (
|
||||||
<Suspense fallback={<div style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>}>
|
<LazyBoundary>
|
||||||
<DiscordLogs client:only="react" />
|
<Suspense fallback={<div style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>}>
|
||||||
</Suspense>
|
<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>
|
||||||
)}
|
)}
|
||||||
{child == "qs2.MediaRequestForm" && <MediaRequestForm client:only="react" />}
|
|
||||||
{child == "qs2.RequestManagement" && <RequestManagement client:only="react" />}
|
|
||||||
{child == "ReqForm" && <ReqForm {...props} client:only="react" />}
|
|
||||||
{child == "Lighting" && <Lighting key={window.location.pathname + Math.random()} client:only="react" />}
|
|
||||||
</JoyUIRootIsland>
|
</JoyUIRootIsland>
|
||||||
</PrimeReactProvider>
|
</PrimeReactProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -53,7 +53,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: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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')) {
|
||||||
setTrackTitle('No track playing');
|
// Only clear if we don't have a current track UUID (meaning we never had valid data)
|
||||||
setLyrics([]);
|
if (!currentTrackUuid.current) {
|
||||||
|
setTrackTitle('No track playing');
|
||||||
|
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"
|
||||||
@@ -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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,13 @@
|
|||||||
* This is a minimal version that avoids importing from shared modules
|
* This is a minimal version that avoids importing from shared modules
|
||||||
* that would pull in heavy CSS (AppLayout, Components, etc.)
|
* that would pull in heavy CSS (AppLayout, Components, etc.)
|
||||||
*/
|
*/
|
||||||
import React, { Suspense, lazy, ReactNode } from 'react';
|
import React, { Suspense, lazy } from 'react';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
import { ToastContainer, toast } from 'react-toastify';
|
import { ToastContainer, toast } from 'react-toastify';
|
||||||
import { CssVarsProvider } from "@mui/joy";
|
import { CssVarsProvider } from "@mui/joy";
|
||||||
import { CacheProvider, EmotionCache } from "@emotion/react";
|
import { CacheProvider } from "@emotion/react";
|
||||||
import createCache from "@emotion/cache";
|
import createCache from "@emotion/cache";
|
||||||
|
import type { EmotionCache } from "@emotion/cache";
|
||||||
import { PrimeReactProvider } from "primereact/api";
|
import { PrimeReactProvider } from "primereact/api";
|
||||||
|
|
||||||
// Import only minimal CSS - no theme CSS, no primeicons
|
// Import only minimal CSS - no theme CSS, no primeicons
|
||||||
|
|||||||
@@ -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"
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (currentTrackId === track.id) {
|
try {
|
||||||
if (audio.paused) {
|
if (currentTrackId === track.id) {
|
||||||
setIsAudioPlaying(true);
|
if (audio.paused) {
|
||||||
try {
|
setIsAudioPlaying(true);
|
||||||
await audio.play();
|
await audio.play();
|
||||||
} catch (error) {
|
} else {
|
||||||
setIsAudioPlaying(false);
|
setIsAudioPlaying(false);
|
||||||
console.error(error);
|
audio.pause();
|
||||||
toast.error("Unable to resume playback.");
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
setIsAudioPlaying(false);
|
await playTrack(track, { fromQueue: false });
|
||||||
audio.pause();
|
|
||||||
}
|
}
|
||||||
return;
|
} 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
await playTrack(track, { fromQueue: false });
|
|
||||||
};
|
};
|
||||||
|
|
||||||
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" />
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -11,17 +11,27 @@ 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;
|
||||||
tracks: number;
|
tracks: number;
|
||||||
quality: string;
|
quality: string;
|
||||||
status: string;
|
status: string;
|
||||||
progress: number;
|
progress: number | string | null;
|
||||||
type?: string;
|
type?: string;
|
||||||
tarball_path?: string;
|
tarball?: string;
|
||||||
created_at?: string;
|
created_at?: string;
|
||||||
updated_at?: string;
|
updated_at?: string;
|
||||||
|
track_list?: TrackInfo[];
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,11 +48,24 @@ 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 tarballUrl = (absPath: string | undefined, quality: string) => {
|
const tarballUrl = (absPath: string | undefined, quality: string) => {
|
||||||
if (!absPath) return null;
|
if (!absPath) return null;
|
||||||
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 (/^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}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -172,39 +195,111 @@ export default function RequestManagement() {
|
|||||||
|
|
||||||
const formatProgress = (p: unknown) => {
|
const formatProgress = (p: unknown) => {
|
||||||
if (p === null || p === undefined || p === "") return "—";
|
if (p === null || p === undefined || p === "") return "—";
|
||||||
const num = Number(p);
|
const pct = computePct(p);
|
||||||
if (Number.isNaN(num)) return "—";
|
|
||||||
const pct = num > 1 ? Math.round(num) : num;
|
|
||||||
return `${pct}%`;
|
return `${pct}%`;
|
||||||
};
|
};
|
||||||
|
|
||||||
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.isNaN(num)) return 0;
|
if (!Number.isFinite(num)) return 0;
|
||||||
return Math.min(100, Math.max(0, num > 1 ? Math.round(num) : Math.round(num * 100)));
|
// Backend sends progress as 0-100 directly, so just clamp it
|
||||||
|
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 === 0) return "—";
|
if (p === null || p === undefined || p === "") return "—";
|
||||||
const num = Number(p);
|
const pctRaw = computePct(p);
|
||||||
if (Number.isNaN(num)) return "—";
|
const isFinalizing = isFinalizingJob(rowData);
|
||||||
const pct = computePct(p);
|
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(),
|
||||||
@@ -212,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>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -341,7 +436,7 @@ export default function RequestManagement() {
|
|||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
body={(row: RequestJob) => {
|
body={(row: RequestJob) => {
|
||||||
const url = tarballUrl(row.tarball_path, row.quality || "FLAC");
|
const url = tarballUrl(resolveTarballPath(row as RequestJob), row.quality || "FLAC");
|
||||||
if (!url) return "—";
|
if (!url) return "—";
|
||||||
const encodedURL = encodeURI(url);
|
const encodedURL = encodeURI(url);
|
||||||
|
|
||||||
@@ -409,20 +504,35 @@ export default function RequestManagement() {
|
|||||||
<strong>Progress:</strong>
|
<strong>Progress:</strong>
|
||||||
<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">
|
||||||
<div
|
{(() => {
|
||||||
className={`rm-progress-fill ${selectedRequest.status === "Failed" ? "bg-red-500" : selectedRequest.status === "Finished" ? "bg-green-500" : "bg-blue-500"}`}
|
const pctRawDialog = computePct(selectedRequest.progress);
|
||||||
style={{
|
const isFinalizingDialog = isFinalizingJob(selectedRequest);
|
||||||
['--rm-progress' as string]: (computePct(selectedRequest.progress) / 100).toString(),
|
const pctDialog = isFinalizingDialog ? 99 : pctRawDialog;
|
||||||
borderTopRightRadius: computePct(selectedRequest.progress) >= 100 ? '999px' : 0,
|
const status = selectedRequest.status;
|
||||||
borderBottomRightRadius: computePct(selectedRequest.progress) >= 100 ? '999px' : 0
|
const fillColor = status === "Failed" ? "bg-red-500" : status === "Finished" ? "bg-green-500" : isFinalizingDialog ? "bg-yellow-500" : "bg-blue-500";
|
||||||
}}
|
|
||||||
data-pct={computePct(selectedRequest.progress)}
|
// Ensure we poll for finalizing jobs to get the real status update
|
||||||
aria-valuenow={Math.min(100, Math.max(0, Number(selectedRequest.progress) > 1 ? Math.round(selectedRequest.progress) : selectedRequest.progress * 100))}
|
if (isFinalizingDialog) startFinalizingPoll(selectedRequest.id);
|
||||||
aria-valuemin={0}
|
|
||||||
aria-valuemax={100}
|
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>
|
</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>
|
||||||
)}
|
)}
|
||||||
@@ -437,23 +547,83 @@ export default function RequestManagement() {
|
|||||||
|
|
||||||
{/* --- Tarball Card --- */}
|
{/* --- Tarball Card --- */}
|
||||||
{
|
{
|
||||||
selectedRequest.tarball_path && (
|
selectedRequest.tarball && (
|
||||||
<div className="p-3 bg-gray-100 dark:bg-neutral-800 rounded-md">
|
<div className="p-3 bg-gray-100 dark:bg-neutral-800 rounded-md">
|
||||||
<p>
|
<p>
|
||||||
<strong>Tarball:</strong>{" "}
|
<strong>Tarball:</strong>{" "}
|
||||||
<a
|
<a
|
||||||
href={encodeURI(tarballUrl(selectedRequest.tarball_path, selectedRequest.quality) || "")}
|
href={encodeURI(tarballUrl(resolveTarballPath(selectedRequest), selectedRequest.quality) || "")}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="text-blue-500 hover:underline"
|
className="text-blue-500 hover:underline"
|
||||||
>
|
>
|
||||||
{tarballUrl(selectedRequest.tarball_path, selectedRequest.quality)?.split("/").pop()}
|
{tarballUrl(resolveTarballPath(selectedRequest), selectedRequest.quality)?.split("/").pop()}
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
{/* --- 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>
|
||||||
|
|||||||
@@ -5,19 +5,46 @@ import { Button } from "@mui/joy";
|
|||||||
import { AutoComplete } from "primereact/autocomplete";
|
import { AutoComplete } from "primereact/autocomplete";
|
||||||
import { InputText } from "primereact/inputtext";
|
import { InputText } from "primereact/inputtext";
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
_t?: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type MediaType = 'movie' | 'tv' | string;
|
||||||
|
|
||||||
|
interface SearchItem {
|
||||||
|
label: string;
|
||||||
|
year?: string;
|
||||||
|
mediaType?: MediaType;
|
||||||
|
poster_path?: string | null;
|
||||||
|
overview?: string;
|
||||||
|
title?: string;
|
||||||
|
type?: string;
|
||||||
|
requester?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SubmittedRequest {
|
||||||
|
title: string;
|
||||||
|
year: string;
|
||||||
|
type: string;
|
||||||
|
requester: string;
|
||||||
|
poster_path?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export default function ReqForm() {
|
export default function ReqForm() {
|
||||||
const [type, setType] = useState("");
|
const [type, setType] = useState<string>("");
|
||||||
const [title, setTitle] = useState("");
|
const [title, setTitle] = useState<string>("");
|
||||||
const [year, setYear] = useState("");
|
const [year, setYear] = useState<string>("");
|
||||||
const [requester, setRequester] = useState("");
|
const [requester, setRequester] = useState<string>("");
|
||||||
const [selectedItem, setSelectedItem] = useState(null);
|
const [selectedItem, setSelectedItem] = useState<SearchItem | null>(null);
|
||||||
const [selectedOverview, setSelectedOverview] = useState("");
|
const [selectedOverview, setSelectedOverview] = useState<string>("");
|
||||||
const [selectedTitle, setSelectedTitle] = useState("");
|
const [selectedTitle, setSelectedTitle] = useState<string>("");
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
|
||||||
const [suggestions, setSuggestions] = useState([]);
|
const [suggestions, setSuggestions] = useState<SearchItem[]>([]);
|
||||||
const [posterLoading, setPosterLoading] = useState(true);
|
const [posterLoading, setPosterLoading] = useState<boolean>(true);
|
||||||
const [submittedRequest, setSubmittedRequest] = useState(null); // Track successful submission
|
const [submittedRequest, setSubmittedRequest] = useState<SubmittedRequest | null>(null); // Track successful submission
|
||||||
const [csrfToken, setCsrfToken] = useState(null);
|
const [csrfToken, setCsrfToken] = useState<string | null>(null);
|
||||||
|
|
||||||
// Get CSRF token from window global on mount
|
// Get CSRF token from window global on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -36,7 +63,7 @@ export default function ReqForm() {
|
|||||||
}
|
}
|
||||||
}, [title, selectedTitle, selectedOverview, selectedItem, type]);
|
}, [title, selectedTitle, selectedOverview, selectedItem, type]);
|
||||||
|
|
||||||
const searchTitles = async (event) => {
|
const searchTitles = async (event: { query: string }) => {
|
||||||
const query = event.query;
|
const query = event.query;
|
||||||
if (query.length < 2) {
|
if (query.length < 2) {
|
||||||
setSuggestions([]);
|
setSuggestions([]);
|
||||||
@@ -48,7 +75,7 @@ export default function ReqForm() {
|
|||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`API error: ${response.status}`);
|
throw new Error(`API error: ${response.status}`);
|
||||||
}
|
}
|
||||||
const data = await response.json();
|
const data: SearchItem[] = await response.json();
|
||||||
setSuggestions(data);
|
setSuggestions(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching suggestions:', error);
|
console.error('Error fetching suggestions:', error);
|
||||||
@@ -56,7 +83,7 @@ export default function ReqForm() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async (e) => {
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!title.trim()) {
|
if (!title.trim()) {
|
||||||
toast.error("Please fill in the required fields.");
|
toast.error("Please fill in the required fields.");
|
||||||
@@ -101,7 +128,7 @@ export default function ReqForm() {
|
|||||||
year,
|
year,
|
||||||
type,
|
type,
|
||||||
requester,
|
requester,
|
||||||
poster_path: selectedItem?.poster_path,
|
poster_path: selectedItem?.poster_path ?? null,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Submission error:', error);
|
console.error('Submission error:', error);
|
||||||
@@ -126,13 +153,13 @@ export default function ReqForm() {
|
|||||||
|
|
||||||
const attachScrollFix = () => {
|
const attachScrollFix = () => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const panel = document.querySelector(".p-autocomplete-panel");
|
const panel = document.querySelector<HTMLElement>(".p-autocomplete-panel");
|
||||||
const items = panel?.querySelector(".p-autocomplete-items");
|
const items = panel?.querySelector<HTMLElement>(".p-autocomplete-items");
|
||||||
if (items) {
|
if (items) {
|
||||||
items.style.maxHeight = "200px";
|
items.style.maxHeight = "200px";
|
||||||
items.style.overflowY = "auto";
|
items.style.overflowY = "auto";
|
||||||
items.style.overscrollBehavior = "contain";
|
items.style.overscrollBehavior = "contain";
|
||||||
const wheelHandler = (e) => {
|
const wheelHandler = (e: WheelEvent) => {
|
||||||
const delta = e.deltaY;
|
const delta = e.deltaY;
|
||||||
const atTop = items.scrollTop === 0;
|
const atTop = items.scrollTop === 0;
|
||||||
const atBottom = items.scrollTop + items.clientHeight >= items.scrollHeight;
|
const atBottom = items.scrollTop + items.clientHeight >= items.scrollHeight;
|
||||||
@@ -148,7 +175,7 @@ export default function ReqForm() {
|
|||||||
}, 0);
|
}, 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
const formatMediaType = (mediaTypeValue) => {
|
const formatMediaType = (mediaTypeValue: MediaType | undefined) => {
|
||||||
if (!mediaTypeValue) return "";
|
if (!mediaTypeValue) return "";
|
||||||
if (mediaTypeValue === "tv") return "TV Series";
|
if (mediaTypeValue === "tv") return "TV Series";
|
||||||
if (mediaTypeValue === "movie") return "Movie";
|
if (mediaTypeValue === "movie") return "Movie";
|
||||||
@@ -239,16 +266,17 @@ export default function ReqForm() {
|
|||||||
delay={300}
|
delay={300}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
// Handle both string input and object selection
|
// Handle both string input and object selection
|
||||||
const val = e.target?.value ?? e.value;
|
const val = (e as any).target?.value ?? e.value;
|
||||||
setTitle(typeof val === 'string' ? val : val?.label || '');
|
setTitle(typeof val === 'string' ? val : (val as SearchItem | undefined)?.label || '');
|
||||||
}}
|
}}
|
||||||
onSelect={(e) => {
|
onSelect={(e: { value: SearchItem }) => {
|
||||||
setType(e.value.mediaType === 'tv' ? 'tv' : 'movie');
|
const item = e.value;
|
||||||
setTitle(e.value.label);
|
setType(item.mediaType === 'tv' ? 'tv' : 'movie');
|
||||||
setSelectedTitle(e.value.label);
|
setTitle(item.label);
|
||||||
setSelectedItem(e.value);
|
setSelectedTitle(item.label);
|
||||||
if (e.value.year) setYear(e.value.year);
|
setSelectedItem(item);
|
||||||
setSelectedOverview(e.value.overview || "");
|
if (item.year) setYear(item.year);
|
||||||
|
setSelectedOverview(item.overview || "");
|
||||||
}}
|
}}
|
||||||
placeholder="Enter movie or TV title"
|
placeholder="Enter movie or TV title"
|
||||||
title="Enter movie or TV show title"
|
title="Enter movie or TV show title"
|
||||||
|
|||||||
@@ -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.5"
|
export const MAJOR_VERSION: string = "0.6"
|
||||||
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";
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { ReactNode, CSSProperties } from 'react';
|
import React from 'react';
|
||||||
|
import type { ReactNode, CSSProperties } from 'react';
|
||||||
|
|
||||||
interface WhitelabelLayoutProps {
|
interface WhitelabelLayoutProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
|
|||||||
511
src/middleware.js
Normal file
511
src/middleware.js
Normal file
@@ -0,0 +1,511 @@
|
|||||||
|
import { defineMiddleware } from 'astro:middleware';
|
||||||
|
import { SUBSITES, PROTECTED_ROUTES, PUBLIC_ROUTES } from './config.js';
|
||||||
|
import { getSubsiteByHost, getSubsiteFromSignal } from './utils/subsites.js';
|
||||||
|
|
||||||
|
// Polyfill Headers.getSetCookie for environments where it's not present.
|
||||||
|
// Astro's Node adapter expects headers.getSetCookie() to exist when
|
||||||
|
// 'set-cookie' headers are present; in some Node runtimes Headers lacks it
|
||||||
|
// which leads to TypeError: headers.getSetCookie is not a function.
|
||||||
|
if (typeof globalThis.Headers !== 'undefined' && typeof globalThis.Headers.prototype.getSetCookie !== 'function') {
|
||||||
|
try {
|
||||||
|
Object.defineProperty(globalThis.Headers.prototype, 'getSetCookie', {
|
||||||
|
value: function () {
|
||||||
|
const cookies = [];
|
||||||
|
for (const [name, val] of this.entries()) {
|
||||||
|
if (name && name.toLowerCase() === 'set-cookie') cookies.push(val);
|
||||||
|
}
|
||||||
|
return cookies;
|
||||||
|
},
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
// If we can't patch Headers, swallow silently — code will still try to
|
||||||
|
// access getSetCookie, but our other guards handle missing function calls.
|
||||||
|
console.warn('[middleware] Failed to polyfill Headers.getSetCookie', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const API_URL = "https://api.codey.lol";
|
||||||
|
const AUTH_TIMEOUT_MS = 3000; // 3 second timeout for auth requests
|
||||||
|
|
||||||
|
// Deduplication for concurrent refresh requests (prevents race condition where
|
||||||
|
// multiple SSR requests try to refresh simultaneously, causing 401s after the
|
||||||
|
// first one rotates the refresh token)
|
||||||
|
let refreshPromise = null;
|
||||||
|
let lastRefreshResult = null;
|
||||||
|
let lastRefreshTime = 0;
|
||||||
|
const REFRESH_RESULT_TTL = 5000; // Cache successful refresh result for 5 seconds
|
||||||
|
|
||||||
|
// Auth check function (mirrors requireAuthHook logic but for middleware)
|
||||||
|
async function checkAuth(request) {
|
||||||
|
try {
|
||||||
|
const cookieHeader = request.headers.get("cookie") ?? "";
|
||||||
|
|
||||||
|
// Add timeout to prevent hanging
|
||||||
|
let controller = new AbortController;
|
||||||
|
let timeout = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS);
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(`${API_URL}/auth/id`, {
|
||||||
|
headers: { Cookie: cookieHeader },
|
||||||
|
credentials: "include",
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
console.error("[middleware] auth/id failed or timed out", err.name === 'AbortError' ? 'timeout' : err);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
clearTimeout(timeout);
|
||||||
|
|
||||||
|
if (res.status === 401) {
|
||||||
|
// Check if we even have a refresh token before attempting refresh
|
||||||
|
if (!cookieHeader.includes('refresh_token=')) {
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if we have a recent successful refresh result we can reuse
|
||||||
|
const now = Date.now();
|
||||||
|
if (lastRefreshResult && (now - lastRefreshTime) < REFRESH_RESULT_TTL) {
|
||||||
|
console.log(`[middleware] Reusing cached refresh result from ${now - lastRefreshTime}ms ago`);
|
||||||
|
return lastRefreshResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deduplicate concurrent refresh requests
|
||||||
|
if (refreshPromise) {
|
||||||
|
console.log(`[middleware] Waiting for in-flight refresh request`);
|
||||||
|
return refreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start a new refresh request
|
||||||
|
refreshPromise = (async () => {
|
||||||
|
console.log(`[middleware] Starting token refresh...`);
|
||||||
|
let controller = new AbortController();
|
||||||
|
let timeout = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS);
|
||||||
|
let refreshRes;
|
||||||
|
try {
|
||||||
|
refreshRes = await fetch(`${API_URL}/auth/refresh`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Cookie: cookieHeader },
|
||||||
|
credentials: "include",
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
console.error("[middleware] auth/refresh failed or timed out", err.name === 'AbortError' ? 'timeout' : err);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
clearTimeout(timeout);
|
||||||
|
|
||||||
|
if (!refreshRes.ok) {
|
||||||
|
// Log the response body for debugging
|
||||||
|
let errorDetail = '';
|
||||||
|
try {
|
||||||
|
const errorBody = await refreshRes.text();
|
||||||
|
errorDetail = ` - ${errorBody}`;
|
||||||
|
} catch {}
|
||||||
|
console.error(`[middleware] Token refresh failed ${refreshRes.status}${errorDetail}`);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[middleware] Token refresh succeeded`);
|
||||||
|
|
||||||
|
// Get refreshed cookies
|
||||||
|
let setCookies = [];
|
||||||
|
if (typeof refreshRes.headers.getSetCookie === 'function') {
|
||||||
|
setCookies = refreshRes.headers.getSetCookie();
|
||||||
|
} else {
|
||||||
|
const setCookieHeader = refreshRes.headers.get("set-cookie");
|
||||||
|
if (setCookieHeader) {
|
||||||
|
setCookies = setCookieHeader.split(/,(?=\s*[a-zA-Z_][a-zA-Z0-9_]*=)/);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (setCookies.length === 0) {
|
||||||
|
console.error("[middleware] No set-cookie headers in refresh response");
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build new cookie header for retry
|
||||||
|
const newCookieHeader = setCookies.map(c => c.split(";")[0].trim()).join("; ");
|
||||||
|
|
||||||
|
// Retry auth/id with new cookies and timeout
|
||||||
|
controller = new AbortController();
|
||||||
|
timeout = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS);
|
||||||
|
let retryRes;
|
||||||
|
try {
|
||||||
|
retryRes = await fetch(`${API_URL}/auth/id`, {
|
||||||
|
headers: { Cookie: newCookieHeader },
|
||||||
|
credentials: "include",
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
console.error("[middleware] auth/id retry failed or timed out", err.name === 'AbortError' ? 'timeout' : err);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
clearTimeout(timeout);
|
||||||
|
|
||||||
|
if (!retryRes.ok) {
|
||||||
|
console.error(`[middleware] auth/id retry failed with status ${retryRes.status}`);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await retryRes.json();
|
||||||
|
return { authenticated: true, user, cookies: setCookies };
|
||||||
|
})();
|
||||||
|
|
||||||
|
// Clear the promise when done and cache the result
|
||||||
|
refreshPromise.then(result => {
|
||||||
|
if (result.authenticated) {
|
||||||
|
lastRefreshResult = result;
|
||||||
|
lastRefreshTime = Date.now();
|
||||||
|
}
|
||||||
|
refreshPromise = null;
|
||||||
|
}).catch(() => {
|
||||||
|
refreshPromise = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
return refreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await res.json();
|
||||||
|
return { authenticated: true, user, cookies: null };
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[middleware] Auth check error:", err);
|
||||||
|
return { authenticated: false, user: null, cookies: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if a path matches any protected route and return the config
|
||||||
|
function getProtectedRouteConfig(pathname) {
|
||||||
|
// Normalize pathname for comparison (lowercase)
|
||||||
|
const normalizedPath = pathname.toLowerCase();
|
||||||
|
|
||||||
|
for (const route of PROTECTED_ROUTES) {
|
||||||
|
const routePath = typeof route === 'string' ? route : route.path;
|
||||||
|
const normalizedRoute = routePath.toLowerCase();
|
||||||
|
const matches = normalizedPath === normalizedRoute || normalizedPath.startsWith(normalizedRoute + '/');
|
||||||
|
if (matches) {
|
||||||
|
// Check if this path is excluded from protection
|
||||||
|
const excludes = (typeof route === 'object' && route.exclude) || [];
|
||||||
|
for (const excludePath of excludes) {
|
||||||
|
const normalizedExclude = excludePath.toLowerCase();
|
||||||
|
if (normalizedPath === normalizedExclude || normalizedPath.startsWith(normalizedExclude + '/')) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Path ${pathname} excluded from protection by ${excludePath}`);
|
||||||
|
return null; // Excluded, not protected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return typeof route === 'string' ? { path: route, roles: null } : route;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if a path is explicitly public (but NOT if it matches a protected route)
|
||||||
|
function isPublicRoute(pathname) {
|
||||||
|
// If the path matches a protected route, it's NOT public
|
||||||
|
if (getProtectedRouteConfig(pathname)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const route of PUBLIC_ROUTES) {
|
||||||
|
// For routes ending with /, match any path starting with that prefix
|
||||||
|
if (route.endsWith('/') && route !== '/') {
|
||||||
|
if (pathname.startsWith(route)) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] isPublicRoute: ${pathname} matched ${route} (prefix)`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// For other routes, match exactly or as a path prefix (route + /)
|
||||||
|
if (pathname === route) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] isPublicRoute: ${pathname} matched ${route} (exact)`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Special case: don't treat / as a prefix for all paths
|
||||||
|
if (route !== '/' && pathname.startsWith(route + '/')) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] isPublicRoute: ${pathname} matched ${route}/ (subpath)`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] isPublicRoute(${pathname}) = false`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const onRequest = defineMiddleware(async (context, next) => {
|
||||||
|
try {
|
||||||
|
const pathname = context.url.pathname;
|
||||||
|
|
||||||
|
// Skip auth check for static assets
|
||||||
|
const skipAuthPrefixes = ['/_astro', '/_', '/assets', '/scripts', '/favicon', '/images', '/_static'];
|
||||||
|
const shouldSkipAuth = skipAuthPrefixes.some(p => pathname.startsWith(p));
|
||||||
|
|
||||||
|
// Check if route is protected (requires auth)
|
||||||
|
const protectedConfig = getProtectedRouteConfig(pathname);
|
||||||
|
const isApiRoute = pathname.startsWith('/api/');
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Path: ${pathname}, Protected: ${!!protectedConfig}, SkipAuth: ${shouldSkipAuth}`);
|
||||||
|
|
||||||
|
// Always attempt auth for non-static routes to populate user info
|
||||||
|
if (!shouldSkipAuth) {
|
||||||
|
const { authenticated, user, cookies } = await checkAuth(context.request);
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Auth result: authenticated=${authenticated}`);
|
||||||
|
|
||||||
|
// Expose authenticated user and refreshed cookies to downstream handlers/layouts
|
||||||
|
if (authenticated && user) {
|
||||||
|
context.locals.user = user;
|
||||||
|
if (cookies && cookies.length > 0) {
|
||||||
|
context.locals.refreshedCookies = cookies;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// For protected routes, enforce authentication
|
||||||
|
if (protectedConfig && !isPublicRoute(pathname)) {
|
||||||
|
if (!authenticated) {
|
||||||
|
if (isApiRoute) {
|
||||||
|
// Return JSON 401 for API routes
|
||||||
|
return new Response(JSON.stringify({ error: 'Unauthorized', message: 'Authentication required' }), {
|
||||||
|
status: 401,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Redirect to login with return URL
|
||||||
|
const returnUrl = encodeURIComponent(pathname + context.url.search);
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Auth required for ${pathname}, redirecting to login`);
|
||||||
|
return context.redirect(`/login?returnUrl=${returnUrl}`, 302);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check role-based access if roles are specified
|
||||||
|
if (protectedConfig.roles && protectedConfig.roles.length > 0) {
|
||||||
|
const userRoles = user?.roles || [];
|
||||||
|
const isAdmin = userRoles.includes('admin');
|
||||||
|
const hasRequiredRole = isAdmin || protectedConfig.roles.some(role => userRoles.includes(role));
|
||||||
|
if (!hasRequiredRole) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] User lacks required role for ${pathname}`);
|
||||||
|
if (isApiRoute) {
|
||||||
|
// Return JSON 403 for API routes
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
error: 'Forbidden',
|
||||||
|
message: 'Insufficient permissions',
|
||||||
|
requiredRoles: protectedConfig.roles
|
||||||
|
}), {
|
||||||
|
status: 403,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Store required roles in locals for the login page to access
|
||||||
|
context.locals.accessDenied = true;
|
||||||
|
context.locals.requiredRoles = protectedConfig.roles;
|
||||||
|
context.locals.returnUrl = pathname + context.url.search;
|
||||||
|
// Rewrite to login page - this renders /login but keeps the URL and locals
|
||||||
|
return context.rewrite('/login');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Auth OK for ${pathname}, user: ${user?.username || user?.id || 'unknown'}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check the Host header to differentiate subdomains
|
||||||
|
// Build a headers map safely because Headers.get(':authority') throws
|
||||||
|
const headersMap = {};
|
||||||
|
for (const [k, v] of context.request.headers) {
|
||||||
|
headersMap[k.toLowerCase()] = v;
|
||||||
|
}
|
||||||
|
const hostHeader = headersMap['host'] || '';
|
||||||
|
// Node/http2 might store host as :authority (pseudo header); it appears under iteration as ':authority'
|
||||||
|
const authorityHeader = headersMap[':authority'] || '';
|
||||||
|
// Fallback to context.url.hostname if available (some environments populate it)
|
||||||
|
const urlHost = context.url?.hostname || '';
|
||||||
|
const host = (hostHeader || authorityHeader || urlHost).split(':')[0]; // normalize remove port
|
||||||
|
|
||||||
|
const requestIp = (headersMap['x-forwarded-for']?.split(',')[0]?.trim())
|
||||||
|
|| headersMap['x-real-ip']
|
||||||
|
|| headersMap['cf-connecting-ip']
|
||||||
|
|| headersMap['forwarded']?.split(';').find(kv => kv.trim().startsWith('for='))?.split('=')[1]?.replace(/"/g, '')
|
||||||
|
|| context.request.headers.get('x-client-ip')
|
||||||
|
|| 'unknown';
|
||||||
|
|
||||||
|
// Cloudflare geo data (available in production)
|
||||||
|
const cfCountry = headersMap['cf-ipcountry'] || null;
|
||||||
|
const userAgent = headersMap['user-agent'] || null;
|
||||||
|
|
||||||
|
// Debug info for incoming requests
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] incoming: host=${hostHeader} ip=${requestIp} path=${context.url.pathname}`);
|
||||||
|
|
||||||
|
|
||||||
|
// When the host header is missing, log all headers for debugging and
|
||||||
|
// attempt to determine host from forwarded headers or a dev query header.
|
||||||
|
if (!host) {
|
||||||
|
if (import.meta.env.DEV) console.log('[middleware] WARNING: Host header missing. Dumping headers:');
|
||||||
|
for (const [k, v] of context.request.headers) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] header: ${k}=${v}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine if how the request says it wants the whitelabel
|
||||||
|
const forwardedHost = headersMap['x-forwarded-host'] || '';
|
||||||
|
const xWhitelabel = headersMap['x-whitelabel'] || '';
|
||||||
|
const forceWhitelabelQuery = context.url.searchParams.get('whitelabel');
|
||||||
|
|
||||||
|
// Make whitelabel detection dynamic based on `SUBSITES` mapping and incoming signals
|
||||||
|
// We'll detect by full host (host/forwarded/authority) or by short-name match
|
||||||
|
const subsiteHosts = Object.keys(SUBSITES || {});
|
||||||
|
|
||||||
|
const hostSubsite = getSubsiteByHost(host);
|
||||||
|
const forwardedSubsite = getSubsiteByHost(forwardedHost);
|
||||||
|
const authoritySubsite = getSubsiteByHost(authorityHeader);
|
||||||
|
const headerSignalSubsite = getSubsiteFromSignal(xWhitelabel);
|
||||||
|
const querySignalSubsite = getSubsiteFromSignal(forceWhitelabelQuery);
|
||||||
|
|
||||||
|
const wantsSubsite = Boolean(hostSubsite || forwardedSubsite || authoritySubsite || headerSignalSubsite || querySignalSubsite);
|
||||||
|
|
||||||
|
// Use central SUBSITES mapping
|
||||||
|
// import from config.js near top to ensure single source of truth
|
||||||
|
// (we import lazily here for compatibility with middleware runtime)
|
||||||
|
const subsites = SUBSITES || {};
|
||||||
|
|
||||||
|
// Check if the request matches a subsite
|
||||||
|
const subsitePath = subsites[host];
|
||||||
|
if (subsitePath) {
|
||||||
|
const skipPrefixes = ['/_astro', '/_', '/assets', '/scripts', '/favicon', '/api', '/robots.txt', '/_static'];
|
||||||
|
const shouldSkip = skipPrefixes.some((p) => context.url.pathname.startsWith(p));
|
||||||
|
|
||||||
|
if (!shouldSkip && !context.url.pathname.startsWith(subsitePath)) {
|
||||||
|
const newPath = `${subsitePath}${context.url.pathname}`;
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Rewriting ${host} ${context.url.pathname} -> ${newPath}`);
|
||||||
|
return context.rewrite(newPath);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// If the path appears to be a subsite path (like /subsites/req) but the host isn't a subsite,
|
||||||
|
// block so the main site doesn't accidentally serve that content.
|
||||||
|
const allPaths = Object.values(subsites || {});
|
||||||
|
const pathLooksLikeSubsite = allPaths.some((p) => context.url.pathname.startsWith(p));
|
||||||
|
if (pathLooksLikeSubsite) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Blocking subsite path on main domain: ${host}${context.url.pathname}`);
|
||||||
|
return new Response('Not found', { status: 404 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Block /subsites/req/* on main domain (codey.lol, local.codey.lol, etc)
|
||||||
|
const isMainDomain = !wantsSubsite;
|
||||||
|
if (isMainDomain && Object.values(subsites || {}).some(p => context.url.pathname.startsWith(p))) {
|
||||||
|
// Immediately return a 404 for /req on the main domain
|
||||||
|
if (Object.values(subsites || {}).includes(context.url.pathname)) {
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Blocking subsite root on main domain: ${hostHeader}${context.url.pathname}`);
|
||||||
|
return new Response('Not found', { status: 404 });
|
||||||
|
}
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Blocking subsite wildcard path on main domain: ${hostHeader}${context.url.pathname}`);
|
||||||
|
return new Response('Not found', { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Explicitly handle the forceWhitelabelQuery to rewrite the path
|
||||||
|
if (forceWhitelabelQuery) {
|
||||||
|
const forced = getSubsiteFromSignal(forceWhitelabelQuery);
|
||||||
|
const subsitePath = forced?.path || (`/${forceWhitelabelQuery}`.startsWith('/') ? `/${forceWhitelabelQuery}` : `/${forceWhitelabelQuery}`);
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Forcing whitelabel via query: ${forceWhitelabelQuery} -> rewrite to ${subsitePath}${context.url.pathname}`);
|
||||||
|
context.url.pathname = `${subsitePath}${context.url.pathname}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass the whitelabel value explicitly to context.locals
|
||||||
|
// set a normalized whitelabel short name if available
|
||||||
|
const chosen = querySignalSubsite?.short || headerSignalSubsite?.short || hostSubsite?.short || forwardedSubsite?.short || authoritySubsite?.short || null;
|
||||||
|
context.locals.whitelabel = chosen;
|
||||||
|
context.locals.isSubsite = Boolean(wantsSubsite);
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Setting context.locals.whitelabel: ${context.locals.whitelabel}`);
|
||||||
|
|
||||||
|
// Final debug: show the final pathname we hand to Astro
|
||||||
|
if (import.meta.env.DEV) console.log(`[middleware] Final pathname: ${context.url.pathname}`);
|
||||||
|
|
||||||
|
// Let Astro handle the request first
|
||||||
|
const response = await next();
|
||||||
|
|
||||||
|
// Add security headers to response
|
||||||
|
const securityHeaders = new Headers(response.headers);
|
||||||
|
|
||||||
|
// Prevent clickjacking
|
||||||
|
securityHeaders.set('X-Frame-Options', 'SAMEORIGIN');
|
||||||
|
|
||||||
|
// Prevent MIME type sniffing
|
||||||
|
securityHeaders.set('X-Content-Type-Options', 'nosniff');
|
||||||
|
|
||||||
|
// XSS protection (legacy, but still useful)
|
||||||
|
securityHeaders.set('X-XSS-Protection', '1; mode=block');
|
||||||
|
|
||||||
|
// Referrer policy - send origin only on cross-origin requests
|
||||||
|
securityHeaders.set('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||||
|
|
||||||
|
// HSTS - enforce HTTPS (only in production)
|
||||||
|
if (!import.meta.env.DEV) {
|
||||||
|
securityHeaders.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Permissions policy - restrict sensitive APIs
|
||||||
|
securityHeaders.set('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
|
||||||
|
|
||||||
|
// Content Security Policy - restrict resource loading
|
||||||
|
// Note: 'unsafe-inline' and 'unsafe-eval' needed for React/Astro hydration
|
||||||
|
// In production, consider using nonces or hashes for stricter CSP
|
||||||
|
const cspDirectives = [
|
||||||
|
"default-src 'self'",
|
||||||
|
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.youtube.com https://www.youtube-nocookie.com https://s.ytimg.com https://challenges.cloudflare.com https://static.cloudflareinsights.com",
|
||||||
|
// Allow Cloudflare's inline event handlers (for Turnstile/challenges)
|
||||||
|
"script-src-attr 'unsafe-inline'",
|
||||||
|
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
|
||||||
|
"font-src 'self' https://fonts.gstatic.com data:",
|
||||||
|
"img-src 'self' data: blob: https: http:",
|
||||||
|
"media-src 'self' blob: https:",
|
||||||
|
"connect-src 'self' https://api.codey.lol https://*.codey.lol https://*.audio.tidal.com wss:",
|
||||||
|
// Allow YouTube for video embeds and Cloudflare for challenges/Turnstile
|
||||||
|
"frame-src 'self' https://www.youtube.com https://www.youtube-nocookie.com https://challenges.cloudflare.com",
|
||||||
|
"object-src 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
"frame-ancestors 'self'",
|
||||||
|
"upgrade-insecure-requests",
|
||||||
|
].join('; ');
|
||||||
|
securityHeaders.set('Content-Security-Policy', cspDirectives);
|
||||||
|
|
||||||
|
// Forward any refreshed auth cookies to the client
|
||||||
|
if (context.locals.refreshedCookies && context.locals.refreshedCookies.length > 0) {
|
||||||
|
const newResponse = new Response(response.body, {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
headers: securityHeaders,
|
||||||
|
});
|
||||||
|
context.locals.refreshedCookies.forEach(cookie => {
|
||||||
|
newResponse.headers.append('set-cookie', cookie.trim());
|
||||||
|
});
|
||||||
|
|
||||||
|
// If it's a 404, redirect to home
|
||||||
|
if (newResponse.status === 404 && !context.url.pathname.startsWith('/api/')) {
|
||||||
|
if (import.meta.env.DEV) console.log(`404 redirect: ${context.url.pathname} -> /`);
|
||||||
|
return context.redirect('/', 302);
|
||||||
|
}
|
||||||
|
|
||||||
|
return newResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If it's a 404, redirect to home
|
||||||
|
if (response.status === 404 && !context.url.pathname.startsWith('/api/')) {
|
||||||
|
if (import.meta.env.DEV) console.log(`404 redirect: ${context.url.pathname} -> /`);
|
||||||
|
return context.redirect('/', 302);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return response with security headers
|
||||||
|
return new Response(response.body, {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
headers: securityHeaders,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Handle any middleware errors by redirecting to home
|
||||||
|
console.error('Middleware error:', error);
|
||||||
|
return context.redirect('/', 302);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -2,6 +2,30 @@ import { defineMiddleware } from 'astro:middleware';
|
|||||||
import { SUBSITES, PROTECTED_ROUTES, PUBLIC_ROUTES, type ProtectedRoute } from './config.ts';
|
import { SUBSITES, PROTECTED_ROUTES, PUBLIC_ROUTES, type ProtectedRoute } from './config.ts';
|
||||||
import { getSubsiteByHost, getSubsiteFromSignal, type SubsiteInfo } from './utils/subsites.ts';
|
import { getSubsiteByHost, getSubsiteFromSignal, type SubsiteInfo } from './utils/subsites.ts';
|
||||||
|
|
||||||
|
declare module 'astro' {
|
||||||
|
interface Locals {
|
||||||
|
user?: AuthUser;
|
||||||
|
refreshedCookies?: string[];
|
||||||
|
accessDenied?: boolean;
|
||||||
|
requiredRoles?: string[];
|
||||||
|
returnUrl?: string;
|
||||||
|
whitelabel?: string | null;
|
||||||
|
isSubsite?: boolean;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module 'astro:middleware' {
|
||||||
|
interface Locals {
|
||||||
|
user?: AuthUser;
|
||||||
|
refreshedCookies?: string[];
|
||||||
|
accessDenied?: boolean;
|
||||||
|
requiredRoles?: string[];
|
||||||
|
returnUrl?: string;
|
||||||
|
whitelabel?: string | null;
|
||||||
|
isSubsite?: boolean;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export interface AuthUser {
|
export interface AuthUser {
|
||||||
id?: string;
|
id?: string;
|
||||||
username?: string;
|
username?: string;
|
||||||
@@ -313,9 +337,9 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
// Store required roles in locals for the login page to access
|
// Store required roles in locals for the login page to access
|
||||||
context.locals.accessDenied = true;
|
(context.locals as any).accessDenied = true;
|
||||||
context.locals.requiredRoles = protectedConfig.roles;
|
(context.locals as any).requiredRoles = protectedConfig.roles;
|
||||||
context.locals.returnUrl = pathname + context.url.search;
|
(context.locals as any).returnUrl = pathname + context.url.search;
|
||||||
// Rewrite to login page - this renders /login but keeps the URL and locals
|
// Rewrite to login page - this renders /login but keeps the URL and locals
|
||||||
return context.rewrite('/login');
|
return context.rewrite('/login');
|
||||||
}
|
}
|
||||||
@@ -374,8 +398,8 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
|||||||
const hostSubsite = getSubsiteByHost(host);
|
const hostSubsite = getSubsiteByHost(host);
|
||||||
const forwardedSubsite = getSubsiteByHost(forwardedHost);
|
const forwardedSubsite = getSubsiteByHost(forwardedHost);
|
||||||
const authoritySubsite = getSubsiteByHost(authorityHeader);
|
const authoritySubsite = getSubsiteByHost(authorityHeader);
|
||||||
const headerSignalSubsite = getSubsiteFromSignal(xWhitelabel);
|
const headerSignalSubsite = getSubsiteFromSignal(xWhitelabel || undefined);
|
||||||
const querySignalSubsite = getSubsiteFromSignal(forceWhitelabelQuery);
|
const querySignalSubsite = getSubsiteFromSignal(forceWhitelabelQuery || undefined);
|
||||||
|
|
||||||
const wantsSubsite = Boolean(hostSubsite || forwardedSubsite || authoritySubsite || headerSignalSubsite || querySignalSubsite);
|
const wantsSubsite = Boolean(hostSubsite || forwardedSubsite || authoritySubsite || headerSignalSubsite || querySignalSubsite);
|
||||||
|
|
||||||
@@ -420,7 +444,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
|||||||
|
|
||||||
// Explicitly handle the forceWhitelabelQuery to rewrite the path
|
// Explicitly handle the forceWhitelabelQuery to rewrite the path
|
||||||
if (forceWhitelabelQuery) {
|
if (forceWhitelabelQuery) {
|
||||||
const forced = getSubsiteFromSignal(forceWhitelabelQuery);
|
const forced = getSubsiteFromSignal(forceWhitelabelQuery || undefined);
|
||||||
const subsitePath = forced?.path || (`/${forceWhitelabelQuery}`.startsWith('/') ? `/${forceWhitelabelQuery}` : `/${forceWhitelabelQuery}`);
|
const subsitePath = forced?.path || (`/${forceWhitelabelQuery}`.startsWith('/') ? `/${forceWhitelabelQuery}` : `/${forceWhitelabelQuery}`);
|
||||||
if (import.meta.env.DEV) console.log(`[middleware] Forcing whitelabel via query: ${forceWhitelabelQuery} -> rewrite to ${subsitePath}${context.url.pathname}`);
|
if (import.meta.env.DEV) console.log(`[middleware] Forcing whitelabel via query: ${forceWhitelabelQuery} -> rewrite to ${subsitePath}${context.url.pathname}`);
|
||||||
context.url.pathname = `${subsitePath}${context.url.pathname}`;
|
context.url.pathname = `${subsitePath}${context.url.pathname}`;
|
||||||
@@ -433,7 +457,6 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
|||||||
// Also make it explicit whether this request maps to a subsite (any configured SUBSITES value)
|
// Also make it explicit whether this request maps to a subsite (any configured SUBSITES value)
|
||||||
// Middleware already resolved `wantsSubsite` which is true if host/forwarded/authority/header/query indicate a subsite.
|
// Middleware already resolved `wantsSubsite` which is true if host/forwarded/authority/header/query indicate a subsite.
|
||||||
// Expose a simple boolean so server-rendered pages/layouts or components can opt-out of loading/hydrating
|
// Expose a simple boolean so server-rendered pages/layouts or components can opt-out of loading/hydrating
|
||||||
// heavyweight subsystems (like the AudioPlayer) when the request is for a subsite.
|
|
||||||
context.locals.isSubsite = Boolean(wantsSubsite);
|
context.locals.isSubsite = Boolean(wantsSubsite);
|
||||||
if (import.meta.env.DEV) console.log(`[middleware] Setting context.locals.whitelabel: ${context.locals.whitelabel}`);
|
if (import.meta.env.DEV) console.log(`[middleware] Setting context.locals.whitelabel: ${context.locals.whitelabel}`);
|
||||||
|
|
||||||
|
|||||||
@@ -120,6 +120,10 @@ export async function GET({ request }: APIContext): Promise<Response> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Partial content
|
// Partial content
|
||||||
|
if (result.start == null || result.end == null) {
|
||||||
|
console.error('[cached-video] Missing range bounds in partial response');
|
||||||
|
return new Response('Invalid range', { status: 500 });
|
||||||
|
}
|
||||||
headers.set('Content-Range', `bytes ${result.start}-${result.end}/${result.total}`);
|
headers.set('Content-Range', `bytes ${result.start}-${result.end}/${result.total}`);
|
||||||
headers.set('Content-Length', String(result.end - result.start + 1));
|
headers.set('Content-Length', String(result.end - result.start + 1));
|
||||||
return new Response(result.stream, { status: 206, headers });
|
return new Response(result.stream, { status: 206, headers });
|
||||||
|
|||||||
@@ -27,9 +27,9 @@ interface ChannelRow {
|
|||||||
export async function GET({ request }: APIContext): Promise<Response> {
|
export async function GET({ request }: APIContext): Promise<Response> {
|
||||||
// Rate limit check
|
// Rate limit check
|
||||||
const rateCheck = checkRateLimit(request, {
|
const rateCheck = checkRateLimit(request, {
|
||||||
limit: 20,
|
limit: 60,
|
||||||
windowMs: 1000,
|
windowMs: 1000,
|
||||||
burstLimit: 100,
|
burstLimit: 240,
|
||||||
burstWindowMs: 10_000,
|
burstWindowMs: 10_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,12 @@ const ADMINISTRATOR = 0x8n; // 8
|
|||||||
* 3. Apply member-specific overwrites (allow/deny)
|
* 3. Apply member-specific overwrites (allow/deny)
|
||||||
* 4. Check if VIEW_CHANNEL permission is granted
|
* 4. Check if VIEW_CHANNEL permission is granted
|
||||||
*/
|
*/
|
||||||
async function getChannelVisibleMembers(channelId, guildId) {
|
interface RoleOverwrite {
|
||||||
|
allow: bigint;
|
||||||
|
deny: bigint;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getChannelVisibleMembers(channelId: string, guildId: string): Promise<Set<string>> {
|
||||||
// Get guild info including owner
|
// Get guild info including owner
|
||||||
const guildInfo = await sql`
|
const guildInfo = await sql`
|
||||||
SELECT owner_id FROM guilds WHERE guild_id = ${guildId}
|
SELECT owner_id FROM guilds WHERE guild_id = ${guildId}
|
||||||
@@ -43,8 +48,8 @@ async function getChannelVisibleMembers(channelId, guildId) {
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
// Build overwrite lookups
|
// Build overwrite lookups
|
||||||
const roleOverwrites = new Map();
|
const roleOverwrites = new Map<string, RoleOverwrite>();
|
||||||
const memberOverwrites = new Map();
|
const memberOverwrites = new Map<string, RoleOverwrite>();
|
||||||
for (const ow of overwrites) {
|
for (const ow of overwrites) {
|
||||||
const targetId = ow.target_id.toString();
|
const targetId = ow.target_id.toString();
|
||||||
const allow = BigInt(ow.allow_permissions);
|
const allow = BigInt(ow.allow_permissions);
|
||||||
@@ -67,16 +72,16 @@ async function getChannelVisibleMembers(channelId, guildId) {
|
|||||||
const allRoles = await sql`
|
const allRoles = await sql`
|
||||||
SELECT role_id, permissions FROM roles WHERE guild_id = ${guildId}
|
SELECT role_id, permissions FROM roles WHERE guild_id = ${guildId}
|
||||||
`;
|
`;
|
||||||
const rolePermissions = new Map();
|
const rolePermissions = new Map<string, bigint>();
|
||||||
for (const role of allRoles) {
|
for (const role of allRoles) {
|
||||||
rolePermissions.set(role.role_id.toString(), BigInt(role.permissions || 0));
|
rolePermissions.set(role.role_id.toString(), BigInt(role.permissions || 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
const visibleMemberIds = new Set();
|
const visibleMemberIds = new Set<string>();
|
||||||
|
|
||||||
for (const member of members) {
|
for (const member of members) {
|
||||||
const userId = member.user_id.toString();
|
const userId = member.user_id.toString();
|
||||||
const memberRoles = (member.roles || []).map(r => r.toString());
|
const memberRoles = (member.roles || []).map((r: bigint | string) => r.toString());
|
||||||
|
|
||||||
// Owner always has access
|
// Owner always has access
|
||||||
if (ownerId && member.user_id.toString() === ownerId.toString()) {
|
if (ownerId && member.user_id.toString() === ownerId.toString()) {
|
||||||
@@ -138,9 +143,9 @@ async function getChannelVisibleMembers(channelId, guildId) {
|
|||||||
export async function GET({ request }) {
|
export async function GET({ request }) {
|
||||||
// Rate limit check
|
// Rate limit check
|
||||||
const rateCheck = checkRateLimit(request, {
|
const rateCheck = checkRateLimit(request, {
|
||||||
limit: 20,
|
limit: 80,
|
||||||
windowMs: 1000,
|
windowMs: 1000,
|
||||||
burstLimit: 100,
|
burstLimit: 320,
|
||||||
burstWindowMs: 10_000,
|
burstWindowMs: 10_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -187,7 +192,7 @@ export async function GET({ request }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If channelId provided, get visible members for that channel
|
// If channelId provided, get visible members for that channel
|
||||||
let visibleMemberIds = null;
|
let visibleMemberIds: Set<string> | null = null;
|
||||||
if (channelId) {
|
if (channelId) {
|
||||||
visibleMemberIds = await getChannelVisibleMembers(channelId, guildId);
|
visibleMemberIds = await getChannelVisibleMembers(channelId, guildId);
|
||||||
}
|
}
|
||||||
@@ -226,14 +231,22 @@ export async function GET({ request }) {
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
// Create role lookup map
|
// Create role lookup map
|
||||||
const roleMap = {};
|
interface RoleInfo {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
color: string | null;
|
||||||
|
position: number;
|
||||||
|
hoist: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const roleMap: Record<string, RoleInfo> = {};
|
||||||
roles.forEach(role => {
|
roles.forEach(role => {
|
||||||
roleMap[role.role_id.toString()] = {
|
roleMap[role.role_id.toString()] = {
|
||||||
id: role.role_id.toString(),
|
id: role.role_id.toString(),
|
||||||
name: role.name,
|
name: role.name,
|
||||||
color: role.color ? `#${role.color.toString(16).padStart(6, '0')}` : null,
|
color: role.color ? `#${Number(role.color).toString(16).padStart(6, '0')}` : null,
|
||||||
position: role.position,
|
position: Number(role.position ?? 0),
|
||||||
hoist: role.hoist, // "hoist" means the role is displayed separately in member list
|
hoist: Boolean(role.hoist), // "hoist" means the role is displayed separately in member list
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -243,11 +256,24 @@ export async function GET({ request }) {
|
|||||||
: members;
|
: members;
|
||||||
|
|
||||||
// Format members with their highest role for color
|
// Format members with their highest role for color
|
||||||
const formattedMembers = filteredMembers.map(member => {
|
interface FormattedMember {
|
||||||
const memberRoles = (member.roles || []).map(r => r.toString());
|
id: string;
|
||||||
|
username: string;
|
||||||
|
displayName: string;
|
||||||
|
avatar: string | null;
|
||||||
|
isBot: boolean;
|
||||||
|
color: string | null;
|
||||||
|
primaryRoleId: string | null;
|
||||||
|
primaryRoleName: string | null;
|
||||||
|
roles: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const formattedMembers: FormattedMember[] = filteredMembers.map(member => {
|
||||||
|
const memberRoles = (member.roles || []).map((r: bigint | string) => r.toString());
|
||||||
|
|
||||||
// Find highest positioned role with color for display
|
// Find highest positioned role with color for display
|
||||||
let displayRole = null;
|
let displayRole: RoleInfo | null = null;
|
||||||
|
let displayRoleColor: string | null = null;
|
||||||
let highestPosition = -1;
|
let highestPosition = -1;
|
||||||
|
|
||||||
memberRoles.forEach(roleId => {
|
memberRoles.forEach(roleId => {
|
||||||
@@ -256,6 +282,7 @@ export async function GET({ request }) {
|
|||||||
highestPosition = role.position;
|
highestPosition = role.position;
|
||||||
if (role.color && role.color !== '#000000') {
|
if (role.color && role.color !== '#000000') {
|
||||||
displayRole = role;
|
displayRole = role;
|
||||||
|
displayRoleColor = role.color;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -263,7 +290,7 @@ export async function GET({ request }) {
|
|||||||
// Find all hoisted roles for grouping
|
// Find all hoisted roles for grouping
|
||||||
const hoistedRoles = memberRoles
|
const hoistedRoles = memberRoles
|
||||||
.map(rid => roleMap[rid])
|
.map(rid => roleMap[rid])
|
||||||
.filter(r => r && r.hoist)
|
.filter((r): r is RoleInfo => Boolean(r && r.hoist))
|
||||||
.sort((a, b) => b.position - a.position);
|
.sort((a, b) => b.position - a.position);
|
||||||
|
|
||||||
const primaryRole = hoistedRoles[0] || displayRole || null;
|
const primaryRole = hoistedRoles[0] || displayRole || null;
|
||||||
@@ -284,7 +311,7 @@ export async function GET({ request }) {
|
|||||||
displayName: member.nickname || member.global_name || member.username,
|
displayName: member.nickname || member.global_name || member.username,
|
||||||
avatar: avatarUrl,
|
avatar: avatarUrl,
|
||||||
isBot: member.is_bot || false,
|
isBot: member.is_bot || false,
|
||||||
color: displayRole?.color || null,
|
color: displayRoleColor,
|
||||||
primaryRoleId: primaryRole?.id || null,
|
primaryRoleId: primaryRole?.id || null,
|
||||||
primaryRoleName: primaryRole?.name || null,
|
primaryRoleName: primaryRole?.name || null,
|
||||||
roles: memberRoles,
|
roles: memberRoles,
|
||||||
@@ -292,8 +319,8 @@ export async function GET({ request }) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Group members by their primary (highest hoisted) role
|
// Group members by their primary (highest hoisted) role
|
||||||
const membersByRole = {};
|
const membersByRole: Record<string, { role: RoleInfo; members: FormattedMember[] }> = {};
|
||||||
const noRoleMembers = [];
|
const noRoleMembers: FormattedMember[] = [];
|
||||||
|
|
||||||
formattedMembers.forEach(member => {
|
formattedMembers.forEach(member => {
|
||||||
if (member.primaryRoleId) {
|
if (member.primaryRoleId) {
|
||||||
@@ -316,7 +343,7 @@ export async function GET({ request }) {
|
|||||||
// Add "Online" or default group for members without hoisted roles
|
// Add "Online" or default group for members without hoisted roles
|
||||||
if (noRoleMembers.length > 0) {
|
if (noRoleMembers.length > 0) {
|
||||||
sortedGroups.push({
|
sortedGroups.push({
|
||||||
role: { id: 'none', name: 'Members', color: null, position: -1 },
|
role: { id: 'none', name: 'Members', color: null, position: -1, hoist: false },
|
||||||
members: noRoleMembers,
|
members: noRoleMembers,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -99,9 +99,9 @@ function getSafeImageUrl(originalUrl: string | null, baseUrl: string): string |
|
|||||||
export async function GET({ request }: APIContext) {
|
export async function GET({ request }: APIContext) {
|
||||||
// Rate limit check
|
// Rate limit check
|
||||||
const rateCheck = checkRateLimit(request, {
|
const rateCheck = checkRateLimit(request, {
|
||||||
limit: 30,
|
limit: 100,
|
||||||
windowMs: 1000,
|
windowMs: 1000,
|
||||||
burstLimit: 150,
|
burstLimit: 400,
|
||||||
burstWindowMs: 10_000,
|
burstWindowMs: 10_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -920,7 +920,7 @@ export async function GET({ request }: APIContext) {
|
|||||||
}
|
}
|
||||||
const ext = stickerExtensions[sticker.format_type] || 'png';
|
const ext = stickerExtensions[sticker.format_type] || 'png';
|
||||||
// Use cached sticker image if available, otherwise fall back to Discord CDN
|
// Use cached sticker image if available, otherwise fall back to Discord CDN
|
||||||
let stickerUrl = null;
|
let stickerUrl: string | null = null;
|
||||||
if (sticker.cached_image_id) {
|
if (sticker.cached_image_id) {
|
||||||
const sig = signImageId(sticker.cached_image_id);
|
const sig = signImageId(sticker.cached_image_id);
|
||||||
stickerUrl = `${baseUrl}/api/discord/cached-image?id=${sticker.cached_image_id}&sig=${sig}`;
|
stickerUrl = `${baseUrl}/api/discord/cached-image?id=${sticker.cached_image_id}&sig=${sig}`;
|
||||||
|
|||||||
@@ -182,7 +182,20 @@ export async function GET({ request }) {
|
|||||||
LEFT JOIN video_cache vc ON a.cached_video_id = vc.video_id
|
LEFT JOIN video_cache vc ON a.cached_video_id = vc.video_id
|
||||||
WHERE a.message_id = ANY(${messageIds})
|
WHERE a.message_id = ANY(${messageIds})
|
||||||
ORDER BY a.attachment_id
|
ORDER BY a.attachment_id
|
||||||
`;
|
` as unknown as Array<{
|
||||||
|
message_id: string;
|
||||||
|
attachment_id: string;
|
||||||
|
filename: string | null;
|
||||||
|
url: string;
|
||||||
|
proxy_url: string | null;
|
||||||
|
content_type: string | null;
|
||||||
|
size: number | null;
|
||||||
|
width: number | null;
|
||||||
|
height: number | null;
|
||||||
|
cached_image_id: number | null;
|
||||||
|
cached_video_id: number | null;
|
||||||
|
video_file_path: string | null;
|
||||||
|
}>;
|
||||||
|
|
||||||
// Fetch cached video URLs for video attachments
|
// Fetch cached video URLs for video attachments
|
||||||
const videoUrls = attachments
|
const videoUrls = attachments
|
||||||
@@ -193,9 +206,9 @@ export async function GET({ request }) {
|
|||||||
SELECT source_url, video_id
|
SELECT source_url, video_id
|
||||||
FROM video_cache
|
FROM video_cache
|
||||||
WHERE source_url = ANY(${videoUrls})
|
WHERE source_url = ANY(${videoUrls})
|
||||||
` : [];
|
` as unknown as Array<{ source_url: string; video_id: number }> : [];
|
||||||
|
|
||||||
const videoCacheMap = {};
|
const videoCacheMap: Record<string, number> = {};
|
||||||
cachedVideos.forEach(v => {
|
cachedVideos.forEach(v => {
|
||||||
videoCacheMap[v.source_url] = v.video_id;
|
videoCacheMap[v.source_url] = v.video_id;
|
||||||
});
|
});
|
||||||
@@ -234,7 +247,13 @@ export async function GET({ request }) {
|
|||||||
.filter(m => m.reference_message_id)
|
.filter(m => m.reference_message_id)
|
||||||
.map(m => m.reference_message_id);
|
.map(m => m.reference_message_id);
|
||||||
|
|
||||||
let referencedMessages = [];
|
let referencedMessages: Array<{
|
||||||
|
message_id: string;
|
||||||
|
content: string;
|
||||||
|
author_id: string;
|
||||||
|
author_username: string;
|
||||||
|
author_display_name: string;
|
||||||
|
}> = [];
|
||||||
if (referencedIds.length > 0) {
|
if (referencedIds.length > 0) {
|
||||||
referencedMessages = await sql`
|
referencedMessages = await sql`
|
||||||
SELECT
|
SELECT
|
||||||
|
|||||||
@@ -263,7 +263,8 @@ export async function GET({ request }) {
|
|||||||
return proxyResponse;
|
return proxyResponse;
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[image-proxy] Error fetching image:', err.message);
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
console.error('[image-proxy] Error fetching image:', message);
|
||||||
return new Response('Failed to fetch image', { status: 500 });
|
return new Response('Failed to fetch image', { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ interface LinkPreviewMeta {
|
|||||||
type: string | null;
|
type: string | null;
|
||||||
video: string | null;
|
video: string | null;
|
||||||
themeColor: string | null;
|
themeColor: string | null;
|
||||||
|
trusted: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trusted domains that can be loaded client-side
|
// Trusted domains that can be loaded client-side
|
||||||
@@ -73,6 +74,7 @@ function parseMetaTags(html: string, url: string): LinkPreviewMeta {
|
|||||||
type: null,
|
type: null,
|
||||||
video: null,
|
video: null,
|
||||||
themeColor: null,
|
themeColor: null,
|
||||||
|
trusted: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
const decode = str => str?.replace(/&(#(?:x[0-9a-fA-F]+|\d+)|[a-zA-Z]+);/g,
|
const decode = str => str?.replace(/&(#(?:x[0-9a-fA-F]+|\d+)|[a-zA-Z]+);/g,
|
||||||
@@ -253,6 +255,13 @@ export async function GET({ request }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Read first 50KB
|
// Read first 50KB
|
||||||
|
if (!response.body) {
|
||||||
|
return new Response(JSON.stringify({ error: 'Empty response body' }), {
|
||||||
|
status: 502,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const reader = response.body.getReader();
|
const reader = response.body.getReader();
|
||||||
let html = '';
|
let html = '';
|
||||||
let bytesRead = 0;
|
let bytesRead = 0;
|
||||||
@@ -281,7 +290,8 @@ export async function GET({ request }) {
|
|||||||
return resp;
|
return resp;
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[link-preview] Error fetching URL:', err.message);
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
console.error('[link-preview] Error fetching URL:', message);
|
||||||
// Don't expose internal error details to client
|
// Don't expose internal error details to client
|
||||||
return new Response(JSON.stringify({ error: 'Failed to fetch preview' }), {
|
return new Response(JSON.stringify({ error: 'Failed to fetch preview' }), {
|
||||||
status: 500,
|
status: 500,
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ interface SearchSuggestion {
|
|||||||
|
|
||||||
export async function GET({ request }: APIContext): Promise<Response> {
|
export async function GET({ request }: APIContext): Promise<Response> {
|
||||||
const host = request.headers.get('host');
|
const host = request.headers.get('host');
|
||||||
const subsite = getSubsiteByHost(host);
|
const subsite = getSubsiteByHost(host || undefined);
|
||||||
|
|
||||||
if (!subsite || subsite.short !== 'req') {
|
if (!subsite || subsite.short !== 'req') {
|
||||||
return new Response('Not found', { status: 404 });
|
return new Response('Not found', { status: 404 });
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import Root from "@/components/AppLayout.jsx";
|
|||||||
const user = Astro.locals.user as any;
|
const user = Astro.locals.user as any;
|
||||||
---
|
---
|
||||||
|
|
||||||
<Base>
|
<Base title="Lighting">
|
||||||
<section class="page-section">
|
<section class="page-section">
|
||||||
<Root child="Lighting" user?={user} client:only="react" />
|
<Root child="Lighting" user?={user} client:only="react" />
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const accessDenied = Astro.locals.accessDenied || false;
|
|||||||
const requiredRoles = Astro.locals.requiredRoles || [];
|
const requiredRoles = Astro.locals.requiredRoles || [];
|
||||||
|
|
||||||
---
|
---
|
||||||
<Base>
|
<Base title="Login">
|
||||||
<section class="page-section">
|
<section class="page-section">
|
||||||
<Root child="LoginPage" loggedIn={isLoggedIn} accessDenied={accessDenied} requiredRoles={requiredRoles} client:only="react" />
|
<Root child="LoginPage" loggedIn={isLoggedIn} accessDenied={accessDenied} requiredRoles={requiredRoles} client:only="react" />
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import Root from "../components/AppLayout.jsx";
|
|||||||
import "@styles/MemeGrid.css";
|
import "@styles/MemeGrid.css";
|
||||||
---
|
---
|
||||||
|
|
||||||
<Base hideFooter>
|
<Base hideFooter title="Memes">
|
||||||
<section class="page-section">
|
<section class="page-section">
|
||||||
<Root child="Memes" client:only="react" />
|
<Root child="Memes" client:only="react" />
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export async function requireApiAuth(request: Request): Promise<AuthResult> {
|
|||||||
}
|
}
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
|
|
||||||
let newSetCookieHeader = null;
|
let newSetCookieHeader: string[] | null = null;
|
||||||
|
|
||||||
// If unauthorized, try to refresh the token
|
// If unauthorized, try to refresh the token
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import postgres from 'postgres';
|
|||||||
import type { Sql } from 'postgres';
|
import type { Sql } from 'postgres';
|
||||||
|
|
||||||
// Database connection configuration
|
// Database connection configuration
|
||||||
const sql: Sql = postgres({
|
const sql: Sql<any> = postgres({
|
||||||
host: import.meta.env.DISCORD_DB_HOST || 'localhost',
|
host: import.meta.env.DISCORD_DB_HOST || 'localhost',
|
||||||
port: parseInt(import.meta.env.DISCORD_DB_PORT || '5432', 10),
|
port: parseInt(import.meta.env.DISCORD_DB_PORT || '5432', 10),
|
||||||
database: import.meta.env.DISCORD_DB_NAME || 'discord',
|
database: import.meta.env.DISCORD_DB_NAME || 'discord',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { SUBSITES, WHITELABELS, WhitelabelConfig } from '../config.ts';
|
import { SUBSITES, WHITELABELS, type WhitelabelConfig } from '../config.ts';
|
||||||
|
|
||||||
export interface SubsiteInfo {
|
export interface SubsiteInfo {
|
||||||
host: string;
|
host: string;
|
||||||
|
|||||||
Reference in New Issue
Block a user