nzbget, qbittorrent: full nox downloader modules (ADR 0044/0046)

nzbget (usenet, JSON-RPC) and qbittorrent (torrents, WebUI API with manual SID
session). Tools: status, queue/torrents, add, pause/resume, delete. Both poll
and emit module.<app>.download.added and module.<app>.download.completed — the
key plex consumes to rescan; completion is keyed off real success (nzbget
history SUCCESS, qbittorrent progress reaching 1), not mere queue disappearance,
so a failed or deleted item is not reported as done. Typecheck; manifests parse.
This commit is contained in:
2026-09-04 02:40:06 +02:00
parent d7ceb05e53
commit 1e2a849b90
12 changed files with 700 additions and 0 deletions
+170
View File
@@ -0,0 +1,170 @@
// The qBittorrent API client — qbittorrent's own code, living in the module (novox/hq ADR 0044).
// Written against the WebUI API (/api/v2/...), self-contained so a change to it rebuilds only
// qbittorrent. Both this module's tools and its events entrypoint import it, and nothing outside
// qbittorrent does.
//
// The WebUI authenticates with a session cookie (SID) obtained by POSTing credentials, and guards
// against CSRF by checking the Referer header. Node's fetch keeps no cookie jar, so the SID is
// captured on login and carried by hand on every later call, with a single re-login on expiry.
export interface QbTransferInfo {
dlSpeedBytesPerSec: number;
upSpeedBytesPerSec: number;
dlData: number;
upData: number;
connectionStatus: string;
}
export interface QbTorrent {
hash: string;
name: string;
/** qBittorrent's state, e.g. "downloading", "stalledUP", "uploading", "pausedUP", "error". */
state: string;
/** 0..1 — 1 means the download is complete. */
progress: number;
sizeBytes: number;
dlSpeed: number;
upSpeed: number;
category: string;
ratio: number;
savePath: string;
}
export class QbittorrentClient {
readonly baseUrl: string;
private sid: string | null = null;
constructor(
baseUrl: string,
private readonly user: string,
private readonly password: string,
) {
this.baseUrl = baseUrl.replace(/\/$/, "");
}
/**
* Build from the module's resolved environment. URL and password are read from
* MESH_QBITTORRENT_URL and MESH_QBITTORRENT_PASSWORD; both must be present — an unconfigured
* qBittorrent throws rather than pretend to be reachable, so the tools/events simply do not load
* (the harness treats the throw as "exposes nothing"). The user defaults to "admin".
*/
static fromEnv(env: NodeJS.ProcessEnv = process.env): QbittorrentClient {
const url = env.MESH_QBITTORRENT_URL;
const password = env.MESH_QBITTORRENT_PASSWORD;
if (!url || !password) {
throw new Error("qBittorrent not configured — set MESH_QBITTORRENT_URL and MESH_QBITTORRENT_PASSWORD");
}
const user = env.MESH_QBITTORRENT_USER ?? "admin";
return new QbittorrentClient(url, user, password);
}
private async login(): Promise<void> {
const res = await fetch(`${this.baseUrl}/api/v2/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded", Referer: this.baseUrl },
body: new URLSearchParams({ username: this.user, password: this.password }),
});
if (!res.ok) throw new Error(`qBittorrent login: ${res.status} ${await res.text()}`);
if ((await res.text()).trim() !== "Ok.") {
throw new Error("qBittorrent login rejected — check credentials");
}
const match = res.headers.get("set-cookie")?.match(/SID=([^;]+)/);
if (!match) throw new Error("qBittorrent login returned no SID cookie");
this.sid = match[1];
}
private async call(method: "GET" | "POST", path: string, form?: Record<string, string>): Promise<Response> {
if (!this.sid) await this.login();
const doFetch = (): Promise<Response> => {
const headers: Record<string, string> = { Referer: this.baseUrl, Cookie: `SID=${this.sid}` };
const init: RequestInit = { method, headers };
if (form) {
headers["Content-Type"] = "application/x-www-form-urlencoded";
init.body = new URLSearchParams(form);
}
return fetch(`${this.baseUrl}/api/v2/${path}`, init);
};
let res = await doFetch();
if (res.status === 403) {
// The SID expired — re-authenticate once and retry, rather than fail a routine call.
await this.login();
res = await doFetch();
}
return res;
}
private async getJson<T>(path: string): Promise<T> {
const res = await this.call("GET", path);
if (!res.ok) throw new Error(`qBittorrent GET ${path}: ${res.status} ${await res.text()}`);
return (await res.json()) as T;
}
async getVersion(): Promise<string> {
const res = await this.call("GET", "app/version");
if (!res.ok) throw new Error(`qBittorrent app/version: ${res.status}`);
return (await res.text()).trim();
}
async getTransferInfo(): Promise<QbTransferInfo> {
const d = await this.getJson<Record<string, any>>("transfer/info");
return {
dlSpeedBytesPerSec: Number(d.dl_info_speed ?? 0),
upSpeedBytesPerSec: Number(d.up_info_speed ?? 0),
dlData: Number(d.dl_info_data ?? 0),
upData: Number(d.up_info_data ?? 0),
connectionStatus: String(d.connection_status ?? "unknown"),
};
}
async getTorrents(filter?: string): Promise<QbTorrent[]> {
const path = filter ? `torrents/info?filter=${encodeURIComponent(filter)}` : "torrents/info";
const list = await this.getJson<Record<string, any>[]>(path);
return list.map((t) => ({
hash: String(t.hash),
name: String(t.name ?? "Unknown"),
state: String(t.state ?? "unknown"),
progress: Number(t.progress ?? 0),
sizeBytes: Number(t.size ?? 0),
dlSpeed: Number(t.dlspeed ?? 0),
upSpeed: Number(t.upspeed ?? 0),
category: String(t.category ?? ""),
ratio: Number(t.ratio ?? 0),
savePath: String(t.save_path ?? ""),
}));
}
/** Add a torrent by magnet or http(s) .torrent URL, optionally into a category / save path. */
async add(url: string, category = "", savepath = "", paused = false): Promise<void> {
const form: Record<string, string> = { urls: url, paused: paused ? "true" : "false" };
if (category) form.category = category;
if (savepath) form.savepath = savepath;
const res = await this.call("POST", "torrents/add", form);
const text = (await res.text()).trim();
if (!res.ok || text.toLowerCase() === "fails.") {
throw new Error(`qBittorrent refused the torrent: ${res.status} ${text}`);
}
}
// qBittorrent 5.x renamed pause/resume to stop/start; try the modern name and fall back to the
// legacy one on a 404, so the client works against both.
private async command(modern: string, legacy: string, hashes: string): Promise<void> {
let res = await this.call("POST", `torrents/${modern}`, { hashes });
if (res.status === 404) res = await this.call("POST", `torrents/${legacy}`, { hashes });
if (!res.ok) throw new Error(`qBittorrent torrents/${modern}: ${res.status} ${await res.text()}`);
}
/** Pause torrents — a pipe-separated hash list, or "all" (the default). */
async pause(hashes = "all"): Promise<void> {
await this.command("stop", "pause", hashes);
}
/** Resume torrents — a pipe-separated hash list, or "all" (the default). */
async resume(hashes = "all"): Promise<void> {
await this.command("start", "resume", hashes);
}
async delete(hashes: string, deleteFiles = false): Promise<void> {
const res = await this.call("POST", "torrents/delete", { hashes, deleteFiles: deleteFiles ? "true" : "false" });
if (!res.ok) throw new Error(`qBittorrent torrents/delete: ${res.status} ${await res.text()}`);
}
}
+52
View File
@@ -0,0 +1,52 @@
// qbittorrent's events. The tool runtime imports this once the broker is bound. It watches the
// torrent list and turns its comings and goings into mesh events.
//
// Emits (novox/hq ADR 0046/0047):
// module.qbittorrent.download.added — a torrent was added
// module.qbittorrent.download.completed — a torrent finished downloading (progress reached 1).
// This exact routing key is what the plex module
// consumes (module.*.download.completed) to rescan, so
// the new file becomes a visible item.
// Consumes: none.
//
// The torrent list is polled and diffed by hash, primed silently on the first look (like plex's and
// sonarr's index.ts) so a restart does not re-announce everything already present. Completion is a
// progress crossing from below 1 to exactly 1 — a torrent added already-complete is announced only
// as added, never as freshly completed, since nothing was downloaded.
import { emit } from "@novox/mesh-sdk/events";
import { QbittorrentClient } from "./client.js";
const qb = QbittorrentClient.fromEnv();
const progressByHash = new Map<string, number>();
let primed = false;
async function pollTorrents(): Promise<void> {
const torrents = await qb.getTorrents();
const now = new Map(torrents.map((t) => [t.hash, t]));
if (primed) {
for (const [hash, t] of now) {
const before = progressByHash.get(hash);
if (before === undefined) {
await emit("module.qbittorrent.download.added", { name: t.name, category: t.category, sizeBytes: t.sizeBytes });
} else if (before < 1 && t.progress >= 1) {
await emit("module.qbittorrent.download.completed", { name: t.name, category: t.category, sizeBytes: t.sizeBytes });
}
}
}
progressByHash.clear();
for (const [hash, t] of now) progressByHash.set(hash, t.progress);
primed = true;
}
const tick = (fn: () => Promise<void>, everyMs: number): void => {
const run = (): void => void fn().catch((err) => console.error(`[qbittorrent] ${err}`));
setInterval(run, everyMs);
run();
};
tick(pollTorrents, 20_000);
console.log("[qbittorrent] watching torrents, emitting adds and completions");
+8
View File
@@ -4,6 +4,14 @@
"capabilities": [
"container-runtime"
],
"emits": [
"module.qbittorrent.download.added",
"module.qbittorrent.download.completed"
],
"consumes": [],
"own-secrets": {
"broker": "/var/lib/qbittorrent/broker"
},
"listens": [
{
"port": 8080,
+14
View File
@@ -0,0 +1,14 @@
{
"name": "@novox/module-qbittorrent",
"version": "0.1.0",
"description": "qbittorrent — BitTorrent download client. Its API client, tools and events live here (novox/hq ADR 0044).",
"type": "module",
"private": true,
"dependencies": {
"@novox/mesh-sdk": "^0.1.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"typescript": "^5.6.0"
}
}
+98
View File
@@ -0,0 +1,98 @@
// qbittorrent's tools — living in the module (novox/hq ADR 0044), importing qbittorrent's own
// client. They return structured data; the mesh serves them through the sdk's tool harness.
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
import { QbittorrentClient } from "../client.js";
export function getQbittorrentTools(qb: QbittorrentClient): ToolDefinition[] {
return [
{
name: "qbittorrent_status",
description: "qBittorrent status: version, global transfer rates, and how many torrents are active.",
input: {},
run: async () => {
const [version, transfer, torrents] = await Promise.all([
qb.getVersion(),
qb.getTransferInfo(),
qb.getTorrents(),
]);
const downloading = torrents.filter((t) => t.progress < 1).length;
return { version, transfer, torrents: torrents.length, downloading, seeding: torrents.length - downloading };
},
},
{
name: "qbittorrent_torrents",
description: "List torrents — name, state, progress and speed. Optional filter narrows the set.",
input: {
filter: { type: "string", description: "one of all|downloading|seeding|completed|paused|active|inactive|stalled" },
},
run: async (args) => {
const items = await qb.getTorrents(args.filter ? String(args.filter) : undefined);
return { count: items.length, torrents: items };
},
},
{
name: "qbittorrent_add",
description: "Add a torrent by magnet link or .torrent URL, optionally into a category.",
input: {
url: { type: "string", description: "magnet link or http(s) URL to a .torrent" },
category: { type: "string", description: "category name (determines save directory)" },
savepath: { type: "string", description: "explicit save path (overrides the category default)" },
paused: { type: "boolean", description: "add in paused state (default false)" },
},
run: async (args) => {
await qb.add(
String(args.url),
args.category ? String(args.category) : "",
args.savepath ? String(args.savepath) : "",
args.paused === true || args.paused === "true",
);
return { added: String(args.url), category: args.category ? String(args.category) : null };
},
},
{
name: "qbittorrent_pause",
description: "Pause torrents — a pipe-separated hash list, or 'all' (the default).",
input: { hashes: { type: "string", description: "pipe-separated torrent hashes, or 'all' (default)" } },
run: async (args) => {
const hashes = args.hashes ? String(args.hashes) : "all";
await qb.pause(hashes);
return { paused: hashes };
},
},
{
name: "qbittorrent_resume",
description: "Resume torrents — a pipe-separated hash list, or 'all' (the default).",
input: { hashes: { type: "string", description: "pipe-separated torrent hashes, or 'all' (default)" } },
run: async (args) => {
const hashes = args.hashes ? String(args.hashes) : "all";
await qb.resume(hashes);
return { resumed: hashes };
},
},
{
name: "qbittorrent_delete",
description: "Remove torrents by hash, optionally deleting their files on disk.",
input: {
hashes: { type: "string", description: "pipe-separated torrent hashes, or 'all'" },
deleteFiles: { type: "boolean", description: "also delete downloaded files (default false)" },
},
run: async (args) => {
const hashes = String(args.hashes);
const deleteFiles = args.deleteFiles === true || args.deleteFiles === "true";
await qb.delete(hashes, deleteFiles);
return { deleted: hashes, deleteFiles };
},
},
];
}
// The tools exist only when qBittorrent is configured; without a URL and password, qbittorrent
// contributes none rather than failing the whole runtime.
registerModuleTools("qbittorrent", (env) => {
try {
return getQbittorrentTools(QbittorrentClient.fromEnv(env));
} catch {
return [];
}
});
+12
View File
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"noEmit": true
},
"include": ["client.ts", "index.ts", "tools/index.ts"]
}