Skip to content

Usenet streaming with a WebDAV server and a SABnzbd-compatible API

C#

Added real-time queue/history.

nzbdav-dev23d3950dd277
diff --git a/frontend/app/clients/backend-client.server.ts b/frontend/app/clients/backend-client.server.ts
index e3505e85..9e762565 100644
--- a/frontend/app/clients/backend-client.server.ts
+++ b/frontend/app/clients/backend-client.server.ts
@@ -251,7 +251,7 @@ class BackendClient {
export const backendClient = new BackendClient();
export type QueueResponse = {
- slots: [QueueSlot]
+ slots: QueueSlot[]
}
export type QueueSlot = {
@@ -266,7 +266,7 @@ export type QueueSlot = {
}
export type HistoryResponse = {
- slots: [HistorySlot]
+ slots: HistorySlot[]
}
export type HistorySlot = {
diff --git a/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.tsx b/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.tsx
index 2fcee330..e63f0c1e 100644
--- a/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.tsx
+++ b/frontend/app/routes/_index/components/live-usenet-connections/live-usenet-connections.tsx
@@ -1,7 +1,8 @@
import { useEffect, useState } from "react";
import styles from "./live-usenet-connections.module.css";
+import { receiveMessage } from "~/utils/websocket-util";
-const usenetConnectionsTopic = "cxs";
+const usenetConnectionsTopic = {'cxs': 'state'};
export function LiveUsenetConnections() {
const [connections, setConnections] = useState<string | null>(null);
@@ -16,8 +17,8 @@ export function LiveUsenetConnections() {
let disposed = false;
function connect() {
ws = new WebSocket(window.location.origin.replace(/^http/, 'ws'));
- ws.onmessage = (event) => setConnections(event.data);
- ws.onopen = () => ws.send(usenetConnectionsTopic);
+ ws.onmessage = receiveMessage((_, message) => setConnections(message));
+ ws.onopen = () => ws.send(JSON.stringify(usenetConnectionsTopic));
ws.onclose = () => { !disposed && setTimeout(() => connect(), 1000); setConnections(null) };
ws.onerror = () => { ws.close() };
return () => { disposed = true; ws.close(); }
diff --git a/frontend/app/routes/queue/components/history-table/history-table.tsx b/frontend/app/routes/queue/components/history-table/history-table.tsx
index 9ef9c70a..0b533e1c 100644
--- a/frontend/app/routes/queue/components/history-table/history-table.tsx
+++ b/frontend/app/routes/queue/components/history-table/history-table.tsx
@@ -1,5 +1,5 @@
-import type { HistoryResponse, HistorySlot } from "~/clients/backend-client.server"
-import { CategoryBadge, formatFileSize, StatusBadge } from "../queue-table/queue-table"
+import type { HistorySlot } from "~/clients/backend-client.server"
+import { CategoryBadge, formatFileSize } from "../queue-table/queue-table"
import { ActionButton } from "../action-button/action-button"
import { PageTable } from "../page-table/page-table"
import tableStyles from "../page-table/page-table.module.css"
@@ -7,12 +7,13 @@ import { Truncate } from "../truncate/truncate"
import { useCallback, useState } from "react"
import { ConfirmModal } from "../confirm-modal/confirm-modal"
import { Link } from "react-router"
+import { StatusBadge } from "../status-badge/status-badge"
export type HistoryTableProps = {
- history: HistoryResponse
+ historySlots: HistorySlot[]
}
-export function HistoryTable({ history }: HistoryTableProps) {
+export function HistoryTable({ historySlots }: HistoryTableProps) {
return (
<PageTable responsive>
<thead>
@@ -25,7 +26,7 @@ export function HistoryTable({ history }: HistoryTableProps) {
</tr>
</thead>
<tbody>
- {history.slots.map(slot =>
+ {historySlots.map(slot =>
<HistoryRow slot={slot} key={slot.nzo_id} />
)}
</tbody>
diff --git a/frontend/app/routes/queue/components/page-table/page-table.module.css b/frontend/app/routes/queue/components/page-table/page-table.module.css
index 4597baf9..87dfd541 100644
--- a/frontend/app/routes/queue/components/page-table/page-table.module.css
+++ b/frontend/app/routes/queue/components/page-table/page-table.module.css
@@ -60,7 +60,7 @@
margin-bottom: 5px;
}
-.reappear div {
+.reappear > div {
margin-left: 5px;
}
diff --git a/frontend/app/routes/queue/components/queue-table/queue-table.module.css b/frontend/app/routes/queue/components/queue-table/queue-table.module.css
deleted file mode 100644
index 3fea6672..00000000
--- a/frontend/app/routes/queue/components/queue-table/queue-table.module.css
+++ /dev/null
@@ -1,5 +0,0 @@
-@media not (pointer: coarse), (min-width: 900px) {
- .failure-badge:hover {
- cursor: pointer;
- }
-}
\ No newline at end of file
diff --git a/frontend/app/routes/queue/components/queue-table/queue-table.module.css.d.ts b/frontend/app/routes/queue/components/queue-table/queue-table.module.css.d.ts
deleted file mode 100644
index 513489a3..00000000
--- a/frontend/app/routes/queue/components/queue-table/queue-table.module.css.d.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-declare const styles: {
- readonly "failure-badge": string;
-};
-export = styles;
-
diff --git a/frontend/app/routes/queue/components/queue-table/queue-table.tsx b/frontend/app/routes/queue/components/queue-table/queue-table.tsx
index 40e217f1..7f02bf9c 100644
--- a/frontend/app/routes/queue/components/queue-table/queue-table.tsx
+++ b/frontend/app/routes/queue/components/queue-table/queue-table.tsx
@@ -1,18 +1,18 @@
-import type { QueueResponse, QueueSlot } from "~/clients/backend-client.server"
-import styles from "./queue-table.module.css"
+import type { QueueSlot } from "~/clients/backend-client.server"
import tableStyles from "../page-table/page-table.module.css"
-import { Badge, OverlayTrigger, Tooltip } from "react-bootstrap"
+import { Badge } from "react-bootstrap"
import { ActionButton } from "../action-button/action-button"
import { PageTable } from "../page-table/page-table"
import { Truncate } from "../truncate/truncate"
import { useCallback, useState } from "react"
import { ConfirmModal } from "../confirm-modal/confirm-modal"
+import { StatusBadge } from "../status-badge/status-badge"
export type QueueTableProps = {
- queue: QueueResponse
+ queueSlots: QueueSlot[]
}
-export function QueueTable({ queue }: QueueTableProps) {
+export function QueueTable({ queueSlots }: QueueTableProps) {
return (
<PageTable responsive striped>
<thead>
@@ -25,7 +25,7 @@ export function QueueTable({ queue }: QueueTableProps) {
</tr>
</thead>
<tbody>
- {queue.slots.map(slot =>
+ {queueSlots.map(slot =>
<QueueRow slot={slot} key={slot.nzo_id} />
)}
</tbody>
@@ -76,7 +76,7 @@ export function QueueRow({ slot }: QueueRowProps) {
<td>
<Truncate>{slot.filename}</Truncate>
<div className={tableStyles.reappear}>
- <StatusBadge status={slot.status} />
+ <StatusBadge status={slot.status} percentage={slot.percentage} />
<CategoryBadge category={slot.cat} />
<div>{formatFileSize(Number(slot.mb) * 1024 * 1024)}</div>
</div>
@@ -85,7 +85,7 @@ export function QueueRow({ slot }: QueueRowProps) {
<CategoryBadge category={slot.cat} />
</td>
<td className={tableStyles.disappear}>
- <StatusBadge status={slot.status} />
+ <StatusBadge status={slot.status} percentage={slot.percentage} />
</td>
<td className={tableStyles.disappear}>
{formatFileSize(Number(slot.mb) * 1024 * 1024)}
@@ -112,25 +112,6 @@ export function CategoryBadge({ category }: { category: string }) {
return <Badge bg={variant} style={{ width: '85px' }}>{categoryLower}</Badge>
}
-export function StatusBadge({ status, error }: { status: string, error?: string }) {
- const statusLower = status?.toLowerCase();
- let variant = "secondary";
- if (statusLower === "completed") variant = "success";
- if (statusLower === "failed") variant = "danger";
- if (statusLower === "downloading") variant = "primary";
-
- if (error?.startsWith("Article with message-id")) error = "Missing articles";
- const badgeClass = statusLower === "failed" ? styles["failure-badge"] : "";
- const overlay = statusLower == "failed"
- ? <Tooltip>{error}</Tooltip>
- : <></>;
-
- return (
- <OverlayTrigger placement="top" overlay={overlay} trigger="click">
- <Badge bg={variant} className={badgeClass} style={{ width: '85px' }}>{statusLower}</Badge>
- </OverlayTrigger>
- );
-}
export function formatFileSize(bytes: number) {
var suffix = "B";
diff --git a/frontend/app/routes/queue/components/status-badge/status-badge.module.css b/frontend/app/routes/queue/components/status-badge/status-badge.module.css
new file mode 100644
index 00000000..1953969a
--- /dev/null
+++ b/frontend/app/routes/queue/components/status-badge/status-badge.module.css
@@ -0,0 +1,35 @@
+.badge {
+ display: inline-block;
+ line-height: 1;
+ border-radius: .375rem;
+ font-weight: 700;
+ font-size: .75em;
+ padding: .35em .65em;
+ color: #fff;
+ position: relative;
+ text-align: center;
+ vertical-align: bottom;
+ background-color: #222;
+ overflow: hidden;
+ width: 85px;
+}
+
+.badge-text {
+ position: relative;
+}
+
+.progress {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 0;
+ height: 100%;
+ background-color: rgba(var(--bs-primary-rgb));
+}
+
+@media not (pointer: coarse),
+(min-width: 900px) {
+ .failure-badge:hover {
+ cursor: pointer;
+ }
+}
\ No newline at end of file
diff --git a/frontend/app/routes/queue/components/status-badge/status-badge.module.css.d.ts b/frontend/app/routes/queue/components/status-badge/status-badge.module.css.d.ts
new file mode 100644
index 00000000..c6f46324
--- /dev/null
+++ b/frontend/app/routes/queue/components/status-badge/status-badge.module.css.d.ts
@@ -0,0 +1,8 @@
+declare const styles: {
+ readonly "badge": string;
+ readonly "badge-text": string;
+ readonly "progress": string;
+ readonly "failure-badge": string;
+};
+export = styles;
+
diff --git a/frontend/app/routes/queue/components/status-badge/status-badge.tsx b/frontend/app/routes/queue/components/status-badge/status-badge.tsx
new file mode 100644
index 00000000..e47afe34
--- /dev/null
+++ b/frontend/app/routes/queue/components/status-badge/status-badge.tsx
@@ -0,0 +1,59 @@
+import { OverlayTrigger, Tooltip } from "react-bootstrap";
+import styles from "./status-badge.module.css";
+import type React from "react";
+import { className } from "~/utils/styling";
+
+export type StatusBadgeProps = {
+ status: string,
+ percentage?: string,
+ error?: string,
+}
+
+
+export function StatusBadge({ status, percentage, error }: StatusBadgeProps) {
+ const statusLower = status?.toLowerCase();
+ const percentNum = Number(percentage);
+
+ // determine badge color
+ let color = "grey";
+ if (statusLower === "completed") color = "rgba(var(--bs-success-rgb)";
+ if (statusLower === "failed") color = "rgba(var(--bs-danger-rgb)";
+ if (statusLower === "downloading" || percentNum > 0) color = `#333`;
+
+ // determine badge text
+ let badgeText = statusLower;
+ if (statusLower === "downloading" || percentNum > 0) badgeText = `${percentNum}%`;
+
+ // determine class name
+ if (error?.startsWith("Article with message-id")) error = "Missing articles";
+ const badgeClass = statusLower === "failed" ? styles["failure-badge"] : "";
+ const overlay = statusLower == "failed"
+ ? <Tooltip>{error}</Tooltip>
+ : <></>;
+
+ return (
+ <OverlayTrigger placement="top" overlay={overlay} trigger="click">
+ <Badge className={badgeClass} color={color} percentNum={percentNum}>{badgeText}</Badge>
+ </OverlayTrigger>
+ );
+}
+
+type BadgeProps = {
+ className?: string,
+ color: string,
+ percentNum: number,
+ children?: React.ReactNode
+}
+
+function Badge(props: BadgeProps) {
+ let style = (props.percentNum >= 0)
+ ? { width: `${props.percentNum}%` }
+ : undefined;
+
+ return (
+ <div {...className([styles.badge, props.className])} style={{ backgroundColor: props.color }}>
+ <div className={styles.progress} style={style} />
+ <div className={styles["badge-text"]}>{props.children}</div>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/frontend/app/routes/queue/route.tsx b/frontend/app/routes/queue/route.tsx
index e94f3313..4aa4ac8d 100644
--- a/frontend/app/routes/queue/route.tsx
+++ b/frontend/app/routes/queue/route.tsx
@@ -3,14 +3,34 @@ import type { Route } from "./+types/route";
import { sessionStorage } from "~/auth/authentication.server";
import styles from "./route.module.css"
import { Alert } from 'react-bootstrap';
-import { backendClient, type HistoryResponse, type QueueResponse } from "~/clients/backend-client.server";
+import { backendClient, type HistorySlot, type QueueSlot } from "~/clients/backend-client.server";
import { EmptyQueue } from "./components/empty-queue/empty-queue";
import { HistoryTable } from "./components/history-table/history-table";
import { QueueTable } from "./components/queue-table/queue-table";
+import { useEffect, useState } from "react";
+import { receiveMessage } from "~/utils/websocket-util";
+
+const topicNames = {
+ queueItemStatus: 'qs',
+ queueItemPercentage: 'qp',
+ queueItemAdded: 'qa',
+ queueItemRemoved: 'qr',
+ historyItemAdded: 'ha',
+ historyItemRemoved: 'hr',
+}
+const topicSubscriptions = {
+ [topicNames.queueItemStatus]: 'state',
+ [topicNames.queueItemPercentage]: 'state',
+ [topicNames.queueItemAdded]: 'event',
+ [topicNames.queueItemRemoved]: 'event',
+ [topicNames.historyItemAdded]: 'event',
+ [topicNames.historyItemRemoved]: 'event',
+}
type BodyProps = {
- loaderData: { queue: QueueResponse, history: HistoryResponse },
- actionData: { error: string } | undefined
+ queueSlots: QueueSlot[],
+ historySlots: HistorySlot[],
+ error?: string,
};
export async function loader({ request }: Route.LoaderArgs) {
@@ -19,19 +39,79 @@ export async function loader({ request }: Route.LoaderArgs) {
var queue = await queuePromise;
var history = await historyPromise;
return {
- queue: queue,
- history: history,
+ queueSlots: queue?.slots || [],
+ historySlots: history?.slots || [],
}
}
export default function Queue(props: Route.ComponentProps) {
+ const [queueSlots, setQueueSlots] = useState(props.loaderData.queueSlots);
+ const [historySlots, setHistorySlots] = useState(props.loaderData.historySlots);
+ const error = props.actionData?.error;
+
+
+ useEffect(() => {
+ let ws: WebSocket;
+ let disposed = false;
+ function connect() {
+ ws = new WebSocket(window.location.origin.replace(/^http/, 'ws'));
+ ws.onmessage = receiveMessage(onMessage);
+ ws.onopen = () => { ws.send(JSON.stringify(topicSubscriptions)); }
+ ws.onclose = () => { !disposed && setTimeout(() => connect(), 1000); };
+ ws.onerror = () => { ws.close() };
+ return () => { disposed = true; ws.close(); }
+ }
+
+ function onMessage(topic: string, message: string) {
+ if (topic == topicNames.queueItemStatus)
+ onChangeQueueSlotStatus(message);
+ if (topic == topicNames.queueItemPercentage)
+ onChangeQueueSlotPercentage(message);
+ else if (topic == topicNames.queueItemAdded)
+ onAddQueueSlot(JSON.parse(message));
+ else if (topic == topicNames.queueItemRemoved)
+ onRemoveQueueSlot(message);
+ else if (topic == topicNames.historyItemAdded)
+ onAddHistorySlot(JSON.parse(message));
+ else if (topic == topicNames.historyItemRemoved)
+ onRemoveHistorySlot(message);
+ }
+
+ function onChangeQueueSlotStatus(message: string) {
+ const [nzo_id, status] = message.split('|');
+ setQueueSlots(slots => slots.map(x => x.nzo_id === nzo_id ? { ...x, status } : x))
+ }
+
+ function onChangeQueueSlotPercentage(message: string) {
+ const [nzo_id, percentage] = message.split('|');
+ setQueueSlots(slots => slots.map(x => x.nzo_id === nzo_id ? { ...x, percentage } : x))
+ }
+
+ function onAddQueueSlot(queueSlot: QueueSlot) {
+ setQueueSlots(slots => [...slots, queueSlot])
+ }
+
+ function onRemoveQueueSlot(id: string) {
+ setQueueSlots(slots => slots.filter(x => x.nzo_id !== id));
+ }
+
+ function onAddHistorySlot(historySlot: HistorySlot) {
+ setHistorySlots(slots => [historySlot, ...slots])
+ }
+
+ function onRemoveHistorySlot(id: string) {
+ setHistorySlots(slots => slots.filter(x => x.nzo_id !== id));
+ }
+
+ return connect();
+ }, [setQueueSlots, setHistorySlots]);
+
return (
- <Body loaderData={props.loaderData} actionData={props.actionData} />
+ <Body queueSlots={queueSlots} historySlots={historySlots} error={error} />
);
}
-function Body({ loaderData, actionData }: BodyProps) {
- const { queue, history } = loaderData;
+function Body({ queueSlots, historySlots, error }: BodyProps) {
return (
<div className={styles.container}>
{/* queue */}
@@ -41,23 +121,23 @@ function Body({ loaderData, actionData }: BodyProps) {
</h3>
<div className={styles["section-body"]}>
{/* error message */}
- {actionData?.error &&
+ {error &&
<Alert variant="danger">
- {actionData?.error}
+ {error}
</Alert>
}
- {queue.slots.length > 0 ? <QueueTable queue={queue} /> : <EmptyQueue />}
+ {queueSlots.length > 0 ? <QueueTable queueSlots={queueSlots} /> : <EmptyQueue />}
</div>
</div>
{/* history */}
- {history?.slots?.length > 0 &&
+ {historySlots.length > 0 &&
<div className={styles.section}>
<h3 className={styles["section-title"]}>
History
</h3>
<div className={styles["section-body"]}>
- <HistoryTable history={history} />
+ <HistoryTable historySlots={historySlots} />
</div>
</div>
}
diff --git a/frontend/app/routes/settings/maintenance/maintenance.tsx b/frontend/app/routes/settings/maintenance/maintenance.tsx
index 906cf53e..820cee00 100644
--- a/frontend/app/routes/settings/maintenance/maintenance.tsx
+++ b/frontend/app/routes/settings/maintenance/maintenance.tsx
@@ -1,6 +1,9 @@
import { Alert, Button, Form } from "react-bootstrap";
import styles from "./maintenance.module.css"
import { useCallback, useEffect, useState } from "react";
+import { receiveMessage } from "~/utils/websocket-util";
+
+const symlinksTaskTopic = { 'stp': 'state' };
type MaintenanceProps = {
savedConfig: Record<string, string>
@@ -32,14 +35,14 @@ export function Maintenance({ savedConfig }: MaintenanceProps) {
let disposed = false;
function connect() {
ws = new WebSocket(window.location.origin.replace(/^http/, 'ws'));
- ws.onmessage = (event) => setProgress(event.data);
- ws.onopen = () => { setConnected(true); ws.send('stp'); }
+ ws.onmessage = receiveMessage((_, message) => setProgress(message));
+ ws.onopen = () => { setConnected(true); ws.send(JSON.stringify(symlinksTaskTopic)); }
ws.onclose = () => { !disposed && setTimeout(() => connect(), 1000); setProgress(null) };
ws.onerror = () => { ws.close() };
return () => { disposed = true; ws.close(); }
}
return connect();
- }, [setProgress]);
+ }, [setProgress, setConnected]);
// events
const onRun = useCallback(async () => {
@@ -64,7 +67,7 @@ export function Maintenance({ savedConfig }: MaintenanceProps) {
}
{libraryDir &&
<Alert variant="danger">
- <span style={{fontWeight: 'bold'}}>Danger</span>
+ <span style={{ fontWeight: 'bold' }}>Danger</span>
<ul className={styles.list}>
<li className={styles["list-item"]}>
Make a backup of your organized media library
diff --git a/frontend/app/utils/websocket-util.ts b/frontend/app/utils/websocket-util.ts
new file mode 100644
index 00000000..23feb7b0
--- /dev/null
+++ b/frontend/app/utils/websocket-util.ts
@@ -0,0 +1,8 @@
+export function receiveMessage(
+ onMessage: (topic: string, message: string) => void
+): (event: MessageEvent) => void {
+ return (event) => {
+ var parsed = JSON.parse(event.data);
+ onMessage(parsed.Topic, parsed.Message);
+ }
+}
\ No newline at end of file
diff --git a/frontend/server/websocket.server.ts b/frontend/server/websocket.server.ts
index 8be13068..b3c8cae2 100644
--- a/frontend/server/websocket.server.ts
+++ b/frontend/server/websocket.server.ts
@@ -4,7 +4,7 @@ import type { IncomingMessage } from 'http';
function initializeWebsocketServer(wss: WebSocketServer) {
// keep track of socket subscriptions
- const websockets = new Map<WebSocket, string>();
+ const websockets = new Map<WebSocket, any>();
const subscriptions = new Map<string, Set<WebSocket>>();
const lastMessage = new Map<string, string>();
initializeWebsocketClient(subscriptions, lastMessage);
@@ -24,22 +24,32 @@ function initializeWebsocketServer(wss: WebSocketServer) {
// handle topic subscription
ws.onmessage = (event: WebSocket.MessageEvent) => {
- var topic = event.data.toString();
- websockets.set(ws, topic);
- var topicSubscriptions = subscriptions.get(topic);
- if (topicSubscriptions) topicSubscriptions.add(ws);
- else subscriptions.set(topic, new Set<WebSocket>([ws]));
- var messageToSend = lastMessage.get(topic);
- if (messageToSend) ws.send(messageToSend);
+ try {
+ var topics = JSON.parse(event.data.toString());
+ websockets.set(ws, topics);
+ for (const topic in topics) {
+ var topicSubscriptions = subscriptions.get(topic);
+ if (topicSubscriptions) topicSubscriptions.add(ws);
+ else subscriptions.set(topic, new Set<WebSocket>([ws]));
+ if (topics[topic] === 'state') {
+ var messageToSend = lastMessage.get(topic);
+ if (messageToSend) ws.send(messageToSend);
+ }
+ }
+ } catch {
+ ws.close(1003, "Could not process topic subscription. If recently updated, try refreshing the page.");
+ }
};
// unsubscribe from topics
ws.onclose = () => {
- var topic = websockets.get(ws);
- if (topic) {
+ var topics = websockets.get(ws);
+ if (topics) {
websockets.delete(ws);
- var topicSubscriptions = subscriptions.get(topic);
- if (topicSubscriptions) topicSubscriptions.delete(ws);
+ for (const topic in topics) {
+ var topicSubscriptions = subscriptions.get(topic);
+ if (topicSubscriptions) topicSubscriptions.delete(ws);
+ }
}
};
} catch (error) {
@@ -79,11 +89,11 @@ export function initializeWebsocketClient(subscriptions: Map<string, Set<WebSock
var topicMessage = JSON.parse(rawMessage);
var [topic, message] = [topicMessage.Topic, topicMessage.Message];
if (!topic || !message) return;
- lastMessage.set(topic, message);
+ lastMessage.set(topic, rawMessage);
var subscribed = subscriptions.get(topic) || [];
subscribed.forEach(client => {
if (client.readyState === client.OPEN) {
- client.send(message);
+ client.send(rawMessage);
}
});
};